Merge prep-period-saved: periods, saved preparations, game links
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run
CI / macos-build (push) Waiting to run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 22:05:45 +03:00
commit 6f61234ac6
16 changed files with 2165 additions and 57 deletions

View file

@ -4,6 +4,17 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
## [Unreleased]
- Preparing against an opponent: choose which of his games — all, the last 3 or 6
months, a year or two (counted back from his newest game), or his last 50, 100 or 200
games of each colour; every choice shows how many games it takes. Games without a date
are taken only with all games, and the report says how many were left out.
- Saved preparations: «★ Save» keeps a preparation with the errors found; «🗐
Preparations» in the library opens, renames and deletes them. New games of the
database are added when it is opened again, and the engine looks only at what is new.
- A game downloaded from Lichess or Chess.com opens on the site: the globe after the
result, the ☰ menu or the game list's menu. A Lichess game opens at the move shown,
from the side at the bottom of the board.
## [2.1.2] — 2026-10-31
- The game review runs on your own Stockfish when it is the same Stockfish 19 as

View file

@ -286,6 +286,11 @@ pub struct App {
/// between the library and the game (opponent-prep.md §3.1).
prep_dialog: Option<PrepDialog>,
prep: Option<PrepScreen>,
/// The library's «Preparations» window, and a saved preparation waiting for its
/// database to be read.
prep_list: Option<crate::prep_ui::PrepList>,
/// The names of its player, found again in the database once it is read.
prep_waiting: Option<(crate::prep_ui::PrepStart, Vec<String>)>,
/// Quitting while the opening errors are searched: asked first; «Quit» answered.
prep_quit_ask: bool,
prep_quit_ok: bool,
@ -511,6 +516,8 @@ impl App {
reference: Default::default(),
prep_dialog: None,
prep: None,
prep_list: None,
prep_waiting: None,
prep_quit_ask: false,
prep_quit_ok: false,
engine_offer: crate::engine_offer::EngineOffer::new(),
@ -758,6 +765,11 @@ impl App {
};
self.prep_dialog = Some(PrepDialog::new(path, entry));
}
// `CP_PREP_LIST=1`: the «Preparations» window at the start (screenshots).
if self.prep_list.is_none() && std::env::var_os("CP_PREP_LIST").is_some() {
static SHOWN: std::sync::Once = std::sync::Once::new();
SHOWN.call_once(|| self.prep_list = Some(crate::prep_ui::PrepList::new()));
}
let Some(index) = self.debug.open else { return };
let Some(path) = self.settings.databases.first().cloned() else {
return;
@ -928,6 +940,96 @@ impl App {
}
}
/// «🗐 Preparations», and a saved preparation opened once its database is read.
fn prep_list(&mut self, ctx: &egui::Context) {
if let Some((mut start, names)) = self.prep_waiting.take() {
if let Some(db) = self.library.database(&start.path) {
// The player by his names: the database's ids of them may have changed.
let mut ids = Vec::new();
let mut missing = None;
for name in &names {
// Every id of the name (a ChessBase database can have two).
let (found, _) = prep::candidates(&db, name, 50);
let before = ids.len();
ids.extend(found.iter().filter(|c| c.name == *name).map(|c| c.id));
if ids.len() == before {
missing = Some(name.clone());
}
}
match missing {
Some(name) => self.toast(
ctx,
trf(
"The player is not in the database: {name}",
&[("name", &name)],
),
),
None => {
start.player = prep::Player::new(ids);
self.open_prep(ctx, start);
}
}
} else if let Some(e) = self.library.failure(&start.path) {
let e = e.to_owned();
self.toast(
ctx,
trf("This database cannot be opened: {e}", &[("e", &e)]),
);
} else {
self.prep_waiting = Some((start, names));
}
}
let Some(list) = self.prep_list.as_mut() else {
return;
};
let can_new = !self.settings.databases.is_empty();
match list.show(ctx, can_new) {
Some(crate::prep_ui::ListOutcome::Close) => self.prep_list = None,
Some(crate::prep_ui::ListOutcome::New) => {
self.prep_list = None;
let (path, entry) = match self.library.prep_entry() {
Some((path, entry)) => (path, entry.unwrap_or_default()),
None => match self.settings.databases.first() {
Some(p) => (p.clone(), Default::default()),
None => return,
},
};
self.prep_dialog = Some(PrepDialog::new(path, entry));
}
Some(crate::prep_ui::ListOutcome::Open(id)) => {
let Some(meta) = crate::prep_saved::dir()
.as_deref()
.and_then(|d| crate::prep_saved::get(d, &id))
else {
return;
};
self.prep_list = None;
if !self.settings.databases.contains(&meta.path) {
self.settings.touch_database(&meta.path);
self.settings_dirty = true;
}
let dbs = self.shelf_dbs();
let start = crate::prep_ui::PrepStart {
book: crate::prep_ui::BookChoice::from_setting(
Some(&meta.book),
&meta.path,
&dbs,
),
path: meta.path,
player: meta.player,
side: meta.color,
};
if self.library.database(&start.path).is_none() {
self.library.load(&start.path, ctx);
self.toast(ctx, tr("Opening the database…"));
}
self.prep_waiting = Some((start, meta.names));
ctx.request_repaint();
}
None => {}
}
}
/// The preparation's dialog, when it is open.
fn prep_dialog(&mut self, ctx: &egui::Context) {
if self.prep_dialog.is_none() {
@ -3942,6 +4044,9 @@ impl eframe::App for App {
LibraryAction::PrepareAgainst { path, entry } => {
self.prep_dialog = Some(PrepDialog::new(path, entry));
}
LibraryAction::Preparations => {
self.prep_list = Some(crate::prep_ui::PrepList::new());
}
}
}
}
@ -4020,6 +4125,7 @@ impl eframe::App for App {
self.confirm_dialog(&ctx);
self.own_dialogs(&ctx);
self.prep_list(&ctx);
self.prep_dialog(&ctx);
self.prep_quit_question(&ctx);
// Whether the database the dialog names is there, as last found.

View file

@ -0,0 +1,133 @@
//! The game's page on the site it was played on: Lichess writes it in the Site tag
//! («https://lichess.org/AbCdEfGh»), Chess.com in the Link tag (its Site is
//! «Chess.com»). A Lichess game opens at the move shown and from the side at the
//! bottom of the board; Chess.com's page has no such address, it opens at the start.
use crate::i18n::tr;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Site {
Lichess,
ChessCom,
/// Another web address.
Other,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GameLink {
pub url: String,
pub site: Site,
/// The Lichess game id (8 characters), when the address is a game's.
lichess_id: Option<String>,
}
/// The game's web address from its tags (Link first, then Site), if it has one.
pub fn of(tag: impl Fn(&str) -> Option<String>) -> Option<GameLink> {
let url = ["Link", "Site"]
.into_iter()
.filter_map(&tag)
.map(|v| v.trim().to_owned())
.find(|v| v.starts_with("https://") || v.starts_with("http://"))?;
let host_and_path = url.split_once("://").map_or("", |(_, rest)| rest);
let (host, path) = host_and_path.split_once('/').unwrap_or((host_and_path, ""));
let host = host.to_ascii_lowercase();
let host = host.strip_prefix("www.").unwrap_or(&host);
let site = match host {
"lichess.org" => Site::Lichess,
"chess.com" => Site::ChessCom,
_ => Site::Other,
};
// «AbCdEfGh», or the 12-character id of one player's view of it.
let first = path.split(['/', '#', '?']).next().unwrap_or("");
let lichess_id = (site == Site::Lichess
&& (first.len() == 8 || first.len() == 12)
&& first.chars().all(|c| c.is_ascii_alphanumeric()))
.then(|| first[..8].to_owned());
Some(GameLink {
url,
site,
lichess_id,
})
}
impl GameLink {
/// The address to open: a Lichess game at half-move `ply` (0: the start) from
/// Black's side when `black`; any other as written.
pub fn at(&self, ply: u32, black: bool) -> String {
match &self.lichess_id {
Some(id) => {
let mut url = format!("https://lichess.org/{id}");
if black {
url.push_str("/black");
}
if ply > 0 {
url.push_str(&format!("#{ply}"));
}
url
}
None => self.url.clone(),
}
}
/// The globe's tooltip: «Open on Lichess (in the browser, at this move)».
pub fn hint(&self) -> &'static str {
match (self.site, self.lichess_id.is_some()) {
(Site::Lichess, true) => tr("Open on Lichess (in the browser, at this move)"),
(Site::Lichess, false) => tr("Open on Lichess (in the browser)"),
(Site::ChessCom, _) => tr("Open on Chess.com (in the browser)"),
(Site::Other, _) => tr("Open the game's link (in the browser)"),
}
}
/// «🌐 Open on Lichess».
pub fn label(&self) -> &'static str {
match self.site {
Site::Lichess => tr("🌐 Open on Lichess"),
Site::ChessCom => tr("🌐 Open on Chess.com"),
Site::Other => tr("🌐 Open the game's link"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn link(tags: &[(&str, &str)]) -> Option<GameLink> {
of(|name| {
tags.iter()
.find(|(n, _)| *n == name)
.map(|(_, v)| (*v).to_owned())
})
}
#[test]
fn lichess_chess_com_and_others() {
let l = link(&[("Site", "https://lichess.org/AbCdEfGh")]).expect("lichess");
assert_eq!(l.site, Site::Lichess);
assert_eq!(l.at(0, false), "https://lichess.org/AbCdEfGh");
assert_eq!(l.at(23, true), "https://lichess.org/AbCdEfGh/black#23");
// One player's view (12 characters): the game.
let l = link(&[("Site", "https://lichess.org/AbCdEfGh1234")]).unwrap();
assert_eq!(l.at(4, false), "https://lichess.org/AbCdEfGh#4");
// A study is opened as it is.
let s = link(&[("Site", "https://lichess.org/study/abcdefgh/ijklmnop")]).unwrap();
assert_eq!(
s.at(10, true),
"https://lichess.org/study/abcdefgh/ijklmnop"
);
let c = link(&[
("Site", "Chess.com"),
("Link", "https://www.chess.com/game/live/123456789"),
])
.expect("chess.com");
assert_eq!(c.site, Site::ChessCom);
assert_eq!(c.at(12, true), "https://www.chess.com/game/live/123456789");
assert_eq!(
link(&[("Site", "http://example.org/g/1")]).unwrap().site,
Site::Other
);
assert!(link(&[("Site", "Moscow RUS")]).is_none());
assert!(link(&[("Site", "Chess.com")]).is_none());
}
}

View file

@ -328,6 +328,17 @@ impl GameView {
}
}
/// The game's web page, if its tags have one.
fn link(&self) -> Option<crate::game_link::GameLink> {
crate::game_link::of(|t| self.game.tag(t).map(str::to_owned))
}
/// Opens the game's page at the move shown, from the side at the bottom.
fn open_link(&self, ctx: &egui::Context, link: &crate::game_link::GameLink) {
let ply = self.game.node(self.cursor).map_or(0, |n| n.ply());
ctx.open_url(egui::OpenUrl::new_tab(link.at(ply, self.flipped)));
}
fn subtitle(&self) -> String {
if let Some(t) = &self.train {
let up_to = trf(
@ -344,7 +355,10 @@ impl GameView {
for t in ["Event", "Site", "Date", "ECO", "Annotator"] {
if let Some(v) = g
.tag(t)
.filter(|v| !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.'))
// A web address is the globe's, not text.
.filter(|v| {
!v.is_empty() && !v.chars().all(|c| c == '?' || c == '.') && !v.contains("://")
})
{
parts.push(v.to_string());
}
@ -1020,17 +1034,34 @@ impl GameView {
None => (None, ""),
},
};
let result_w = result.as_ref().map_or(0.0, |r| {
// The game's page on Lichess or Chess.com: a globe after the result.
let link = self.link();
let link_w = if link.is_some() {
ui.painter()
.layout_no_wrap(
format!(" {r} "),
egui::FontId::proportional(15.0),
"🌐".to_owned(),
egui::TextStyle::Button.resolve(ui.style()),
Color32::WHITE,
)
.size()
.x
+ 2.0 * ui.spacing().button_padding.x
+ gap
});
} else {
0.0
};
let result_w = link_w
+ result.as_ref().map_or(0.0, |r| {
ui.painter()
.layout_no_wrap(
format!(" {r} "),
egui::FontId::proportional(15.0),
Color32::WHITE,
)
.size()
.x
+ gap
});
let row = ui.available_width();
let compact = row - left(false) - right(false) - result_w < 160.0;
let title_room = (row - left(compact) - right(compact)).max(0.0);
@ -1105,6 +1136,11 @@ impl GameView {
)
.on_hover_text(result_hint);
}
if let Some(l) = &link
&& ui.button("🌐").on_hover_text(l.hint()).clicked()
{
self.open_link(ui.ctx(), l);
}
});
let sub: Vec<String> = self
.source_line()
@ -1988,6 +2024,12 @@ impl GameView {
actions.push(GameAction::AddToDatabase);
ui.close();
}
if let Some(l) = self.link()
&& ui.button(l.label()).clicked()
{
self.open_link(ui.ctx(), &l);
ui.close();
}
ui.separator();
if ui.button(tr("Copy PGN")).clicked() {
actions.push(self.copy_pgn());

View file

@ -15623,6 +15623,549 @@ const ROWS: &[[&str; 9]] = &[
"Dvigatel bilan tahlil qilish",
"Қозғалтқышпен талдау",
],
[
"Last year",
"За год",
"La dernière année",
"Letztes Jahr",
"Último año",
"Ultimo anno",
"Último ano",
"Oxirgi yil",
"Соңғы жыл",
],
[
"Last 2 years",
"За 2 года",
"Les 2 dernières années",
"Letzte 2 Jahre",
"Últimos 2 años",
"Ultimi 2 anni",
"Últimos 2 anos",
"Oxirgi 2 yil",
"Соңғы 2 жыл",
],
[
"Last 3 months",
"За 3 месяца",
"Les 3 derniers mois",
"Letzte 3 Monate",
"Últimos 3 meses",
"Ultimi 3 mesi",
"Últimos 3 meses",
"Oxirgi 3 oy",
"Соңғы 3 ай",
],
[
"Last 6 months",
"За полгода",
"Les 6 derniers mois",
"Letzte 6 Monate",
"Últimos 6 meses",
"Ultimi 6 mesi",
"Últimos 6 meses",
"Oxirgi 6 oy",
"Соңғы 6 ай",
],
[
"Last {n} months",
"За {n} мес.",
"Les {n} derniers mois",
"Letzte {n} Monate",
"Últimos {n} meses",
"Ultimi {n} mesi",
"Últimos {n} meses",
"Oxirgi {n} oy",
"Соңғы {n} ай",
],
[
"Last {n} games",
"Последние {n} партий",
"Les {n} dernières parties",
"Letzte {n} Partien",
"Últimas {n} partidas",
"Ultime {n} partite",
"Últimas {n} partidas",
"Oxirgi {n} partiya",
"Соңғы {n} партия",
],
[
"The games have no dates: by number only",
"У партий нет дат: выбор только по числу",
"Les parties n’ont pas de date : par nombre seulement",
"Die Partien haben kein Datum: nur nach Anzahl",
"Las partidas no tienen fecha: solo por número",
"Le partite non hanno data: solo per numero",
"As partidas não têm data: só por número",
"Partiyalarda sana yo‘q: faqat soni bo‘yicha",
"Партиялардың күні жоқ: тек саны бойынша",
],
[
"Without a date: {n} — taken only with all games",
"Без даты: {n} — учитываются только во «Всех партиях»",
"Sans date : {n} — prises seulement avec toutes les parties",
"Ohne Datum: {n} — nur bei allen Partien berücksichtigt",
"Sin fecha: {n} — solo se cuentan con todas las partidas",
"Senza data: {n} — contate solo con tutte le partite",
"Sem data: {n} — contadas só com todas as partidas",
"Sanasiz: {n} — faqat «Barcha partiyalar»da hisoblanadi",
"Күнсіз: {n} — тек «Барлық партиялар» кезінде есептеледі",
],
[
"Which of his games: by date — counted back from his newest game; by number — the newest of each colour",
"Какие его партии брать: по времени — считая назад от его последней партии; по числу — самые свежие каждым цветом",
"Quelles parties prendre : par date — en remontant depuis sa dernière partie ; par nombre — les plus récentes de chaque couleur",
"Welche seiner Partien: nach Zeit — rückwärts ab seiner letzten Partie; nach Anzahl — die neuesten mit jeder Farbe",
"Qué partidas tomar: por fecha — contando hacia atrás desde su última partida; por número — las más recientes con cada color",
"Quali partite prendere: per data — a ritroso dalla sua ultima partita; per numero — le più recenti con ogni colore",
"Quais partidas usar: por data — contando para trás da sua última partida; por número — as mais recentes com cada cor",
"Qaysi partiyalarini olish: vaqt bo‘yicha — oxirgi partiyasidan orqaga sanab; soni bo‘yicha — har bir rangda eng yangilari",
"Қай партияларын алу: уақыт бойынша — соңғы партиясынан кері санап; саны бойынша — әр түспен ең жаңалары",
],
[
"★ Save",
"★ Сохранить",
"★ Enregistrer",
"★ Speichern",
"★ Guardar",
"★ Salva",
"★ Salvar",
"★ Saqlash",
"★ Сақтау",
],
[
"★ Saved",
"★ Сохранено",
"★ Enregistrée",
"★ Gespeichert",
"★ Guardada",
"★ Salvata",
"★ Salva",
"★ Saqlandi",
"★ Сақталды",
],
[
"Kept in the library's «Preparations»: changes are saved by themselves",
"Лежит в «Подготовках» библиотеки: изменения сохраняются сами",
"Rangée dans « Préparations » de la bibliothèque : les changements s’enregistrent d’eux-mêmes",
"In den «Vorbereitungen» der Bibliothek: Änderungen werden von selbst gespeichert",
"Está en «Preparaciones» de la biblioteca: los cambios se guardan solos",
"Si trova in «Preparazioni» della libreria: le modifiche si salvano da sole",
"Está em «Preparações» da biblioteca: as mudanças são salvas sozinhas",
"Kutubxonaning «Tayyorgarliklar» bo‘limida: o‘zgarishlar o‘zi saqlanadi",
"Кітапхананың «Дайындықтар» бөлімінде: өзгерістер өздігінен сақталады",
],
[
"Keep this preparation with the errors found: the library's «Preparations» opens it again",
"Сохранить подготовку вместе с найденными ошибками: её можно снова открыть в «Подготовках» библиотеки",
"Garder cette préparation avec les erreurs trouvées : « Préparations » de la bibliothèque la rouvre",
"Diese Vorbereitung mit den gefundenen Fehlern behalten: die «Vorbereitungen» der Bibliothek öffnen sie wieder",
"Guardar esta preparación con los errores encontrados: «Preparaciones» de la biblioteca la vuelve a abrir",
"Conserva questa preparazione con gli errori trovati: «Preparazioni» della libreria la riapre",
"Guardar esta preparação com os erros encontrados: «Preparações» da biblioteca a abre de novo",
"Tayyorgarlikni topilgan xatolar bilan saqlash: uni kutubxonaning «Tayyorgarliklar» bo‘limida qayta ochish mumkin",
"Дайындықты табылған қателермен сақтау: оны кітапхананың «Дайындықтар» бөлімінде қайта ашуға болады",
],
[
"Saved: the library's «Preparations» opens it",
"Сохранено: открыть можно в «Подготовках» библиотеки",
"Enregistrée : « Préparations » de la bibliothèque l’ouvre",
"Gespeichert: die «Vorbereitungen» der Bibliothek öffnen sie",
"Guardada: se abre en «Preparaciones» de la biblioteca",
"Salvata: si apre da «Preparazioni» della libreria",
"Salva: abra em «Preparações» da biblioteca",
"Saqlandi: kutubxonaning «Tayyorgarliklar» bo‘limida ochiladi",
"Сақталды: кітапхананың «Дайындықтар» бөлімінде ашылады",
],
[
"Could not save: {e}",
"Не удалось сохранить: {e}",
"Impossible d’enregistrer : {e}",
"Speichern fehlgeschlagen: {e}",
"No se pudo guardar: {e}",
"Impossibile salvare: {e}",
"Não foi possível salvar: {e}",
"Saqlab bo‘lmadi: {e}",
"Сақтау мүмкін болмады: {e}",
],
[
"Preparations",
"Подготовки",
"Préparations",
"Vorbereitungen",
"Preparaciones",
"Preparazioni",
"Preparações",
"Tayyorgarliklar",
"Дайындықтар",
],
[
"🗐 Preparations",
"🗐 Подготовки",
"🗐 Préparations",
"🗐 Vorbereitungen",
"🗐 Preparaciones",
"🗐 Preparazioni",
"🗐 Preparações",
"🗐 Tayyorgarliklar",
"🗐 Дайындықтар",
],
[
"Preparations against opponents: the saved ones and a new one",
"Подготовки к соперникам: сохранённые и новая",
"Préparations contre des adversaires : les enregistrées et une nouvelle",
"Vorbereitungen auf Gegner: die gespeicherten und eine neue",
"Preparaciones contra rivales: las guardadas y una nueva",
"Preparazioni contro avversari: quelle salvate e una nuova",
"Preparações contra adversários: as salvas e uma nova",
"Raqiblarga tayyorgarliklar: saqlanganlari va yangisi",
"Қарсыластарға дайындықтар: сақталғандары және жаңасы",
],
[
"Nothing saved yet. Prepare against a player and press «Save» on the report.",
"Пока ничего не сохранено. Подготовьтесь к игроку и нажмите «Сохранить» в отчёте.",
"Rien d’enregistré pour l’instant. Préparez-vous contre un joueur et appuyez sur « Enregistrer » dans le rapport.",
"Noch nichts gespeichert. Bereiten Sie sich auf einen Spieler vor und drücken Sie im Bericht «Speichern».",
"Aún no hay nada guardado. Prepárese contra un jugador y pulse «Guardar» en el informe.",
"Ancora niente di salvato. Preparati contro un giocatore e premi «Salva» nel rapporto.",
"Nada salvo ainda. Prepare-se contra um jogador e pressione «Salvar» no relatório.",
"Hali hech narsa saqlanmagan. O‘yinchiga tayyorlaning va hisobotda «Saqlash» tugmasini bosing.",
"Әзірге ештеңе сақталмаған. Ойыншыға дайындалып, есепте «Сақтау» түймесін басыңыз.",
],
[
"♟ New preparation…",
"♟ Новая подготовка…",
"♟ Nouvelle préparation…",
"♟ Neue Vorbereitung…",
"♟ Nueva preparación…",
"♟ Nuova preparazione…",
"♟ Nova preparação…",
"♟ Yangi tayyorgarlik…",
"♟ Жаңа дайындық…",
],
[
"Add a database to the shelf first",
"Сначала добавьте базу на полку",
"Ajoutez d’abord une base à l’étagère",
"Fügen Sie zuerst eine Datenbank zum Regal hinzu",
"Primero añada una base a la estantería",
"Aggiungi prima un database allo scaffale",
"Primeiro adicione uma base à estante",
"Avval javonga baza qo‘shing",
"Алдымен сөреге база қосыңыз",
],
[
"Choose a player in the current database",
"Выбрать игрока в текущей базе",
"Choisir un joueur dans la base actuelle",
"Einen Spieler in der aktuellen Datenbank wählen",
"Elegir un jugador en la base actual",
"Scegli un giocatore nel database attuale",
"Escolher um jogador na base atual",
"Joriy bazadan o‘yinchini tanlash",
"Ағымдағы базадан ойыншыны таңдау",
],
["OK", "ОК", "OK", "OK", "Aceptar", "OK", "OK", "OK", "ОК"],
[
"Delete?",
"Удалить?",
"Supprimer ?",
"Löschen?",
"¿Eliminar?",
"Eliminare?",
"Excluir?",
"O‘chirilsinmi?",
"Жою керек пе?",
],
[
"Rename",
"Переименовать",
"Renommer",
"Umbenennen",
"Renombrar",
"Rinomina",
"Renomear",
"Qayta nomlash",
"Атын өзгерту",
],
[
"errors: ?? {b} · ? {m} · ?! {i}",
"ошибки: ?? {b} · ? {m} · ?! {i}",
"erreurs : ?? {b} · ? {m} · ?! {i}",
"Fehler: ?? {b} · ? {m} · ?! {i}",
"errores: ?? {b} · ? {m} · ?! {i}",
"errori: ?? {b} · ? {m} · ?! {i}",
"erros: ?? {b} · ? {m} · ?! {i}",
"xatolar: ?? {b} · ? {m} · ?! {i}",
"қателер: ?? {b} · ? {m} · ?! {i}",
],
[
"errors not searched",
"ошибки ещё не искали",
"erreurs non cherchées",
"Fehler nicht gesucht",
"errores no buscados",
"errori non cercati",
"erros não procurados",
"xatolar qidirilmagan",
"қателер ізделмеген",
],
[
"saved {date}",
"сохранено {date}",
"enregistrée le {date}",
"gespeichert am {date}",
"guardada el {date}",
"salvata il {date}",
"salva em {date}",
"saqlangan: {date}",
"сақталған: {date}",
],
[
"database not found: {path}",
"база не найдена: {path}",
"base introuvable : {path}",
"Datenbank nicht gefunden: {path}",
"base no encontrada: {path}",
"database non trovato: {path}",
"base não encontrada: {path}",
"baza topilmadi: {path}",
"база табылмады: {path}",
],
[
"All",
"Все",
"Toutes",
"Alle",
"Todas",
"Tutte",
"Todas",
"Hammasi",
"Барлығы",
],
[
"1 yr", "1 год", "1 an", "1 J.", "1 año", "1 anno", "1 ano", "1 yil", "1 жыл",
],
[
"2 yrs",
"2 года",
"2 ans",
"2 J.",
"2 años",
"2 anni",
"2 anos",
"2 yil",
"2 жыл",
],
[
"{n} mo.",
"{n} мес.",
"{n} mois",
"{n} Mon.",
"{n} m.",
"{n} mesi",
"{n} m.",
"{n} oy",
"{n} ай",
],
[
"Last {n}",
"Посл. {n}",
"{n} dern.",
"Letzte {n}",
"Últ. {n}",
"Ult. {n}",
"Últ. {n}",
"Oxirgi {n}",
"Соңғы {n}",
],
[
"Counted back from his newest game — {date}",
"Считая от его последней партии — {date}",
"En remontant depuis sa dernière partie — {date}",
"Ab seiner letzten Partie gezählt — {date}",
"Contando desde su última partida — {date}",
"Contando dalla sua ultima partita — {date}",
"Contando a partir da sua última partida — {date}",
"Oxirgi partiyasidan sanaladi — {date}",
"Соңғы партиясынан бастап саналады — {date}",
],
[
"Without a date, not counted: {n} (only with all games)",
"Без даты не учтено: {n} (только во «Всех партиях»)",
"Sans date, non comptées : {n} (seulement avec toutes les parties)",
"Ohne Datum, nicht gezählt: {n} (nur bei allen Partien)",
"Sin fecha, no contadas: {n} (solo con todas las partidas)",
"Senza data, non contate: {n} (solo con tutte le partite)",
"Sem data, não contadas: {n} (só com todas as partidas)",
"Sanasiz, hisobga olinmagan: {n} (faqat «Barcha partiyalar»da)",
"Күнсіз, есепке алынбаған: {n} (тек «Барлық партиялар» кезінде)",
],
[
"No games in this period",
"За этот период партий нет",
"Aucune partie sur cette période",
"Keine Partien in diesem Zeitraum",
"No hay partidas en este periodo",
"Nessuna partita in questo periodo",
"Nenhuma partida neste período",
"Bu davrda partiyalar yo‘q",
"Бұл кезеңде партиялар жоқ",
],
[
"both colours",
"обоими цветами",
"des deux couleurs",
"mit beiden Farben",
"con ambos colores",
"con entrambi i colori",
"com ambas as cores",
"ikkala rangda",
"екі түспен",
],
[
"Double-click to open",
"Двойной щелчок — открыть",
"Double-clic pour ouvrir",
"Doppelklick zum Öffnen",
"Doble clic para abrir",
"Doppio clic per aprire",
"Clique duplo para abrir",
"Ochish uchun ikki marta bosing",
"Ашу үшін екі рет басыңыз",
],
[
"The database is not found: put the file back or delete the preparation",
"База не найдена: верните файл на место или удалите подготовку",
"Base introuvable : remettez le fichier en place ou supprimez la préparation",
"Datenbank nicht gefunden: Datei zurücklegen oder Vorbereitung löschen",
"Base no encontrada: devuelva el archivo a su sitio o elimine la preparación",
"Database non trovato: rimetti il file al suo posto o elimina la preparazione",
"Base não encontrada: devolva o arquivo ao lugar ou exclua a preparação",
"Baza topilmadi: faylni joyiga qaytaring yoki tayyorgarlikni o‘chiring",
"База табылмады: файлды орнына қайтарыңыз немесе дайындықты жойыңыз",
],
[
"The player is not in the database: {name}",
"Игрока нет в базе: {name}",
"Le joueur n’est pas dans la base : {name}",
"Der Spieler ist nicht in der Datenbank: {name}",
"El jugador no está en la base: {name}",
"Il giocatore non è nel database: {name}",
"O jogador não está na base: {name}",
"O‘yinchi bazada yo‘q: {name}",
"Ойыншы базада жоқ: {name}",
],
[
"No games as White in this period",
"Белыми за этот период партий нет",
"Aucune partie avec les Blancs sur cette période",
"Keine Partien mit Weiß in diesem Zeitraum",
"No hay partidas con blancas en este periodo",
"Nessuna partita con il Bianco in questo periodo",
"Nenhuma partida de brancas neste período",
"Bu davrda oqlar bilan partiyalar yo‘q",
"Бұл кезеңде ақтармен партиялар жоқ",
],
[
"No games as Black in this period",
"Чёрными за этот период партий нет",
"Aucune partie avec les Noirs sur cette période",
"Keine Partien mit Schwarz in diesem Zeitraum",
"No hay partidas con negras en este periodo",
"Nessuna partita con il Nero in questo periodo",
"Nenhuma partida de pretas neste período",
"Bu davrda qoralar bilan partiyalar yo‘q",
"Бұл кезеңде қаралармен партиялар жоқ",
],
[
"last {n}",
"последние {n}",
"les {n} dernières",
"letzte {n}",
"últimas {n}",
"ultime {n}",
"últimas {n}",
"oxirgi {n}",
"соңғы {n}",
],
[
"🌐 Open on Lichess",
"🌐 Открыть на Lichess",
"🌐 Ouvrir sur Lichess",
"🌐 Auf Lichess öffnen",
"🌐 Abrir en Lichess",
"🌐 Apri su Lichess",
"🌐 Abrir no Lichess",
"🌐 Lichess’da ochish",
"🌐 Lichess-те ашу",
],
[
"🌐 Open on Chess.com",
"🌐 Открыть на Chess.com",
"🌐 Ouvrir sur Chess.com",
"🌐 Auf Chess.com öffnen",
"🌐 Abrir en Chess.com",
"🌐 Apri su Chess.com",
"🌐 Abrir no Chess.com",
"🌐 Chess.com’da ochish",
"🌐 Chess.com-да ашу",
],
[
"🌐 Open the game's link",
"🌐 Открыть ссылку партии",
"🌐 Ouvrir le lien de la partie",
"🌐 Link der Partie öffnen",
"🌐 Abrir el enlace de la partida",
"🌐 Apri il link della partita",
"🌐 Abrir o link da partida",
"🌐 Partiya havolasini ochish",
"🌐 Партия сілтемесін ашу",
],
[
"Open on Lichess (in the browser, at this move)",
"Открыть на Lichess (в браузере, с этого хода)",
"Ouvrir sur Lichess (dans le navigateur, à ce coup)",
"Auf Lichess öffnen (im Browser, bei diesem Zug)",
"Abrir en Lichess (en el navegador, en esta jugada)",
"Apri su Lichess (nel browser, a questa mossa)",
"Abrir no Lichess (no navegador, neste lance)",
"Lichess’da ochish (brauzerda, shu yurishdan)",
"Lichess-те ашу (браузерде, осы жүрістен)",
],
[
"Open on Lichess (in the browser)",
"Открыть на Lichess (в браузере)",
"Ouvrir sur Lichess (dans le navigateur)",
"Auf Lichess öffnen (im Browser)",
"Abrir en Lichess (en el navegador)",
"Apri su Lichess (nel browser)",
"Abrir no Lichess (no navegador)",
"Lichess’da ochish (brauzerda)",
"Lichess-те ашу (браузерде)",
],
[
"Open on Chess.com (in the browser)",
"Открыть на Chess.com (в браузере)",
"Ouvrir sur Chess.com (dans le navigateur)",
"Auf Chess.com öffnen (im Browser)",
"Abrir en Chess.com (en el navegador)",
"Apri su Chess.com (nel browser)",
"Abrir no Chess.com (no navegador)",
"Chess.com’da ochish (brauzerda)",
"Chess.com-да ашу (браузерде)",
],
[
"Open the game's link (in the browser)",
"Открыть ссылку партии (в браузере)",
"Ouvrir le lien de la partie (dans le navigateur)",
"Link der Partie öffnen (im Browser)",
"Abrir el enlace de la partida (en el navegador)",
"Apri il link della partita (nel browser)",
"Abrir o link da partida (no navegador)",
"Partiya havolasini ochish (brauzerda)",
"Партия сілтемесін ашу (браузерде)",
],
];
#[cfg(test)]

View file

@ -341,6 +341,8 @@ pub struct LargeView {
/// «Prepare against…» was asked (the panel's button, a row's menu): the library
/// takes it (docs/design/opponent-prep.md §2.1).
pub prepare: Option<PrepEntry>,
/// The web page of the game whose context menu is open (its record, the link).
menu_link: Option<(usize, Option<crate::game_link::GameLink>)>,
}
impl LargeView {
@ -426,6 +428,7 @@ impl LargeView {
drawer_asked: false,
drawer_top: 0.0,
prepare: None,
menu_link: None,
}
}
@ -2260,6 +2263,19 @@ impl LargeView {
opened = Some(index);
ui.close();
}
// The game's page, when its tags have one (read once per menu).
if self.menu_link.as_ref().is_none_or(|(i, _)| *i != index) {
let link = db.load_game(index).and_then(|p| {
crate::game_link::of(|t| p.game.tag(t).map(str::to_owned))
});
self.menu_link = Some((index, link));
}
if let Some((_, Some(link))) = &self.menu_link
&& ui.button(link.label()).clicked()
{
ui.ctx().open_url(egui::OpenUrl::new_tab(link.at(0, false)));
ui.close();
}
// One item per player of the game (the same name once).
let mut players: Vec<&str> = vec![r.white.as_str(), r.black.as_str()];
players.dedup();

View file

@ -24,6 +24,7 @@ mod engine_offer;
mod engines;
mod examples;
mod file_state;
mod game_link;
mod game_view;
#[cfg(not(web))]
mod graphics;
@ -41,6 +42,7 @@ mod own_db;
pub mod platform;
mod play;
mod player_games;
mod prep_saved;
mod prep_ui;
mod reference;
mod review;

View file

@ -87,6 +87,8 @@ pub enum LibraryAction {
path: PathBuf,
index: usize,
},
/// «🗐 Preparations»: the saved preparations against opponents.
Preparations,
/// «Prepare against…» for a player of this database (opponent-prep.md §2).
PrepareAgainst {
path: PathBuf,
@ -148,11 +150,24 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 {
]
};
let play = crate::platform::CAPS.play;
let groups = if play { 2.0 } else { 1.0 };
let prep = crate::platform::CAPS.prep;
let groups = 1.0 + f32::from(u8::from(play)) + f32::from(u8::from(prep));
texts[..if play { 4 } else { 3 }]
.iter()
.map(|t| button_w(ui, t))
.sum::<f32>()
+ if prep {
button_w(
ui,
if icons {
"🗐"
} else {
tr("🗐 Preparations")
},
)
} else {
0.0
}
+ update.map_or(0.0, |v| button_w(ui, v))
+ groups * GROUP_GAP
}
@ -792,6 +807,25 @@ impl Library {
ui.separator();
self.play_button(ui, icons, actions);
}
if crate::platform::CAPS.prep {
ui.separator();
let label = if icons {
"🗐"
} else {
tr("🗐 Preparations")
};
if ui
.button(label)
.on_hover_text(shelf_hint(
icons,
tr("🗐 Preparations"),
tr("Preparations against opponents: the saved ones and a new one"),
))
.clicked()
{
actions.push(LibraryAction::Preparations);
}
}
}
/// "♞ Play": a game against Maia, a group of its own.

View file

@ -0,0 +1,210 @@
//! Saved preparations: a preparation against an opponent kept for good (not in the
//! cache) and opened again from «Preparations» in the library. One per player of a
//! database: saving the same player of the same database again replaces it. Each is
//! two files in `<data>/preparations/`: `<id>.json`, what the list shows, and
//! `<id>.report.json`, the report with the engine's evaluations (so the errors found
//! come back without the engine, even after the cache was cleared).
use std::path::{Path, PathBuf};
use prep::{ErrorCounts, Period, Player, PrepReport};
use serde::{Deserialize, Serialize};
use crate::prep_ui::ColorChoice;
/// What the list of preparations knows of one.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SavedPrep {
/// The name in the list (the player's at first; the user can rename it).
pub title: String,
/// The database.
pub path: PathBuf,
pub player: Player,
pub names: Vec<String>,
pub plies: usize,
pub period: Period,
pub color: ColorChoice,
/// The book as the setting keeps it (`BookChoice::setting`).
pub book: PathBuf,
/// Seconds since 1970, of the last save.
pub saved: u64,
/// The report's games and errors at that save.
pub games: u32,
pub errors: ErrorCounts,
/// The errors were searched (else the counts mean nothing).
pub evaluated: bool,
}
/// The folder of the saved preparations.
pub fn dir() -> Option<PathBuf> {
crate::platform::data_dir().map(|d| d.join("preparations"))
}
/// The id of the preparation of the player named `names` in the database `path`: by
/// the names, not the database's name ids, which change when a game before his first
/// one is deleted or the database is replaced by a new version.
pub fn id(path: &Path, names: &[String]) -> String {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
let mut eat = |b: u8| {
h ^= u64::from(b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
};
for b in path.to_string_lossy().bytes() {
eat(b);
}
let mut names: Vec<&String> = names.iter().collect();
names.sort();
names.dedup();
for n in names {
eat(0);
for b in n.bytes() {
eat(b);
}
}
format!("{h:016x}")
}
fn meta_path(dir: &Path, id: &str) -> PathBuf {
dir.join(format!("{id}.json"))
}
fn report_path(dir: &Path, id: &str) -> PathBuf {
dir.join(format!("{id}.report.json"))
}
/// Writes through a file beside it, so a crash leaves the old file or the new one.
fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, bytes)?;
std::fs::rename(&tmp, path)
}
/// Every saved preparation (id, what it is), the last saved first.
pub fn list(dir: &Path) -> Vec<(String, SavedPrep)> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut out: Vec<(String, SavedPrep)> = entries
.filter_map(|e| {
let path = e.ok()?.path();
let name = path.file_name()?.to_str()?;
let id = name.strip_suffix(".json")?;
if id.ends_with(".report") {
return None;
}
let meta = serde_json::from_slice(&std::fs::read(&path).ok()?).ok()?;
Some((id.to_owned(), meta))
})
.collect();
out.sort_by(|a, b| b.1.saved.cmp(&a.1.saved).then(a.1.title.cmp(&b.1.title)));
out
}
/// The preparation `id`, if saved.
pub fn get(dir: &Path, id: &str) -> Option<SavedPrep> {
serde_json::from_slice(&std::fs::read(meta_path(dir, id)).ok()?).ok()
}
/// Its report, if it can be read.
pub fn report(dir: &Path, id: &str) -> Option<PrepReport> {
serde_json::from_slice(&std::fs::read(report_path(dir, id)).ok()?).ok()
}
/// Keeps `meta` and `report` as the preparation of their player and database (the
/// report first: a list entry never points to a missing report).
pub fn save(dir: &Path, meta: &SavedPrep, report: &PrepReport) -> std::io::Result<()> {
let id = id(&meta.path, &meta.names);
let bytes = serde_json::to_vec(report).map_err(std::io::Error::other)?;
write_atomic(&report_path(dir, &id), &bytes)?;
let bytes = serde_json::to_vec_pretty(meta).map_err(std::io::Error::other)?;
write_atomic(&meta_path(dir, &id), &bytes)
}
/// A new name in the list.
pub fn rename(dir: &Path, id: &str, title: &str) -> std::io::Result<()> {
let mut meta = get(dir, id).ok_or_else(|| std::io::Error::other("no such preparation"))?;
meta.title = title.to_owned();
let bytes = serde_json::to_vec_pretty(&meta).map_err(std::io::Error::other)?;
write_atomic(&meta_path(dir, id), &bytes)
}
/// Removes the preparation (the list entry first).
pub fn delete(dir: &Path, id: &str) -> std::io::Result<()> {
std::fs::remove_file(meta_path(dir, id))?;
let _ = std::fs::remove_file(report_path(dir, id));
Ok(())
}
/// Seconds since 1970 now.
pub fn now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
#[cfg(test)]
mod tests {
use super::*;
fn meta(path: &str, ids: [u32; 1], title: &str, saved: u64) -> SavedPrep {
SavedPrep {
title: title.to_owned(),
path: PathBuf::from(path),
player: Player::new(ids),
names: vec![title.to_owned()],
plies: 20,
period: Period::Months(24),
color: ColorChoice::Black,
book: PathBuf::new(),
saved,
games: 3,
errors: ErrorCounts::default(),
evaluated: false,
}
}
#[test]
fn saved_listed_replaced_renamed_and_deleted() {
let dir = std::env::temp_dir().join(format!("cp-prep-saved-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
assert!(list(&dir).is_empty());
let report: PrepReport = serde_json::from_str(REPORT).expect("report");
let a = meta("/db/a.pgn", [7], "Вафин", 10);
let b = meta("/db/a.pgn", [8], "Иванов", 20);
save(&dir, &a, &report).expect("save");
save(&dir, &b, &report).expect("save");
let l = list(&dir);
assert_eq!(l.len(), 2);
assert_eq!(l[0].1.title, "Иванов", "the last saved first");
// The same player of the same database: replaced, not added.
let a2 = SavedPrep {
saved: 30,
plies: 30,
..a.clone()
};
save(&dir, &a2, &report).expect("save");
let l = list(&dir);
assert_eq!(l.len(), 2);
assert_eq!(l[0].1, a2);
let ida = id(&a.path, &a.names);
assert!(report_path(&dir, &ida).exists());
assert!(super::report(&dir, &ida).is_some());
rename(&dir, &ida, "Вафин — финал").expect("rename");
assert_eq!(get(&dir, &ida).unwrap().title, "Вафин — финал");
delete(&dir, &ida).expect("delete");
assert_eq!(list(&dir).len(), 1);
assert!(!report_path(&dir, &ida).exists());
let _ = std::fs::remove_dir_all(&dir);
}
const REPORT: &str = r#"{"version":4,"fingerprint":1,"player":{"ids":[7]},"names":["A"],
"plies":20,"side_white":true,"side_black":true,"games":[],"skipped":0,"openings":[],
"white":{"white":true,"games":[],"tree":{"nodes":[]},"families":[],"errors":[],
"repeated":[],"counts":{"inaccuracies":0,"mistakes":0,"blunders":0}},
"black":{"white":false,"games":[],"tree":{"nodes":[]},"families":[],"errors":[],
"repeated":[],"counts":{"inaccuracies":0,"mistakes":0,"blunders":0}},
"book":null,"engine":null,"evals":{}}"#;
}

View file

@ -17,8 +17,8 @@ use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2}
use egui_extras::{Column, TableBuilder};
use game_review::{JobEvent, JobSettings, Judgement};
use prep::{
BookExit, BookOptions, Candidate, ErrorCounts, GameInfo, Options, Player, PositionCache,
PrepReport, Tally,
BookExit, BookOptions, Candidate, ErrorCounts, GameInfo, Options, Period, Player,
PositionCache, PrepReport, Tally,
};
use serde::{Deserialize, Serialize};
use shakmaty::uci::UciMove;
@ -208,7 +208,7 @@ fn sort_col<K: Copy + PartialEq>(
}
/// The colour switch of the report.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ColorChoice {
White,
Black,
@ -216,7 +216,7 @@ pub enum ColorChoice {
}
impl ColorChoice {
fn side(self) -> Side {
pub fn side(self) -> Side {
match self {
ColorChoice::White => Side::White,
ColorChoice::Black => Side::Black,
@ -261,7 +261,7 @@ pub enum BookChoice {
impl BookChoice {
/// From the setting: an empty path is «none», the report's database «the same»,
/// `None` the largest database on the shelf but the report's.
fn from_setting(setting: Option<&Path>, own: &Path, dbs: &[RefDb]) -> BookChoice {
pub fn from_setting(setting: Option<&Path>, own: &Path, dbs: &[RefDb]) -> BookChoice {
match setting {
Some(p) if p.as_os_str().is_empty() => BookChoice::None,
Some(p) if p == own => BookChoice::Same,
@ -274,7 +274,7 @@ impl BookChoice {
}
}
fn setting(&self, own: &Path) -> PathBuf {
pub fn setting(&self, own: &Path) -> PathBuf {
match self {
BookChoice::None => PathBuf::new(),
BookChoice::Database(p) => p.clone(),
@ -367,6 +367,53 @@ pub struct PrepStart {
pub book: BookChoice,
}
// ----- the period ------------------------------------------------------------------
/// The periods offered, in the menu's order.
const PERIODS: [Period; 8] = [
Period::All,
Period::Months(3),
Period::Months(6),
Period::Months(12),
Period::Months(24),
Period::Last(50),
Period::Last(100),
Period::Last(200),
];
/// The period in a narrow row: «3 mo.», «Last 100».
fn period_short(p: Period) -> String {
match p {
Period::All => tr("All").to_owned(),
Period::Months(12) => tr("1 yr").to_owned(),
Period::Months(24) => tr("2 yrs").to_owned(),
Period::Months(m) => trf("{n} mo.", &[("n", &m)]),
Period::Last(n) => trf("Last {n}", &[("n", &n)]),
}
}
/// `yyyymmdd` as «18.10.2026», «10.2026», «2026».
fn shown_date(d: u32) -> String {
match (d / 10000, d / 100 % 100, d % 100) {
(0, ..) => String::new(),
(y, 0, _) => y.to_string(),
(y, m, 0) => format!("{m:02}.{y}"),
(y, m, day) => format!("{day:02}.{m:02}.{y}"),
}
}
fn period_label(p: Period) -> String {
match p {
Period::All => tr("All games").to_owned(),
Period::Months(12) => tr("Last year").to_owned(),
Period::Months(24) => tr("Last 2 years").to_owned(),
Period::Months(3) => tr("Last 3 months").to_owned(),
Period::Months(6) => tr("Last 6 months").to_owned(),
Period::Months(m) => trf("Last {n} months", &[("n", &m)]),
Period::Last(n) => trf("Last {n} games", &[("n", &n)]),
}
}
pub enum DialogOutcome {
Open(PrepStart),
Cancel,
@ -875,6 +922,281 @@ fn base_name(path: &Path) -> String {
.unwrap_or_default()
}
// ----- the saved preparations -----------------------------------------------------
/// What the «Preparations» window asks of the application.
pub enum ListOutcome {
/// The saved preparation of this id.
Open(String),
/// «New preparation…»: the dialog for the chosen database.
New,
Close,
}
/// The library's «Preparations»: the saved ones, to open, rename or delete.
pub struct PrepList {
items: Vec<(String, crate::prep_saved::SavedPrep)>,
/// The entry being renamed and the name typed.
renaming: Option<(String, String)>,
/// The entry asked about before deleting.
deleting: Option<String>,
error: Option<String>,
}
impl PrepList {
pub fn new() -> Self {
let mut list = PrepList {
items: Vec::new(),
renaming: None,
deleting: None,
error: None,
};
list.reload();
list
}
fn reload(&mut self) {
self.items = crate::prep_saved::dir()
.as_deref()
.map(crate::prep_saved::list)
.unwrap_or_default();
}
/// `can_new`: a database is chosen to prepare in.
pub fn show(&mut self, ctx: &egui::Context, can_new: bool) -> Option<ListOutcome> {
let mut out = None;
// Escape while renaming ends the renaming only.
let was_renaming = self.renaming.is_some();
let modal = egui::Modal::new(egui::Id::new("prep_list")).show(ctx, |ui| {
let screen = ctx.content_rect();
ui.set_width((screen.width() - 40.0).min(560.0));
ui.heading(tr("Preparations"));
ui.add_space(6.0);
if self.items.is_empty() {
ui.label(
RichText::new(tr(
"Nothing saved yet. Prepare against a player and press «Save» on the report.",
))
.weak(),
);
}
egui::ScrollArea::vertical()
.max_height((screen.height() - 180.0).max(120.0))
.auto_shrink([false, true])
.show(ui, |ui| {
for (id, item) in self.items.clone() {
self.row(ui, &id, &item, &mut out);
ui.separator();
}
});
if let Some(e) = &self.error {
ui.label(RichText::new(e).color(ui.visuals().warn_fg_color));
}
ui.add_space(6.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Close")).clicked() {
out = Some(ListOutcome::Close);
}
if ui
.add_enabled(can_new, egui::Button::new(tr("♟ New preparation…")))
.on_disabled_hover_text(tr("Add a database to the shelf first"))
.on_hover_text(tr("Choose a player in the current database"))
.clicked()
{
out = Some(ListOutcome::New);
}
});
});
if modal.should_close() && !was_renaming {
out = out.or(Some(ListOutcome::Close));
}
out
}
fn row(
&mut self,
ui: &mut Ui,
id: &str,
item: &crate::prep_saved::SavedPrep,
out: &mut Option<ListOutcome>,
) {
let found = item.path.exists();
if self.renaming.as_ref().is_some_and(|(r, _)| r == id) {
self.rename_row(ui, id);
return;
}
let deleting = self.deleting.as_deref() == Some(id);
// The buttons' room first: the texts are cut to what is left.
let gap = ui.spacing().item_spacing.x;
let pad = 2.0 * ui.spacing().button_padding.x;
let bw = |t: &str| text_width(ui, t, egui::TextStyle::Button) + pad + gap;
let buttons = if deleting {
text_width(ui, tr("Delete?"), egui::TextStyle::Body)
+ gap
+ bw(tr("Delete"))
+ bw(tr("No"))
} else {
bw(tr("Open")) + bw("✏") + bw("🗑")
};
let text_w = (ui.available_width() - buttons - 2.0 * gap).max(80.0);
ui.horizontal(|ui| {
let mut open = false;
ui.allocate_ui(vec2(text_w, 0.0), |ui| {
ui.set_max_width(text_w);
ui.vertical(|ui| {
let title = ui
.add(
egui::Label::new(RichText::new(&item.title).strong())
.truncate()
.sense(Sense::click()),
)
.on_hover_text(tr("Double-click to open"));
open |= found && title.double_clicked();
let mut about = vec![base_name(&item.path)];
// «за 2 года · 8 партий», «последние 100»: the number once.
match item.period {
Period::All => about.push(crate::i18n::games(item.games as usize)),
Period::Last(n) => about.push(trf("last {n}", &[("n", &n)])),
p => {
let label = period_label(p);
let mut chars = label.chars();
let lower = chars
.next()
.map(|c| c.to_lowercase().chain(chars).collect())
.unwrap_or_default();
about.push(lower);
about.push(crate::i18n::games(item.games as usize));
}
}
about.push(
match item.color {
ColorChoice::White => tr("as White"),
ColorChoice::Black => tr("as Black"),
ColorChoice::Both => tr("both colours"),
}
.to_owned(),
);
ui.add(egui::Label::new(RichText::new(about.join(" · ")).weak()).truncate());
let when = chrono::DateTime::<chrono::Local>::from(
std::time::UNIX_EPOCH + std::time::Duration::from_secs(item.saved),
)
.format("%d.%m.%Y")
.to_string();
let errors = if item.evaluated {
let e = &item.errors;
trf(
"errors: ?? {b} · ? {m} · ?! {i}",
&[
("b", &e.blunders),
("m", &e.mistakes),
("i", &e.inaccuracies),
],
)
} else {
tr("errors not searched").to_owned()
};
let path = item.path.display().to_string();
if found {
let line =
format!("{errors} · {}", trf("saved {date}", &[("date", &when)]));
ui.add(egui::Label::new(RichText::new(line).small().weak()).truncate());
} else {
ui.add(
egui::Label::new(
RichText::new(trf(
"database not found: {path}",
&[("path", &path)],
))
.small()
.color(ui.visuals().warn_fg_color),
)
.truncate(),
)
.on_hover_text(path);
}
});
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if deleting {
if ui.button(tr("No")).clicked() {
self.deleting = None;
}
if ui.button(tr("Delete")).clicked() {
self.deleting = None;
if let Some(dir) = crate::prep_saved::dir()
&& let Err(e) = crate::prep_saved::delete(&dir, id)
{
self.error = Some(e.to_string());
}
self.reload();
}
ui.label(tr("Delete?"));
return;
}
if ui.button("🗑").on_hover_text(tr("Delete")).clicked() {
self.deleting = Some(id.to_owned());
}
if ui.button("✏").on_hover_text(tr("Rename")).clicked() {
self.renaming = Some((id.to_owned(), item.title.clone()));
}
open |= ui
.add_enabled(found, egui::Button::new(tr("Open")))
.on_disabled_hover_text(tr(
"The database is not found: put the file back or delete the preparation",
))
.clicked();
});
if open {
*out = Some(ListOutcome::Open(id.to_owned()));
}
});
}
/// The name being typed: Enter or «OK» keeps it, Escape or «Cancel» does not.
fn rename_row(&mut self, ui: &mut Ui, id: &str) {
let mut done = None;
ui.horizontal(|ui| {
let gap = ui.spacing().item_spacing.x;
let pad = 2.0 * ui.spacing().button_padding.x;
let buttons = text_width(ui, tr("OK"), egui::TextStyle::Button)
+ text_width(ui, tr("Cancel"), egui::TextStyle::Button)
+ 2.0 * (pad + gap);
if let Some((_, text)) = self.renaming.as_mut() {
let r = ui.add(
egui::TextEdit::singleline(text)
.desired_width((ui.available_width() - buttons - gap).max(80.0)),
);
r.request_focus();
if ui.input(|i| i.key_pressed(Key::Enter)) {
done = Some(true);
}
if ui.input(|i| i.key_pressed(Key::Escape)) {
done = Some(false);
}
}
if ui.button(tr("OK")).clicked() {
done = Some(true);
}
if ui.button(tr("Cancel")).clicked() {
done = Some(false);
}
});
if let Some(ok) = done {
let (_, text) = self.renaming.take().unwrap_or_default();
let text = text.trim();
if ok
&& !text.is_empty()
&& let Some(dir) = crate::prep_saved::dir()
{
if let Err(e) = crate::prep_saved::rename(&dir, id, text) {
self.error = Some(e.to_string());
}
self.reload();
}
}
}
}
// ----- the screen ------------------------------------------------------------------
/// What the screen asks of the application.
@ -1100,7 +1422,12 @@ pub struct PrepScreen {
pub dbs: Vec<RefDb>,
color: ColorChoice,
plies: usize,
period: Period,
book: BookChoice,
/// Kept in «Preparations» (`prep_saved`): every change is written there too.
saved: bool,
/// A period asked for where the settings are not at hand (applied in `show`).
want_period: Option<Period>,
report: Option<PrepReport>,
rows: Vec<ListRow>,
/// The games read in the background (hundreds in a moment, a Mega filter in seconds).
@ -1416,13 +1743,45 @@ impl PrepScreen {
ctx: &egui::Context,
) -> Self {
let dir = cache_dir();
let cache = dir.as_deref().map(PositionCache::load).unwrap_or_default();
let plies = settings.prep.plies.clamp(2, 60);
let mut cache = dir.as_deref().map(PositionCache::load).unwrap_or_default();
// A saved preparation of this player: its depth and games, its report.
let saved_dir = crate::prep_saved::dir();
let names = start.player.names(&db);
let saved_id = crate::prep_saved::id(&start.path, &names);
let saved = saved_dir
.as_deref()
.and_then(|d| crate::prep_saved::get(d, &saved_id));
let saved_report = saved
.as_ref()
.and(saved_dir.as_deref())
.and_then(|d| crate::prep_saved::report(d, &saved_id));
let plies = saved
.as_ref()
.map_or(settings.prep.plies, |s| s.plies)
.clamp(2, 60);
let period = saved.as_ref().map_or(settings.prep.period, |s| s.period);
let options = Options {
plies,
side: Side::Any,
period,
};
let names = start.player.names(&db);
// The saved report as it is, when the database is the same; else its
// evaluations serve the report made again (new games of the database).
let fresh = saved_report.and_then(|r| {
if r.search != game_review::SEARCH_VERSION {
return None;
}
if r.fingerprint == prep::fingerprint(&db)
&& r.options() == options
&& r.player == start.player
{
return Some(r);
}
for (k, e) in r.evals {
cache.insert(k, e);
}
None
});
let mut screen = PrepScreen {
serial: crate::engine_offer::next_serial(),
db_name: base_name(&start.path),
@ -1434,7 +1793,10 @@ impl PrepScreen {
dbs: Vec::new(),
color: start.side,
plies,
period,
book: start.book,
saved: saved.is_some(),
want_period: None,
report: None,
rows: Vec::new(),
build: None,
@ -1481,9 +1843,10 @@ impl PrepScreen {
games_height: None,
auto_engine: std::env::var_os("CP_PREP_ENGINE").is_some(),
};
let cached = dir
.as_deref()
.and_then(|d| PrepReport::load(d, &screen.db, &screen.player, &options));
let cached = fresh.or_else(|| {
dir.as_deref()
.and_then(|d| PrepReport::load(d, &screen.db, &screen.player, &options))
});
match cached {
Some(r) => screen.take_report(r),
None => screen.rebuild(ctx),
@ -1524,10 +1887,7 @@ impl PrepScreen {
self.job = None;
self.book_job = None;
let (db, player) = (self.db.clone(), self.player.clone());
let options = Options {
plies: self.plies,
side: Side::Any,
};
let options = self.options();
self.build_total = 0;
let now = ctx.input(|i| i.time);
self.build = Background::spawn(ctx, now, move |progress, cancel| {
@ -1574,6 +1934,10 @@ impl PrepScreen {
/// The same player asked for again from the dialog: its colour and book.
pub fn reopen(&mut self, side: ColorChoice, book: BookChoice) {
self.shown = true;
// Deleted from «Preparations» while this screen was hidden: «Save» again.
self.saved &= crate::prep_saved::dir().is_some_and(|d| {
crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names)).is_some()
});
self.set_color(side);
if book != self.book {
self.book = book;
@ -1583,6 +1947,8 @@ impl PrepScreen {
}
fn set_color(&mut self, color: ColorChoice) {
// The colour a saved preparation opens with.
self.dirty |= self.saved && color != self.color;
self.color = color;
// A selection of a colour no longer shown is dropped.
let keep = match &self.selection {
@ -1597,6 +1963,26 @@ impl PrepScreen {
}
}
/// Games of the colour(s) shown.
fn shown_games(&self) -> usize {
self.report.as_ref().map_or(0, |r| {
self.color
.colours()
.iter()
.map(|&w| r.color(w).games.len())
.sum()
})
}
/// What the report is built with.
fn options(&self) -> Options {
Options {
plies: self.plies,
side: Side::Any,
period: self.period,
}
}
/// Another depth: the report of that depth from the cache, else built anew.
fn set_plies(&mut self, plies: usize, settings: &mut Settings, ctx: &egui::Context) {
if plies == self.plies {
@ -1606,16 +1992,33 @@ impl PrepScreen {
self.save();
self.plies = plies;
settings.prep.plies = plies;
self.load_or_build(ctx);
}
/// Other games of the player: the report of them from the cache, else built anew.
fn set_period(&mut self, period: Period, settings: &mut Settings, ctx: &egui::Context) {
if period == self.period {
return;
}
self.stop_engine(&mut Vec::new());
self.save();
self.period = period;
settings.prep.period = period;
self.load_or_build(ctx);
}
/// The report of the current options from the cache, else built anew.
fn load_or_build(&mut self, ctx: &egui::Context) {
self.report = None;
let options = Options {
plies,
side: Side::Any,
};
let options = self.options();
let cached = cache_dir()
.as_deref()
.and_then(|d| PrepReport::load(d, &self.db, &self.player, &options));
match cached {
Some(r) => self.take_report(r),
Some(r) => {
self.take_report(r);
self.dirty |= self.saved;
}
None => self.rebuild(ctx),
}
}
@ -1801,7 +2204,11 @@ impl PrepScreen {
{
self.build = None;
match r {
Some(report) => self.take_report(report),
Some(report) => {
self.take_report(report);
// A saved preparation follows its new games and depth.
self.dirty |= self.saved;
}
None => self.error = Some(tr("The games could not be read").to_owned()),
}
}
@ -2070,7 +2477,8 @@ impl PrepScreen {
}
}
/// Writes the report and the evaluations to the cache.
/// Writes the report and the evaluations to the cache, and to «Preparations» when
/// the preparation is kept there.
pub fn save(&mut self) {
let Some(dir) = cache_dir() else { return };
if let Err(e) = self.cache.save(&dir) {
@ -2079,9 +2487,75 @@ impl PrepScreen {
if self.dirty
&& let Some(r) = &self.report
{
match r.save(&dir) {
Ok(()) => self.dirty = false,
Err(e) => eprintln!("prep report: {}: {e}", dir.display()),
let mut ok = true;
if let Err(e) = r.save(&dir) {
ok = false;
eprintln!("prep report: {}: {e}", dir.display());
}
// Deleted from «Preparations» meanwhile: not written back.
self.saved &= crate::prep_saved::dir().is_some_and(|d| {
crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names))
.is_some()
});
if self.saved
&& let Err(e) = self.keep()
{
ok = false;
eprintln!("prep saved: {e}");
}
if ok {
self.dirty = false;
}
}
}
/// Writes the preparation to «Preparations» (its name in the list kept).
fn keep(&self) -> std::io::Result<()> {
let dir =
crate::prep_saved::dir().ok_or_else(|| std::io::Error::other("no data folder"))?;
let Some(report) = &self.report else {
return Ok(());
};
let id = crate::prep_saved::id(&self.path, &self.names);
let title = crate::prep_saved::get(&dir, &id)
.map(|m| m.title)
.unwrap_or_else(|| self.names.first().cloned().unwrap_or_default());
let mut errors = ErrorCounts::default();
for c in [&report.white, &report.black] {
errors.inaccuracies += c.counts.inaccuracies;
errors.mistakes += c.counts.mistakes;
errors.blunders += c.counts.blunders;
}
let meta = crate::prep_saved::SavedPrep {
title,
path: self.path.clone(),
player: self.player.clone(),
names: self.names.clone(),
plies: self.plies,
period: self.period,
color: self.color,
book: self.book.setting(&self.path),
saved: crate::prep_saved::now(),
games: report.games.len() as u32,
errors,
evaluated: report.evaluated(),
};
crate::prep_saved::save(&dir, &meta, report)
}
/// «💾 Save»: the preparation goes to «Preparations» and is kept there from now on.
fn save_to_list(&mut self, actions: &mut Vec<PrepAction>) {
self.saved = true;
match self.keep() {
Ok(()) => actions.push(PrepAction::Toast(
tr("Saved: the library's «Preparations» opens it").to_owned(),
)),
Err(e) => {
self.saved = false;
actions.push(PrepAction::Toast(trf(
"Could not save: {e}",
&[("e", &e.to_string())],
)));
}
}
}
@ -2505,6 +2979,10 @@ impl PrepScreen {
.show(ui, |ui| self.right_column(ui, settings, &mut actions));
}
self.engine_dialog(&ctx, settings, &mut actions);
if let Some(p) = self.want_period.take() {
self.set_period(p, settings, &ctx);
actions.push(PrepAction::SettingsChanged);
}
if !typing && !overlay {
self.keyboard(&ctx, settings, &mut actions);
}
@ -2525,7 +3003,13 @@ impl PrepScreen {
let row = ui.available_width();
let compact = row < 700.0;
let left = button_w(ui, if compact { "⬅" } else { tr("⬅ Library") }) + 2.0 * gap;
let right = button_w(ui, if compact { "⚙" } else { tr("⚙ Settings") });
let save_label = match (self.saved, compact) {
(false, false) => tr("★ Save"),
(true, false) => tr("★ Saved"),
(_, true) => "★",
};
let right =
button_w(ui, if compact { "⚙" } else { tr("⚙ Settings") }) + button_w(ui, save_label);
let title_room = (row - left - right).max(80.0);
ui.horizontal(|ui| {
if ui
@ -2540,7 +3024,7 @@ impl PrepScreen {
let more = self.names.len().saturating_sub(1);
let mut parts = Vec::new();
if let Some(r) = &self.report {
parts.push(crate::i18n::games(r.games.len()));
parts.push(crate::i18n::games(self.shown_games()));
let p = period(&r.games);
if !p.is_empty() {
parts.push(p);
@ -2581,6 +3065,22 @@ impl PrepScreen {
{
actions.push(PrepAction::OpenSettings);
}
let games = self.shown_games();
if self.saved {
// A quiet mark, not a button that looks unavailable.
ui.label(RichText::new(save_label).color(ui.visuals().selection.bg_fill))
.on_hover_text(tr(
"Kept in the library's «Preparations»: changes are saved by themselves",
));
} else if ui
.add_enabled(games > 0, egui::Button::new(save_label))
.on_hover_text(tr(
"Keep this preparation with the errors found: the library's «Preparations» opens it again",
))
.clicked()
{
self.save_to_list(actions);
}
});
});
}
@ -2630,7 +3130,15 @@ impl PrepScreen {
if caption_apart {
ui.label(tr("Book"));
}
let book_w = if width < 900.0 { 150.0 } else { 240.0 };
let book_w = if width < 700.0 {
120.0
} else if width < 900.0 {
150.0
} else if width < 1100.0 {
180.0
} else {
240.0
};
if let Some(b) = book_picker(
ui,
"prep_book",
@ -2651,24 +3159,36 @@ impl PrepScreen {
.on_hover_text(trf("Book: could not open — {reason}", &[("reason", why)]));
}
ui.separator();
// The depth's caption by the room left: «Opening: 10 moves», «10 moves», «10 m.».
let moves = self.plies.div_ceil(2);
let board_w = if low {
text_width(ui, "♙", egui::TextStyle::Button) + pad + 2.0 * gap
} else {
0.0
};
let room = ui.available_width() - engine_w - board_w;
let depth_label = [
// The period's and the depth's captions by the room left, shortened in one
// order at every width: the depth first, then the period, then both.
let depths = [
trf("Opening: {n} moves", &[("n", &moves)]),
trf("{n} moves", &[("n", &moves)]),
trf("{n} m.", &[("n", &moves)]),
]
.into_iter()
.find(|l| text_width(ui, l, egui::TextStyle::Button) + pad + 20.0 + gap <= room)
.unwrap_or_else(|| trf("{n} m.", &[("n", &moves)]));
];
let periods = self.period_captions();
let combo = |t: &str| text_width(ui, t, egui::TextStyle::Button) + pad + 20.0 + gap;
let room =
ui.available_width() - engine_w - board_w - ui.spacing().item_spacing.x * 2.0;
let (p, d) = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)]
.into_iter()
.find(|&(p, d)| combo(&periods[p]) + combo(&depths[d]) <= room)
.unwrap_or((2, 2));
let [p0, p1, p2] = periods;
let period_label_now = [p0, p1, p2].into_iter().nth(p).unwrap_or_default();
self.period_picker(ui, settings, period_label_now, actions);
ui.separator();
let depth_label = depths[d].clone();
let mut new_plies = None;
let depth_w = text_width(ui, &depth_label, egui::TextStyle::Button) + 8.0;
egui::ComboBox::from_id_salt("prep_plies")
.width(depth_w)
.selected_text(depth_label)
.show_ui(ui, |ui| {
for m in [6usize, 10, 15] {
@ -2705,6 +3225,113 @@ impl PrepScreen {
});
}
/// The period shown: a period by months over games without dates takes all.
fn period_shown(&self) -> Period {
let dated = self
.report
.as_ref()
.is_some_and(|r| r.pool.iter().any(|g| g.date != 0));
match self.period {
Period::Months(_) if self.report.is_some() && !dated => Period::All,
p => p,
}
}
/// How many games `p` takes of the colour(s) shown: «80», «100 + 100».
fn period_number(&self, p: Period) -> String {
let Some(r) = &self.report else {
return "…".to_owned();
};
let side = self.color.side();
match (p, side) {
// The last N of each colour, not N in all.
(Period::Last(_), Side::Any) => format!(
"{} + {}",
grouped(r.count(p, Side::White).games),
grouped(r.count(p, Side::Black).games)
),
_ => grouped(r.count(p, side).games),
}
}
/// The period's captions, longest first: «Last 2 years · 80», «2 yrs · 80», «80».
fn period_captions(&self) -> [String; 3] {
let p = self.period_shown();
let n = self.period_number(p);
[
format!("{} · {n}", period_label(p)),
format!("{} · {n}", period_short(p)),
n,
]
}
/// «Last 2 years · 80 ▾»: which of the player's games, with how many each takes of
/// the colour(s) shown; `selected` is the caption the row has room for.
fn period_picker(
&mut self,
ui: &mut Ui,
settings: &mut Settings,
selected: String,
actions: &mut Vec<PrepAction>,
) {
let side = self.color.side();
let report = self.report.as_ref();
let dated = report.is_some_and(|r| r.pool.iter().any(|g| g.date != 0));
let shown = self.period_shown();
let number = |p: Period| self.period_number(p);
let mut picked = None;
// As wide as its text: the room is the row's.
let width = text_width(ui, &selected, egui::TextStyle::Button) + 8.0;
let r = egui::ComboBox::from_id_salt("prep_period")
.width(width)
.selected_text(selected)
.show_ui(ui, |ui| {
for p in PERIODS {
// Without dates: by number only.
if matches!(p, Period::Months(_)) && !dated {
continue;
}
let text = format!("{} · {}", period_label(p), number(p));
if ui.selectable_label(shown == p, text).clicked() {
picked = Some(p);
}
}
let note = |ui: &mut Ui, text: String| {
ui.label(RichText::new(text).weak().small());
};
if !dated {
note(ui, tr("The games have no dates: by number only").to_owned());
} else if let Some(r) = report {
let newest = prep::period_newest(&r.pool);
note(
ui,
trf(
"Counted back from his newest game — {date}",
&[("date", &shown_date(newest))],
),
);
let out = r.count(Period::Months(12), side).undated_out;
if out > 0 {
note(
ui,
trf(
"Without a date: {n} — taken only with all games",
&[("n", &grouped(out))],
),
);
}
}
})
.response;
r.on_hover_text(tr(
"Which of his games: by date — counted back from his newest game; by number — the newest of each colour",
));
if let Some(p) = picked {
self.set_period(p, settings, ui.ctx());
actions.push(PrepAction::SettingsChanged);
}
}
/// What the engine part of the controls says, by the room there is.
fn engine_texts(&self, state: EngineState, width: f32) -> EngineTexts {
let (missing, secs) = self.estimate();
@ -2793,7 +3420,11 @@ impl PrepScreen {
ui.label(RichText::new(label).weak()).on_hover_text(hint);
}
EngineTexts::Button { label, note } => {
if crate::widgets::primary(ui, &label)
// Nothing to search in no games.
let some = self.shown_games() > 0;
if ui
.add_enabled_ui(some, |ui| crate::widgets::primary(ui, &label))
.inner
.on_hover_text(hint)
.clicked()
{
@ -2978,6 +3609,18 @@ impl PrepScreen {
.iter()
.map(|&w| report.color(w).games.len())
.sum();
if let Period::Months(_) = report.period {
let out = report.count(report.period, self.color.side()).undated_out;
if out > 0 {
ui.label(
RichText::new(trf(
"Without a date, not counted: {n} (only with all games)",
&[("n", &grouped(out))],
))
.weak(),
);
}
}
if n > 0 && n < 10 {
ui.label(
RichText::new(trf(
@ -3861,6 +4504,25 @@ impl PrepScreen {
/// «No games as Black. As White — 138 · Show White» when the colour has none.
fn no_games_note(&mut self, ui: &mut Ui) {
let Some(report) = &self.report else { return };
// No game in the period at all: the way back to all of them.
let side = self.color.side();
if report.period != Period::All && report.count(report.period, side).games == 0 {
let all = report.count(Period::All, side).games;
ui.add_space(12.0);
ui.label(match self.color {
ColorChoice::White => tr("No games as White in this period"),
ColorChoice::Black => tr("No games as Black in this period"),
ColorChoice::Both => tr("No games in this period"),
});
if all > 0
&& ui
.button(format!("{} · {}", period_label(Period::All), grouped(all)))
.clicked()
{
self.want_period = Some(Period::All);
}
return;
}
let (shown, other) = match self.color {
ColorChoice::White => (true, false),
ColorChoice::Black => (false, true),
@ -3886,7 +4548,11 @@ impl PrepScreen {
.link(trf("Show {other}", &[("other", &other_name)]))
.clicked()
{
self.color = ColorChoice::from_side(if other { Side::White } else { Side::Black });
self.set_color(ColorChoice::from_side(if other {
Side::White
} else {
Side::Black
}));
}
});
}
@ -5450,13 +6116,13 @@ impl PrepScreen {
self.tab = Tab::Errors;
}
if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num1))) {
self.color = ColorChoice::White;
self.set_color(ColorChoice::White);
}
if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num2))) {
self.color = ColorChoice::Black;
self.set_color(ColorChoice::Black);
}
if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num3))) {
self.color = ColorChoice::Both;
self.set_color(ColorChoice::Both);
}
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::W))) {
actions.push(PrepAction::Back);

View file

@ -169,6 +169,8 @@ pub struct PrepSettings {
pub book: Option<PathBuf>,
/// Plies of the opening the report looks at.
pub plies: usize,
/// Which of the player's games.
pub period: prep::Period,
/// Moves with fewer games fold into «other moves».
pub branches_from: u32,
/// The colour was chosen in the dialog once: the button starts the engine at once.
@ -184,6 +186,7 @@ impl Default for PrepSettings {
Self {
book: None,
plies: 20,
period: prep::Period::All,
branches_from: 3,
chosen: false,
inaccuracies: true,

View file

@ -274,6 +274,7 @@ fn main() {
let options = Options {
plies: a.plies,
side: Side::Any,
period: prep::Period::All,
};
let t = Instant::now();
let cached = cache_dir

View file

@ -31,6 +31,7 @@ mod book;
mod errors;
mod games;
pub mod openings;
mod period;
mod players;
mod tree;
@ -40,6 +41,7 @@ pub use errors::{EXACT, ErrorCounts, OpeningError, PositionCache, PositionEval,
pub use game_review::{Eval, Judgement};
pub use games::{BookExit, GameInfo, Outcome, Tally, move_label};
pub use openings::Opening;
pub use period::{Chosen, Period, PoolGame, newest as period_newest};
pub use players::{Candidate, Player, candidates, games_of};
pub use tree::{Node, Tree};
@ -55,6 +57,8 @@ pub struct Options {
pub plies: usize,
/// The player's colour(s).
pub side: Side,
/// Which of his games.
pub period: Period,
}
impl Default for Options {
@ -62,6 +66,7 @@ impl Default for Options {
Options {
plies: DEFAULT_PLIES,
side: Side::Any,
period: Period::All,
}
}
}
@ -138,7 +143,8 @@ pub struct BookInfo {
pub left: u32,
}
const REPORT_VERSION: u32 = 3;
// 4: the period and the pool of the player's games.
const REPORT_VERSION: u32 = 4;
/// Everything the preparation knows about the player.
#[derive(Clone, Debug, Serialize, Deserialize)]
@ -152,6 +158,13 @@ pub struct PrepReport {
pub plies: usize,
pub side_white: bool,
pub side_black: bool,
/// Which of the player's games the report took.
#[serde(default)]
pub period: Period,
/// All the player's games of the side(s), before the period's choice (for the
/// counts of the other periods).
#[serde(default)]
pub pool: Vec<PoolGame>,
pub games: Vec<GameInfo>,
/// Games left out: from a set-up position, or unreadable.
pub skipped: u32,
@ -224,9 +237,26 @@ pub fn build(
cancel: &AtomicBool,
) -> Option<PrepReport> {
let found = games_of(db, player, options.side, cancel)?;
// Every game is read (its first plies: a moment), so that the pool and the counts of
// the periods are of the games a report can take: not those from a set-up position.
let collected = games::collect(db, &found, options.plies, progress, cancel)?;
let pool: Vec<PoolGame> = collected
.games
.iter()
.map(|g| PoolGame {
index: g.index,
white: g.white,
date: g.date_number(),
})
.collect();
let chosen: std::collections::HashSet<(u32, bool)> =
period::choose(&pool, options.period).into_iter().collect();
let mut openings = collected.openings;
let games = collected.games;
let games: Vec<GameInfo> = collected
.games
.into_iter()
.filter(|g| chosen.contains(&(g.index, g.white)))
.collect();
let mut evals = HashMap::new();
for (key, pos) in &collected.terminal {
if let Some(eval) = game_review::terminal_eval(pos) {
@ -270,6 +300,8 @@ pub fn build(
plies: options.plies,
side_white: options.side != Side::Black,
side_black: options.side != Side::White,
period: options.period,
pool,
games,
skipped: collected.skipped,
openings: openings.list,
@ -354,6 +386,20 @@ impl PrepReport {
}
}
/// The options the report was built with.
pub fn options(&self) -> Options {
Options {
plies: self.plies,
side: self.side(),
period: self.period,
}
}
/// How many games `period` would take of the colour(s) `side`.
pub fn count(&self, period: Period, side: Side) -> Chosen {
period::count(&self.pool, period, side)
}
pub fn color(&self, white: bool) -> &ColorReport {
if white { &self.white } else { &self.black }
}
@ -564,6 +610,18 @@ impl PrepReport {
Side::White => 1,
Side::Black => 2,
});
// All the games: as before periods were chosen (the reports cached then).
match options.period {
Period::All => {}
Period::Months(m) => {
bytes.push(1);
bytes.extend(u32::from(m).to_le_bytes());
}
Period::Last(n) => {
bytes.push(2);
bytes.extend(n.to_le_bytes());
}
}
dir.join(format!("{:016x}.json", fnv(bytes.iter())))
}
@ -581,7 +639,8 @@ impl PrepReport {
&& report.fingerprint == fp
&& report.player == *player
&& report.plies == options.plies
&& report.side() == options.side;
&& report.side() == options.side
&& report.period == options.period;
if !same {
return None;
}
@ -598,10 +657,7 @@ impl PrepReport {
/// Keeps the report in `dir` (atomically).
pub fn save(&self, dir: &Path) -> std::io::Result<()> {
let options = Options {
plies: self.plies,
side: self.side(),
};
let options = self.options();
let path = Self::cache_path(dir, self.fingerprint, &self.player, &options);
let bytes = serde_json::to_vec(self).map_err(std::io::Error::other)?;
errors::write_atomic(&path, &bytes)
@ -816,6 +872,7 @@ mod tests {
&Options {
plies: 4,
side: Side::White,
period: Period::All,
},
&AtomicUsize::new(0),
&never,
@ -825,6 +882,27 @@ mod tests {
assert!(white_only.black.games.is_empty());
assert!(white_only.games.iter().all(|g| g.ucis.len() <= 4));
assert_eq!(white_only.side(), Side::White);
// The last two months before his newest game (2026.04.01): from 2026.02.01.
let recent = build(
&db,
&player,
&Options {
period: Period::Months(2),
..Options::default()
},
&AtomicUsize::new(0),
&never,
)
.expect("report");
let dates: Vec<&str> = recent.games.iter().map(|g| g.date.as_str()).collect();
assert_eq!(dates, ["2026.02.11", "2026.03.12", "2026.04.01"]);
// The pool: the games a report can take (not the set-up one it skips).
let all = report.games.len();
assert_eq!(report.skipped, 1);
assert_eq!(recent.pool.len(), all);
assert_eq!(recent.count(Period::All, Side::Any).games, all);
assert_eq!(recent.count(Period::Months(2), Side::Any).games, 3);
assert_eq!(recent.count(Period::Last(1), Side::White).games, 1);
// Cancelled.
let cancelled = AtomicBool::new(true);
assert!(
@ -1037,7 +1115,8 @@ mod tests {
&player,
&Options {
plies: 10,
side: Side::Any
side: Side::Any,
period: Period::All,
}
)
.is_none()

250
crates/prep/src/period.rs Normal file
View file

@ -0,0 +1,250 @@
//! Which of the player's games a report takes: all, those of the last months (counted
//! back from his newest game, so an old database is not left empty), or his last games
//! of each colour. Games without a date are taken by «all» only; by number they count
//! as the oldest, in the order of the database (so a database without dates gives its
//! last records). When no game has a date, a period by months takes them all: it
//! cannot choose, and an empty report would explain nothing.
use serde::{Deserialize, Serialize};
use chess_import::chessbase::base::Side;
/// The games a report takes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Period {
#[default]
All,
/// Played within this many months before the player's newest game.
Months(u16),
/// The newest this many games of each colour.
Last(u32),
}
/// One game of the player before the choice.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PoolGame {
/// Record index in the database.
pub index: u32,
pub white: bool,
/// `yyyymmdd` (month or day 0 when unknown); 0: no date.
pub date: u32,
}
/// What a period takes of the games of the colour(s) looked at.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Chosen {
pub games: usize,
/// Of all the games: undated ones a period by months leaves out.
pub undated_out: usize,
}
/// The latest day a PGN date can mean: «2026.??.??» → 2026.12.31, «2026.02.??» →
/// 2026.02.31 (only compared, never shown).
fn latest(date: u32) -> u32 {
match (date / 100 % 100, date % 100) {
(0, _) => date / 10000 * 10000 + 1231,
(_, 0) => date + 31,
_ => date,
}
}
/// Today as `yyyymmdd` (UTC).
fn today() -> u32 {
let days = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() / 86_400) as i64;
// Days since 1970 to the civil date (H. Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
(y * 10000 + m * 100 + d) as u32
}
/// The date as the choice sees it: one after `today` is a typo («2206») and counts as
/// no date.
fn known(date: u32, today: u32) -> u32 {
if date > today { 0 } else { date }
}
/// The date of the player's newest game as written (0: none dated): by its earliest
/// day, so that one game of «2026.??.??» does not move the period past the exactly
/// dated ones.
fn newest_at(pool: &[PoolGame], today: u32) -> u32 {
pool.iter().map(|g| known(g.date, today)).max().unwrap_or(0)
}
/// The date of the player's newest game as written (0: none dated).
pub fn newest(pool: &[PoolGame]) -> u32 {
newest_at(pool, today())
}
/// The first day within `months` before the day `end` (`yyyymmdd`).
fn cutoff(end: u32, months: u16) -> u32 {
let (y, m, d) = (end / 10000, end / 100 % 100, end % 100);
let total = (y * 12 + m - 1).saturating_sub(u32::from(months));
(total / 12) * 10000 + (total % 12 + 1) * 100 + d
}
/// The games `period` takes: (record, the player had White), in record order.
pub fn choose(pool: &[PoolGame], period: Period) -> Vec<(u32, bool)> {
choose_at(pool, period, today())
}
/// [`choose`] on the day `today`. A partly known date is in a period when any day it
/// can mean is.
fn choose_at(pool: &[PoolGame], period: Period, today: u32) -> Vec<(u32, bool)> {
let mut out: Vec<(u32, bool)> = match period {
Period::All => pool.iter().map(|g| (g.index, g.white)).collect(),
Period::Months(months) => {
let newest = newest_at(pool, today);
if newest == 0 {
return choose_at(pool, Period::All, today);
}
let from = cutoff(latest(newest).min(today), months);
pool.iter()
.filter(|g| known(g.date, today) != 0 && latest(g.date) >= from)
.map(|g| (g.index, g.white))
.collect()
}
Period::Last(n) => {
let mut out = Vec::new();
for white in [true, false] {
let mut games: Vec<&PoolGame> = pool.iter().filter(|g| g.white == white).collect();
// Newest first; the undated (0) last, later records counted newer.
games.sort_by(|a, b| {
known(b.date, today)
.cmp(&known(a.date, today))
.then(b.index.cmp(&a.index))
});
out.extend(games.iter().take(n as usize).map(|g| (g.index, g.white)));
}
out
}
};
out.sort_unstable();
out
}
/// How many games of `side` `period` takes, and the undated ones it leaves out.
pub fn count(pool: &[PoolGame], period: Period, side: Side) -> Chosen {
let of_side = |white: bool| match side {
Side::Any => true,
Side::White => white,
Side::Black => !white,
};
let games = choose(pool, period)
.iter()
.filter(|(_, w)| of_side(*w))
.count();
let undated_out = match period {
Period::Months(_) if newest(pool) != 0 => pool
.iter()
.filter(|g| g.date == 0 && of_side(g.white))
.count(),
_ => 0,
};
Chosen { games, undated_out }
}
#[cfg(test)]
mod tests {
use super::*;
fn g(index: u32, white: bool, date: u32) -> PoolGame {
PoolGame { index, white, date }
}
#[test]
fn months_count_back_from_the_newest_game() {
let pool = [
g(0, true, 20200105),
g(1, false, 20240301),
g(2, true, 20250228),
g(3, true, 20250301),
g(4, false, 0),
g(5, true, 20260301),
];
assert_eq!(cutoff(20260301, 12), 20250301);
assert_eq!(cutoff(20260115, 1), 20251215);
// Partly known dates.
assert_eq!(latest(20260000), 20261231);
assert_eq!(latest(20260200), 20260231);
let today = 20261031;
let year_only = [
g(0, true, 20260000),
g(1, true, 20250301),
g(2, true, 20260700),
];
// From «2026.07.??», the newest: its last day 2026.07.31, three months back
// 2026.04.31; «2026» may be any day of the year, so it is in.
assert_eq!(
choose_at(&year_only, Period::Months(3), today),
vec![(0, true), (2, true)]
);
// A typo from the future is not the newest game.
let typo = [
g(0, true, 22060101),
g(1, true, 20260301),
g(2, true, 20250101),
];
assert_eq!(newest_at(&typo, today), 20260301);
assert_eq!(choose_at(&typo, Period::Months(6), today), vec![(1, true)]);
assert_eq!(choose_at(&typo, Period::Last(1), today), vec![(1, true)]);
// One game of «2026» does not push out the exactly dated newest ones.
let mixed = [
g(0, true, 20260510),
g(1, true, 20260000),
g(2, true, 20260301),
];
assert_eq!(newest_at(&mixed, today), 20260510);
assert_eq!(choose_at(&mixed, Period::Months(3), today).len(), 3);
assert_eq!(
choose(&pool, Period::Months(12)),
vec![(3, true), (5, true)]
);
assert_eq!(
choose(&pool, Period::Months(24)),
vec![(1, false), (2, true), (3, true), (5, true)]
);
assert_eq!(choose(&pool, Period::All).len(), 6);
let c = count(&pool, Period::Months(24), Side::Black);
assert_eq!((c.games, c.undated_out), (1, 1));
assert_eq!(count(&pool, Period::All, Side::Any).undated_out, 0);
// Nothing dated: a period by months takes all.
let undated = [g(0, true, 0), g(1, false, 0)];
assert_eq!(choose(&undated, Period::Months(12)).len(), 2);
assert_eq!(
count(&undated, Period::Months(12), Side::Any).undated_out,
0
);
}
#[test]
fn the_last_games_of_each_colour() {
let pool = [
g(0, true, 20200101),
g(1, true, 0),
g(2, true, 20230101),
g(3, false, 20240101),
g(4, true, 20220101),
g(5, false, 20190101),
];
assert_eq!(
choose(&pool, Period::Last(2)),
vec![(2, true), (3, false), (4, true), (5, false)]
);
// Without dates: the last records.
let undated = [g(0, true, 0), g(1, true, 0), g(2, true, 0)];
assert_eq!(
choose(&undated, Period::Last(2)),
vec![(1, true), (2, true)]
);
assert_eq!(count(&pool, Period::Last(1), Side::Any).games, 2);
}
}

View file

@ -234,3 +234,15 @@
- **Окно, если не подошёл** — пять случаев: другой движок («В настройках указан …» / «В системе найден …»), «Ваш Stockfish 19 считает иначе, чем сборка ChessPenguin (другая сборка или сеть)…», «Не удалось запустить …», «… не успел ответить на проверку — проверю снова в следующий раз»; затем зачем нужна официальная сборка, «Скачать?», «Ваш движок остаётся для анализа позиции» (кроме незапустившегося) и «…начнётся сам после загрузки»; ниже — «N МБ · с официальной страницы Stockfish». Без движка — как прежде.
- **Перетаскивание на компьютере** (`platform::files::take_dropped`): брошенные файлы открываются как «Добавить базу» (на полку, выбирается первая; партия на экране не закрывается, тогда тост «Добавлено на полку: …»). `.pgn/.cbh/.cbv/.zip/.7z` — базы; другие файлы ChessBase-базы (`.cbg`, `.cba`, `.cbj`, … — известные расширения) — её `.cbh` рядом, база один раз (дубли по реальному файлу); папка — базы в ней (без вложенных), пустая — тост; несуществующий файл — «Не найдено: …»; прочее — «Это не база: …». База, уже стоящая на полке под другим путём к тому же файлу (ссылка), второй раз не добавляется (`touch_database` сравнивает реальные файлы). Брошенные файлы не заменяют базу из «Выбрать снова»; отмена этого диалога его завершает. Пока файл над окном — подсветка окна с рамкой и карточка «Отпустите, чтобы открыть».
- **Где работает перетаскивание**: Windows, macOS, Linux в X11 и XWayland. В сеансе Wayland окно перетаскивание не принимает (система и не показывает «можно отпустить»): в winit 0.30.13, на котором стоит eframe 0.36, перетаскивание есть только в X11 (`platform_impl/linux/x11/event_processor.rs`), в `wayland/` его нет. Принудительный запуск через X11 не делаем (без обходов).
## Подготовка к сопернику: какие партии брать; сохранённые подготовки (2026-10-31)
Владелец, задачи 20 и 21:
- **Период.** Рядом с глубиной — выбор партий: все / за 3 месяца / полгода / год / 2 года / последние 50 / 100 / 200 (5 лет владелец убрал: «бред»). У каждого варианта сразу видно, сколько партий он берёт (для показанного цвета). Время считается **от последней партии соперника в базе**, не от сегодня (владелец: «давай от последней») — так старая база не оказывается пустой. «Последние N» — самые свежие N партий каждым цветом.
- **Партии без даты** берутся только во «Всех партиях». При выборе периода под списком написано, сколько их не учтено. Если дат нет ни у одной партии, выбор по времени не показывается, остаётся выбор по числу: последние записи базы.
- **Сохранённые подготовки.** Кнопка «💾 Сохранить» в шапке отчёта. Подготовка лежит в данных программы (`~/.local/share/chesspenguin/preparations/`, не в кэше): отчёт вместе с найденными ошибками. На каждого игрока базы — одна подготовка: повторное сохранение заменяет прежнюю. После сохранения все изменения (поиск ошибок, период, глубина) записываются туда сами.
- **Где их открыть.** Кнопка «📑 Подготовки» в библиотеке: список (имя, база, период, партии, цвет, ошибки, дата), там же «Открыть», «Переименовать», «Удалить» и «♟ Новая подготовка…». Если в базе появились новые партии, подготовка собирается заново с прежними оценками, и движок досчитывает только новые позиции.
## Партия на Lichess / Chess.com (2026-10-31)
Владелец: из скачанной партии перейти на её страницу. Ссылка берётся из тега Link (Chess.com), иначе из Site (Lichess), если там веб-адрес. Кнопка «🌐» в шапке партии после результата, пункт в ☰ и в контекстном меню строки списка партий. Партия Lichess открывается на показанном ходу (`#ply`) и со стороны, которая внизу доски (`/black`); у Chess.com такой ссылки нет — открывается страница партии. Адрес из подстроки шапки убран: его открывает глобус.

View file

@ -141,11 +141,11 @@
- **Суть:** (1) дебютный репертуар — свои дебюты за белых и за чёрных деревом вариантов, с тренировкой по нему (продолжение задачи 15: «Мои дебюты», повторение по расписанию); (2) подготовка к сопернику — по партиям соперника (своя база, Lichess, Chess.com) показать, что он играет в дебюте, где ошибается, и сопоставить с моим репертуаром.
### 20. Подготовка к сопернику: какие партии брать — по давности или по числу (2026-10-28)
- **Статус:** идея владельца, не начато.
- **Статус:** сделано в ветке `prep-period-saved` (2026-10-31), проверено тестировщиком и дизайнером. Решения — `docs/decisions.md`, «какие партии брать». Время считается от последней партии соперника; партии без даты учитываются только во «Всех»; если дат нет совсем — выбор только по числу.
- **Суть:** выбирать, насколько старые партии соперника учитывать: «за последние N месяцев/лет от сегодня» или «последние N партий». Что делать, если у партий нет дат, — владелец не знает; нужно продумать (например, порядок партий в базе как замена даты, или такие партии всегда учитываются / показываются отдельно).
### 21. Подготовка к сопернику: сохранять анализ и возвращаться к нему — база подготовок (2026-10-28)
- **Статус:** идея владельца, не начато; продумать основательно.
- **Статус:** сделано в ветке `prep-period-saved` (2026-10-31), проверено тестировщиком и дизайнером: «★ Сохранить» в отчёте, «🗐 Подготовки» в библиотеке (открыть, переименовать, удалить, новая). Одна подготовка на игрока базы.
- **Суть:** сделанная подготовка (соперник, база, цвет, найденные ошибки, отметки) сохраняется, и к ней можно вернуться позже — по сути своя «база подготовок»: список подготовок к разным соперникам, открыть, обновить по новым партиям. Сейчас отчёт только кэшируется на диске и открывается заново при повторном входе к тому же игроку той же базы.
### 22. Веб-версия: ChessPenguin в браузере (2026-10-30)