From 57fa98241b99e21a8b8d08bc7f2ca4d85f4d9513 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 18:11:58 +0300 Subject: [PATCH] Opponent prep: which games by period or number, saved preparations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The report takes all the player's games, those of the last 1/2/5 years before his newest game, or his last 50/100/200 of each colour; every choice shows how many games it takes. Undated games count only with all. «💾 Save» keeps a preparation with its errors in the program's data; «📑 Preparations» in the library opens, renames and deletes them. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 75 +++++ apps/desktop/src/i18n.rs | 298 +++++++++++++++++ apps/desktop/src/lib.rs | 1 + apps/desktop/src/library.rs | 36 +- apps/desktop/src/prep_saved.rs | 204 ++++++++++++ apps/desktop/src/prep_ui.rs | 490 ++++++++++++++++++++++++++-- apps/desktop/src/settings.rs | 3 + crates/prep/examples/prep_report.rs | 1 + crates/prep/src/lib.rs | 86 ++++- crates/prep/src/period.rs | 165 ++++++++++ docs/decisions.md | 8 + docs/dev/tasks.md | 4 +- 12 files changed, 1334 insertions(+), 37 deletions(-) create mode 100644 apps/desktop/src/prep_saved.rs create mode 100644 crates/prep/src/period.rs diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 806bb14..66c311a 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -286,6 +286,10 @@ pub struct App { /// between the library and the game (opponent-prep.md §3.1). prep_dialog: Option, prep: Option, + /// The library's «Preparations» window, and a saved preparation waiting for its + /// database to be read. + prep_list: Option, + prep_waiting: Option, /// Quitting while the opening errors are searched: asked first; «Quit» answered. prep_quit_ask: bool, prep_quit_ok: bool, @@ -511,6 +515,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(), @@ -928,6 +934,71 @@ impl App { } } + /// «📑 Preparations», and a saved preparation opened once its database is read. + fn prep_list(&mut self, ctx: &egui::Context) { + if let Some(start) = self.prep_waiting.take() { + if self.library.database(&start.path).is_some() { + 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); + } + } + 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.prep_waiting = Some(start); + 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 +4013,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 +4094,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. diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index ef326c1..55dfa88 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -15623,6 +15623,304 @@ 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 5 years", + "За 5 лет", + "Les 5 dernières années", + "Letzte 5 Jahre", + "Últimos 5 años", + "Ultimi 5 anni", + "Últimos 5 anos", + "Oxirgi 5 yil", + "Соңғы 5 жыл", + ], + [ + "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 of the chosen database", + "Выбрать игрока выбранной базы", + "Choisir un joueur de la base choisie", + "Einen Spieler der gewählten Datenbank wählen", + "Elegir un jugador de la base elegida", + "Scegli un giocatore del database scelto", + "Escolher um jogador da base escolhida", + "Tanlangan 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}", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index dc9b3ac..ed0ecbf 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -41,6 +41,7 @@ mod own_db; pub mod platform; mod play; mod player_games; +mod prep_saved; mod prep_ui; mod reference; mod review; diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 2ecc3fa..a99b27f 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -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::() + + 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. diff --git a/apps/desktop/src/prep_saved.rs b/apps/desktop/src/prep_saved.rs new file mode 100644 index 0000000..738ba42 --- /dev/null +++ b/apps/desktop/src/prep_saved.rs @@ -0,0 +1,204 @@ +//! 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 `/preparations/`: `.json`, what the list shows, and +//! `.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, + 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 { + crate::platform::data_dir().map(|d| d.join("preparations")) +} + +/// The id of the preparation of `player` in the database `path`. +pub fn id(path: &Path, player: &Player) -> 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); + } + for id in &player.ids { + for b in id.to_le_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 { + 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 { + 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.player); + 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.player); + 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":{}}"#; +} diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index 1043c31..a1e9db0 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -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( } /// 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,30 @@ pub struct PrepStart { pub book: BookChoice, } +// ----- the period ------------------------------------------------------------------ + +/// The periods offered, in the menu's order. +const PERIODS: [Period; 7] = [ + Period::All, + Period::Months(12), + Period::Months(24), + Period::Months(60), + Period::Last(50), + Period::Last(100), + Period::Last(200), +]; + +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(60) => tr("Last 5 years").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 +899,212 @@ 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, + error: Option, +} + +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 { + 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 of the chosen 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, + ) { + let found = item.path.exists(); + ui.horizontal(|ui| { + let renaming = self.renaming.as_ref().is_some_and(|(r, _)| r == id); + if renaming { + let mut done = None; + if let Some((_, text)) = self.renaming.as_mut() { + let r = ui.add( + egui::TextEdit::singleline(text) + .desired_width(ui.available_width() - 120.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 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(); + } + } + return; + } + ui.vertical(|ui| { + ui.label(RichText::new(&item.title).strong()); + let mut about = vec![base_name(&item.path), period_label(item.period)]; + about.push(crate::i18n::games(item.games as usize)); + about.push(item.color.label().to_owned()); + ui.label(RichText::new(about.join(" · ")).weak()); + let when = chrono::DateTime::::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 mut line = format!("{errors} · {}", trf("saved {date}", &[("date", &when)])); + if !found { + line = trf( + "database not found: {path}", + &[("path", &item.path.display().to_string())], + ); + } + let text = RichText::new(line).small(); + ui.label(if found { + text.weak() + } else { + text.color(ui.visuals().warn_fg_color) + }); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if self.deleting.as_deref() == Some(id) { + if ui.button(tr("No")).clicked() { + self.deleting = None; + } + if crate::widgets::primary(ui, 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())); + } + if ui + .add_enabled(found, egui::Button::new(tr("Open"))) + .clicked() + { + *out = Some(ListOutcome::Open(id.to_owned())); + } + }); + }); + } +} + // ----- the screen ------------------------------------------------------------------ /// What the screen asks of the application. @@ -1100,7 +1330,10 @@ pub struct PrepScreen { pub dbs: Vec, color: ColorChoice, plies: usize, + period: Period, book: BookChoice, + /// Kept in «Preparations» (`prep_saved`): every change is written there too. + saved: bool, report: Option, rows: Vec, /// The games read in the background (hundreds in a moment, a Mega filter in seconds). @@ -1416,12 +1649,41 @@ 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 saved_id = crate::prep_saved::id(&start.path, &start.player); + 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, }; + // 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 { + return Some(r); + } + for (k, e) in r.evals { + cache.insert(k, e); + } + None + }); let names = start.player.names(&db); let mut screen = PrepScreen { serial: crate::engine_offer::next_serial(), @@ -1434,7 +1696,9 @@ impl PrepScreen { dbs: Vec::new(), color: start.side, plies, + period, book: start.book, + saved: saved.is_some(), report: None, rows: Vec::new(), build: None, @@ -1481,9 +1745,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 +1789,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| { @@ -1597,6 +1859,15 @@ impl PrepScreen { } } + /// 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 +1877,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 +2089,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 +2362,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 +2372,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.player)) + .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.player); + 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) { + 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())], + ))); } } } @@ -2525,7 +2884,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 @@ -2581,6 +2946,20 @@ impl PrepScreen { { actions.push(PrepAction::OpenSettings); } + if self.saved { + ui.add_enabled(false, egui::Button::new(save_label)) + .on_disabled_hover_text(tr( + "Kept in the library's «Preparations»: changes are saved by themselves", + )); + } else if ui + .add_enabled(self.report.is_some(), 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); + } }); }); } @@ -2651,6 +3030,8 @@ impl PrepScreen { .on_hover_text(trf("Book: could not open — {reason}", &[("reason", why)])); } ui.separator(); + self.period_picker(ui, settings, actions); + 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 { @@ -2705,6 +3086,63 @@ impl PrepScreen { }); } + /// «Last 2 years · 80 ▾»: which of the player's games, with how many each takes of + /// the colour(s) shown. + fn period_picker( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { + let side = self.color.side(); + let count = |p: Period| self.report.as_ref().map(|r| r.count(p, side)); + let dated = self + .report + .as_ref() + .is_some_and(|r| r.pool.iter().any(|g| g.date != 0)); + let number = |p: Period| count(p).map_or("…".to_owned(), |c| grouped(c.games)); + let selected = format!("{} · {}", period_label(self.period), number(self.period)); + let mut picked = None; + let r = egui::ComboBox::from_id_salt("prep_period") + .selected_text(selected) + .show_ui(ui, |ui| { + for p in PERIODS { + // Without dates a period by months takes nothing: by number only. + if matches!(p, Period::Months(_)) && !dated { + continue; + } + let text = format!("{} · {}", period_label(p), number(p)); + if ui.selectable_label(self.period == p, text).clicked() { + picked = Some(p); + } + } + if !dated { + ui.label( + RichText::new(tr("The games have no dates: by number only")) + .weak() + .small(), + ); + } else if let Some(c) = count(Period::Months(12)).filter(|c| c.undated_out > 0) { + ui.label( + RichText::new(trf( + "Without a date: {n} — taken only with all games", + &[("n", &grouped(c.undated_out))], + )) + .weak() + .small(), + ); + } + }) + .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(); diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index c293d35..b85228f 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -169,6 +169,8 @@ pub struct PrepSettings { pub book: Option, /// 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, diff --git a/crates/prep/examples/prep_report.rs b/crates/prep/examples/prep_report.rs index 8e7af56..3995ee0 100644 --- a/crates/prep/examples/prep_report.rs +++ b/crates/prep/examples/prep_report.rs @@ -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 diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs index 950169d..f58b032 100644 --- a/crates/prep/src/lib.rs +++ b/crates/prep/src/lib.rs @@ -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}; 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, pub games: Vec, /// Games left out: from a set-up position, or unreadable. pub skipped: u32, @@ -224,7 +237,16 @@ pub fn build( cancel: &AtomicBool, ) -> Option { let found = games_of(db, player, options.side, cancel)?; - let collected = games::collect(db, &found, options.plies, progress, cancel)?; + let pool: Vec = found + .iter() + .map(|&(index, white)| PoolGame { + index, + white, + date: chess_import::pgn_catalog::date_number(&db.row(index as usize).date), + }) + .collect(); + let chosen = period::choose(&pool, options.period); + let collected = games::collect(db, &chosen, options.plies, progress, cancel)?; let mut openings = collected.openings; let games = collected.games; let mut evals = HashMap::new(); @@ -270,6 +292,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 +378,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 +602,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 +631,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 +649,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 +864,7 @@ mod tests { &Options { plies: 4, side: Side::White, + period: Period::All, }, &AtomicUsize::new(0), &never, @@ -825,6 +874,26 @@ 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: every game of his, a set-up one too (skipped from the report). + let all = report.games.len() + report.skipped as usize; + 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 +1106,8 @@ mod tests { &player, &Options { plies: 10, - side: Side::Any + side: Side::Any, + period: Period::All, } ) .is_none() diff --git a/crates/prep/src/period.rs b/crates/prep/src/period.rs new file mode 100644 index 0000000..a698773 --- /dev/null +++ b/crates/prep/src/period.rs @@ -0,0 +1,165 @@ +//! 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). + +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 newest date of the games (0: none dated). +pub fn newest(pool: &[PoolGame]) -> u32 { + pool.iter().map(|g| g.date).max().unwrap_or(0) +} + +/// The first date within `months` before `newest` (`yyyymmdd`). +fn cutoff(newest: u32, months: u16) -> u32 { + let (y, month, d) = (newest / 10000, newest / 100 % 100, newest % 100); + let total = (y * 12 + month.max(1) - 1).saturating_sub(u32::from(months)); + let (y, m) = (total / 12, total % 12 + 1); + // A newest date without a month: the whole year it was in. + let (m, d) = if month == 0 { (0, 0) } else { (m, d) }; + y * 10000 + m * 100 + d +} + +/// The games `period` takes: (record, the player had White), in record order. +pub fn choose(pool: &[PoolGame], period: Period) -> 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(pool); + if newest == 0 { + return Vec::new(); + } + let from = cutoff(newest, months); + pool.iter() + .filter(|g| g.date != 0 && 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| b.date.cmp(&a.date).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(_) => 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); + assert_eq!(cutoff(20260000, 24), 20240000); + 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 takes nothing. + assert!(choose(&[g(0, true, 0)], Period::Months(12)).is_empty()); + } + + #[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); + } +} diff --git a/docs/decisions.md b/docs/decisions.md index e53e9a3..d3c61f3 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -234,3 +234,11 @@ - **Окно, если не подошёл** — пять случаев: другой движок («В настройках указан …» / «В системе найден …»), «Ваш 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: +- **Период.** Рядом с глубиной — выбор партий: все / за последний год / 2 года / 5 лет / последние 50 / 100 / 200. У каждого варианта сразу видно, сколько партий он берёт (для показанного цвета). Время считается **от последней партии соперника в базе**, не от сегодня (владелец: «давай от последней») — так старая база не оказывается пустой. «Последние N» — самые свежие N партий каждым цветом. +- **Партии без даты** берутся только во «Всех партиях». При выборе периода под списком написано, сколько их не учтено. Если дат нет ни у одной партии, выбор по времени не показывается, остаётся выбор по числу: последние записи базы. +- **Сохранённые подготовки.** Кнопка «💾 Сохранить» в шапке отчёта. Подготовка лежит в данных программы (`~/.local/share/chesspenguin/preparations/`, не в кэше): отчёт вместе с найденными ошибками. На каждого игрока базы — одна подготовка: повторное сохранение заменяет прежнюю. После сохранения все изменения (поиск ошибок, период, глубина) записываются туда сами. +- **Где их открыть.** Кнопка «📑 Подготовки» в библиотеке: список (имя, база, период, партии, цвет, ошибки, дата), там же «Открыть», «Переименовать», «Удалить» и «♟ Новая подготовка…». Если в базе появились новые партии, подготовка собирается заново с прежними оценками, и движок досчитывает только новые позиции. diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index 76b8a8b..0215bf0 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -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)