From 57fa98241b99e21a8b8d08bc7f2ca4d85f4d9513 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 18:11:58 +0300 Subject: [PATCH 01/10] 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) From 570bd84dcf3d1e92caaeccca4c32f7932081f7ad Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 20:28:35 +0300 Subject: [PATCH 02/10] Opponent prep: periods of 3 and 6 months, not 5 years Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/i18n.rs | 29 ++++++++++++++++++++--------- apps/desktop/src/prep_ui.rs | 8 +++++--- docs/decisions.md | 2 +- 3 files changed, 26 insertions(+), 13 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 55dfa88..c5a49e5 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -15646,15 +15646,26 @@ const ROWS: &[[&str; 9]] = &[ "Соңғы 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 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", diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index a1e9db0..e18e453 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -370,11 +370,12 @@ pub struct PrepStart { // ----- the period ------------------------------------------------------------------ /// The periods offered, in the menu's order. -const PERIODS: [Period; 7] = [ +const PERIODS: [Period; 8] = [ Period::All, + Period::Months(3), + Period::Months(6), Period::Months(12), Period::Months(24), - Period::Months(60), Period::Last(50), Period::Last(100), Period::Last(200), @@ -385,7 +386,8 @@ fn period_label(p: Period) -> String { 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(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)]), } diff --git a/docs/decisions.md b/docs/decisions.md index d3c61f3..6d3ffc1 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -238,7 +238,7 @@ ## Подготовка к сопернику: какие партии брать; сохранённые подготовки (2026-10-31) Владелец, задачи 20 и 21: -- **Период.** Рядом с глубиной — выбор партий: все / за последний год / 2 года / 5 лет / последние 50 / 100 / 200. У каждого варианта сразу видно, сколько партий он берёт (для показанного цвета). Время считается **от последней партии соперника в базе**, не от сегодня (владелец: «давай от последней») — так старая база не оказывается пустой. «Последние N» — самые свежие N партий каждым цветом. +- **Период.** Рядом с глубиной — выбор партий: все / за 3 месяца / полгода / год / 2 года / последние 50 / 100 / 200 (5 лет владелец убрал: «бред»). У каждого варианта сразу видно, сколько партий он берёт (для показанного цвета). Время считается **от последней партии соперника в базе**, не от сегодня (владелец: «давай от последней») — так старая база не оказывается пустой. «Последние N» — самые свежие N партий каждым цветом. - **Партии без даты** берутся только во «Всех партиях». При выборе периода под списком написано, сколько их не учтено. Если дат нет ни у одной партии, выбор по времени не показывается, остаётся выбор по числу: последние записи базы. - **Сохранённые подготовки.** Кнопка «💾 Сохранить» в шапке отчёта. Подготовка лежит в данных программы (`~/.local/share/chesspenguin/preparations/`, не в кэше): отчёт вместе с найденными ошибками. На каждого игрока базы — одна подготовка: повторное сохранение заменяет прежнюю. После сохранения все изменения (поиск ошибок, период, глубина) записываются туда сами. - **Где их открыть.** Кнопка «📑 Подготовки» в библиотеке: список (имя, база, период, партии, цвет, ошибки, дата), там же «Открыть», «Переименовать», «Удалить» и «♟ Новая подготовка…». Если в базе появились новые партии, подготовка собирается заново с прежними оценками, и движок досчитывает только новые позиции. From e80933d48dc92560101a9f8531d60ea8d2a28c4b Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 21:47:08 +0300 Subject: [PATCH 03/10] Opponent prep: the designer's review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The period caption shortens in a narrow row; «Last N» with both colours shows «N + N»; the menu says from which date it counts; undated games left out are named in the summary; no games in a period offer all games. Without any dates a period by months takes all. Crisp icons (★, 🗐); saved is a quiet mark. The list cuts long texts, names the colour in words, opens on double-click, renames with Cancel, explains a missing database, and tells while it opens one. CP_PREP_LIST for screenshots. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 8 +- apps/desktop/src/i18n.rs | 207 +++++++++++++++----- apps/desktop/src/library.rs | 12 +- apps/desktop/src/prep_ui.rs | 380 +++++++++++++++++++++++++----------- crates/prep/src/lib.rs | 2 +- crates/prep/src/period.rs | 16 +- 6 files changed, 456 insertions(+), 169 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 66c311a..1ca6b61 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -764,6 +764,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; @@ -934,7 +939,7 @@ impl App { } } - /// «📑 Preparations», and a saved preparation opened once its database is read. + /// «🗐 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() { @@ -991,6 +996,7 @@ impl App { }; 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); ctx.request_repaint(); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index c5a49e5..80cfca9 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -15625,7 +15625,7 @@ const ROWS: &[[&str; 9]] = &[ ], [ "Last year", - "За последний год", + "За год", "La dernière année", "Letztes Jahr", "Último año", @@ -15723,26 +15723,26 @@ const ROWS: &[[&str; 9]] = &[ "Қай партияларын алу: уақыт бойынша — соңғы партиясынан кері санап; саны бойынша — әр түспен ең жаңалары", ], [ - "💾 Save", - "💾 Сохранить", - "💾 Enregistrer", - "💾 Speichern", - "💾 Guardar", - "💾 Salva", - "💾 Salvar", - "💾 Saqlash", - "💾 Сақтау", + "★ Save", + "★ Сохранить", + "★ Enregistrer", + "★ Speichern", + "★ Guardar", + "★ Salva", + "★ Salvar", + "★ Saqlash", + "★ Сақтау", ], [ - "💾 Saved", - "💾 Сохранено", - "💾 Enregistrée", - "💾 Gespeichert", - "💾 Guardada", - "💾 Salvata", - "💾 Salva", - "💾 Saqlandi", - "💾 Сақталды", + "★ Saved", + "★ Сохранено", + "★ Enregistrée", + "★ Gespeichert", + "★ Guardada", + "★ Salvata", + "★ Salva", + "★ Saqlandi", + "★ Сақталды", ], [ "Kept in the library's «Preparations»: changes are saved by themselves", @@ -15800,15 +15800,15 @@ const ROWS: &[[&str; 9]] = &[ "Дайындықтар", ], [ - "📑 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", @@ -15822,15 +15822,15 @@ const ROWS: &[[&str; 9]] = &[ "Қарсыластарға дайындықтар: сақталғандары және жаңасы", ], [ - "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.", - "Әзірге ештеңе сақталмаған. Ойыншыға дайындалып, есепте «💾 Сақтау» түймесін басыңыз.", + "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…", @@ -15855,15 +15855,15 @@ const ROWS: &[[&str; 9]] = &[ "Алдымен сөреге база қосыңыз", ], [ - "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", - "Таңдалған базадан ойыншыны таңдау", + "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", "ОК"], [ @@ -15901,7 +15901,7 @@ const ROWS: &[[&str; 9]] = &[ ], [ "errors not searched", - "ошибки не искали", + "ошибки ещё не искали", "erreurs non cherchées", "Fehler nicht gesucht", "errores no buscados", @@ -15932,6 +15932,119 @@ const ROWS: &[[&str; 9]] = &[ "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", + "База табылмады: файлды орнына қайтарыңыз немесе дайындықты жойыңыз", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index a99b27f..ca66d98 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -87,7 +87,7 @@ pub enum LibraryAction { path: PathBuf, index: usize, }, - /// «📑 Preparations»: the saved preparations against opponents. + /// «🗐 Preparations»: the saved preparations against opponents. Preparations, /// «Prepare against…» for a player of this database (opponent-prep.md §2). PrepareAgainst { @@ -160,9 +160,9 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { button_w( ui, if icons { - "📑" + "🗐" } else { - tr("📑 Preparations") + tr("🗐 Preparations") }, ) } else { @@ -810,15 +810,15 @@ impl Library { if crate::platform::CAPS.prep { ui.separator(); let label = if icons { - "📑" + "🗐" } else { - tr("📑 Preparations") + tr("🗐 Preparations") }; if ui .button(label) .on_hover_text(shelf_hint( icons, - tr("📑 Preparations"), + tr("🗐 Preparations"), tr("Preparations against opponents: the saved ones and a new one"), )) .clicked() diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index e18e453..91553df 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -381,6 +381,27 @@ const PERIODS: [Period; 8] = [ 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(), @@ -954,7 +975,7 @@ impl PrepList { if self.items.is_empty() { ui.label( RichText::new(tr( - "Nothing saved yet. Prepare against a player and press «💾 Save» on the report.", + "Nothing saved yet. Prepare against a player and press «Save» on the report.", )) .weak(), ); @@ -979,7 +1000,7 @@ impl PrepList { 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")) + .on_hover_text(tr("Choose a player in the current database")) .clicked() { out = Some(ListOutcome::New); @@ -1000,85 +1021,96 @@ impl PrepList { out: &mut Option, ) { 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 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); + 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)]; + if item.period != Period::All { + about.push(period_label(item.period)); } - 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()); + 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"), } - 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())], + .to_owned(), ); - } - let text = RichText::new(line).small(); - ui.label(if found { - text.weak() - } else { - text.color(ui.visuals().warn_fg_color) + ui.add(egui::Label::new(RichText::new(about.join(" · ")).weak()).truncate()); + 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 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 self.deleting.as_deref() == Some(id) { + if deleting { if ui.button(tr("No")).clicked() { self.deleting = None; } - if crate::widgets::primary(ui, tr("Delete")).clicked() { + 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) @@ -1096,15 +1128,62 @@ impl PrepList { if ui.button("✏").on_hover_text(tr("Rename")).clicked() { self.renaming = Some((id.to_owned(), item.title.clone())); } - if ui + open |= ui .add_enabled(found, egui::Button::new(tr("Open"))) - .clicked() - { - *out = Some(ListOutcome::Open(id.to_owned())); - } + .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 ------------------------------------------------------------------ @@ -1336,6 +1415,8 @@ pub struct PrepScreen { 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, report: Option, rows: Vec, /// The games read in the background (hundreds in a moment, a Mega filter in seconds). @@ -1701,6 +1782,7 @@ impl PrepScreen { period, book: start.book, saved: saved.is_some(), + want_period: None, report: None, rows: Vec::new(), build: None, @@ -2866,6 +2948,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); } @@ -2887,9 +2973,9 @@ impl PrepScreen { let compact = row < 700.0; let left = button_w(ui, if compact { "⬅" } else { tr("⬅ Library") }) + 2.0 * gap; let save_label = match (self.saved, compact) { - (false, false) => tr("💾 Save"), - (true, false) => tr("💾 Saved"), - (_, true) => "💾", + (false, false) => tr("★ Save"), + (true, false) => tr("★ Saved"), + (_, true) => "★", }; let right = button_w(ui, if compact { "⚙" } else { tr("⚙ Settings") }) + button_w(ui, save_label); @@ -2948,13 +3034,15 @@ impl PrepScreen { { actions.push(PrepAction::OpenSettings); } + let games = self.report.as_ref().map_or(0, |r| r.games.len()); if self.saved { - ui.add_enabled(false, egui::Button::new(save_label)) - .on_disabled_hover_text(tr( + // 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(self.report.is_some(), egui::Button::new(save_label)) + .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", )) @@ -3011,7 +3099,13 @@ 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 { + 240.0 + }; if let Some(b) = book_picker( ui, "prep_book", @@ -3032,15 +3126,24 @@ 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 { text_width(ui, "♙", egui::TextStyle::Button) + pad + 2.0 * gap } else { 0.0 }; + // The period takes what the depth leaves at its shortest. + let depth_least = text_width( + ui, + &trf("{n} m.", &[("n", &moves)]), + egui::TextStyle::Button, + ) + pad + + 20.0 + + 2.0 * gap; + let period_room = ui.available_width() - engine_w - board_w - depth_least - 2.0 * gap; + self.period_picker(ui, settings, period_room, actions); + ui.separator(); + // The depth's caption by the room left: «Opening: 10 moves», «10 moves», «10 m.». let room = ui.available_width() - engine_w - board_w; let depth_label = [ trf("Opening: {n} moves", &[("n", &moves)]), @@ -3089,50 +3192,82 @@ impl PrepScreen { } /// «Last 2 years · 80 ▾»: which of the player's games, with how many each takes of - /// the colour(s) shown. + /// the colour(s) shown; shorter («2 yrs · 80», «80») when `room` is short. fn period_picker( &mut self, ui: &mut Ui, settings: &mut Settings, + room: f32, 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 report = self.report.as_ref(); + let dated = report.is_some_and(|r| r.pool.iter().any(|g| g.date != 0)); + // Without dates a period by months takes all the games: it is shown as all. + let shown = match self.period { + Period::Months(_) if report.is_some() && !dated => Period::All, + p => p, + }; + let number = |p: Period| -> String { + let Some(r) = report else { + return "…".to_owned(); + }; + match (p, side) { + // «100 + 100»: 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), + } + }; + let pad = 2.0 * ui.spacing().button_padding.x + 20.0; + let selected = [ + format!("{} · {}", period_label(shown), number(shown)), + format!("{} · {}", period_short(shown), number(shown)), + ] + .into_iter() + .find(|t| text_width(ui, t, egui::TextStyle::Button) + pad <= room) + .unwrap_or_else(|| number(shown)); 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. + // Without dates: 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() { + 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 { - 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(), + 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; @@ -3418,6 +3553,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( @@ -4301,6 +4448,21 @@ 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(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), diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs index f58b032..e74a09f 100644 --- a/crates/prep/src/lib.rs +++ b/crates/prep/src/lib.rs @@ -41,7 +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 period::{Chosen, Period, PoolGame, newest as period_newest}; pub use players::{Candidate, Player, candidates, games_of}; pub use tree::{Node, Tree}; diff --git a/crates/prep/src/period.rs b/crates/prep/src/period.rs index a698773..ef55de8 100644 --- a/crates/prep/src/period.rs +++ b/crates/prep/src/period.rs @@ -2,7 +2,8 @@ //! 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). +//! 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}; @@ -59,7 +60,7 @@ pub fn choose(pool: &[PoolGame], period: Period) -> Vec<(u32, bool)> { Period::Months(months) => { let newest = newest(pool); if newest == 0 { - return Vec::new(); + return choose(pool, Period::All); } let from = cutoff(newest, months); pool.iter() @@ -94,7 +95,7 @@ pub fn count(pool: &[PoolGame], period: Period, side: Side) -> Chosen { .filter(|(_, w)| of_side(*w)) .count(); let undated_out = match period { - Period::Months(_) => pool + Period::Months(_) if newest(pool) != 0 => pool .iter() .filter(|g| g.date == 0 && of_side(g.white)) .count(), @@ -136,8 +137,13 @@ mod tests { 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()); + // 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] From 758856f4581f1ed0cd16a326a32dc9e2a1a317a3 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 21:54:03 +0300 Subject: [PATCH 04/10] Opponent prep: the tester's findings A saved preparation is the player's by his names, not the database's name ids (they shift when a game is deleted or the file is replaced): opened from the list, the names are found again. The period counts are of the games a report can take (set-up games left out first). A partly known date is in a period when any day it can mean is; a date after today is not the newest. Reopening a hidden report notices a deleted preparation; a colour change is saved. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 35 ++++++++++--- apps/desktop/src/i18n.rs | 11 ++++ apps/desktop/src/prep_saved.rs | 18 ++++--- apps/desktop/src/prep_ui.rs | 19 +++++-- crates/prep/src/lib.rs | 29 ++++++---- crates/prep/src/period.rs | 96 ++++++++++++++++++++++++++++------ 6 files changed, 165 insertions(+), 43 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 1ca6b61..be12c29 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -289,7 +289,8 @@ pub struct App { /// The library's «Preparations» window, and a saved preparation waiting for its /// database to be read. prep_list: Option, - prep_waiting: Option, + /// The names of its player, found again in the database once it is read. + prep_waiting: Option<(crate::prep_ui::PrepStart, Vec)>, /// Quitting while the opening errors are searched: asked first; «Quit» answered. prep_quit_ask: bool, prep_quit_ok: bool, @@ -941,9 +942,31 @@ 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); + 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 { + let (found, _) = prep::candidates(&db, name, 50); + match found.iter().find(|c| c.name == *name) { + Some(c) => ids.push(c.id), + None => 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( @@ -951,7 +974,7 @@ impl App { trf("This database cannot be opened: {e}", &[("e", &e)]), ); } else { - self.prep_waiting = Some(start); + self.prep_waiting = Some((start, names)); } } let Some(list) = self.prep_list.as_mut() else { @@ -998,7 +1021,7 @@ impl App { self.library.load(&start.path, ctx); self.toast(ctx, tr("Opening the database…")); } - self.prep_waiting = Some(start); + self.prep_waiting = Some((start, meta.names)); ctx.request_repaint(); } None => {} diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 80cfca9..d0e16b9 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -16045,6 +16045,17 @@ const ROWS: &[[&str; 9]] = &[ "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}", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/prep_saved.rs b/apps/desktop/src/prep_saved.rs index 738ba42..55106dc 100644 --- a/apps/desktop/src/prep_saved.rs +++ b/apps/desktop/src/prep_saved.rs @@ -40,8 +40,10 @@ 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 { +/// 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); @@ -50,8 +52,12 @@ pub fn id(path: &Path, player: &Player) -> String { for b in path.to_string_lossy().bytes() { eat(b); } - for id in &player.ids { - for b in id.to_le_bytes() { + 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); } } @@ -110,7 +116,7 @@ pub fn report(dir: &Path, id: &str) -> Option { /// 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 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)?; @@ -183,7 +189,7 @@ mod tests { let l = list(&dir); assert_eq!(l.len(), 2); assert_eq!(l[0].1, a2); - let ida = id(&a.path, &a.player); + 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"); diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index 91553df..207096d 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -1735,7 +1735,8 @@ impl PrepScreen { 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 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)); @@ -1759,7 +1760,10 @@ impl PrepScreen { if r.search != game_review::SEARCH_VERSION { return None; } - if r.fingerprint == prep::fingerprint(&db) && r.options() == options { + if r.fingerprint == prep::fingerprint(&db) + && r.options() == options + && r.player == start.player + { return Some(r); } for (k, e) in r.evals { @@ -1767,7 +1771,6 @@ impl PrepScreen { } None }); - let names = start.player.names(&db); let mut screen = PrepScreen { serial: crate::engine_offer::next_serial(), db_name: base_name(&start.path), @@ -1920,6 +1923,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; @@ -1929,6 +1936,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 { @@ -2463,7 +2472,7 @@ impl PrepScreen { } // 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)) + crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names)) .is_some() }); if self.saved @@ -2485,7 +2494,7 @@ impl PrepScreen { let Some(report) = &self.report else { return Ok(()); }; - let id = crate::prep_saved::id(&self.path, &self.player); + 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()); diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs index e74a09f..fd97d7d 100644 --- a/crates/prep/src/lib.rs +++ b/crates/prep/src/lib.rs @@ -237,18 +237,26 @@ pub fn build( cancel: &AtomicBool, ) -> Option { let found = games_of(db, player, options.side, cancel)?; - let pool: Vec = found + // 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 = collected + .games .iter() - .map(|&(index, white)| PoolGame { - index, - white, - date: chess_import::pgn_catalog::date_number(&db.row(index as usize).date), + .map(|g| PoolGame { + index: g.index, + white: g.white, + date: g.date_number(), }) .collect(); - let chosen = period::choose(&pool, options.period); - let collected = games::collect(db, &chosen, options.plies, progress, cancel)?; + 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 = 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) { @@ -888,8 +896,9 @@ mod tests { .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; + // 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); diff --git a/crates/prep/src/period.rs b/crates/prep/src/period.rs index ef55de8..45bf790 100644 --- a/crates/prep/src/period.rs +++ b/crates/prep/src/period.rs @@ -38,33 +38,73 @@ pub struct Chosen { 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 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, + } } -/// 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 +/// 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 of the player's newest game as written (0: none dated). A date after +/// `today` is a typo («2206») and does not count as the newest. +fn newest_at(pool: &[PoolGame], today: u32) -> u32 { + pool.iter() + .filter(|g| g.date != 0 && g.date / 10000 * 10000 <= today) + .max_by_key(|g| (latest(g.date).min(today), g.date)) + .map_or(0, |g| g.date) +} + +/// 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(pool); + let newest = newest_at(pool, today); if newest == 0 { - return choose(pool, Period::All); + return choose_at(pool, Period::All, today); } - let from = cutoff(newest, months); + let from = cutoff(latest(newest).min(today), months); pool.iter() - .filter(|g| g.date != 0 && g.date >= from) + .filter(|g| g.date != 0 && latest(g.date) >= from) .map(|g| (g.index, g.white)) .collect() } @@ -124,7 +164,31 @@ mod tests { ]; assert_eq!(cutoff(20260301, 12), 20250301); assert_eq!(cutoff(20260115, 1), 20251215); - assert_eq!(cutoff(20260000, 24), 20240000); + // 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), + ]; + // «2026» is up to today: three months back is 2026.07.31 — July 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![(0, true), (1, true)] + ); assert_eq!( choose(&pool, Period::Months(12)), vec![(3, true), (5, true)] From e2f4935ecc0d294a58c5fc7180a1b8f9a33e65bd Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 21:58:10 +0300 Subject: [PATCH 05/10] Opponent prep: the newest game by its earliest day; dates after today are typos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One game of «2026.??.??» no longer moves a period past the exactly dated games; a date after today counts as none (in periods and in «Last N»). Every colour change goes through set_color; a name with two ids in the database takes both. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 8 +++++--- apps/desktop/src/prep_ui.rs | 12 +++++++---- crates/prep/src/period.rs | 41 +++++++++++++++++++++++++------------ 3 files changed, 41 insertions(+), 20 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index be12c29..a19c31a 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -948,10 +948,12 @@ impl App { 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); - match found.iter().find(|c| c.name == *name) { - Some(c) => ids.push(c.id), - None => missing = Some(name.clone()), + 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 { diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index 207096d..5c66bda 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -4497,7 +4497,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 + })); } }); } @@ -6061,13 +6065,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); diff --git a/crates/prep/src/period.rs b/crates/prep/src/period.rs index 45bf790..4798015 100644 --- a/crates/prep/src/period.rs +++ b/crates/prep/src/period.rs @@ -66,13 +66,17 @@ fn today() -> u32 { (y * 10000 + m * 100 + d) as u32 } -/// The date of the player's newest game as written (0: none dated). A date after -/// `today` is a typo («2206») and does not count as the newest. +/// 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() - .filter(|g| g.date != 0 && g.date / 10000 * 10000 <= today) - .max_by_key(|g| (latest(g.date).min(today), g.date)) - .map_or(0, |g| g.date) + 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). @@ -104,7 +108,7 @@ fn choose_at(pool: &[PoolGame], period: Period, today: u32) -> Vec<(u32, bool)> } let from = cutoff(latest(newest).min(today), months); pool.iter() - .filter(|g| g.date != 0 && latest(g.date) >= from) + .filter(|g| known(g.date, today) != 0 && latest(g.date) >= from) .map(|g| (g.index, g.white)) .collect() } @@ -113,7 +117,11 @@ fn choose_at(pool: &[PoolGame], period: Period, today: u32) -> Vec<(u32, bool)> 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))); + 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 @@ -173,7 +181,8 @@ mod tests { g(1, true, 20250301), g(2, true, 20260700), ]; - // «2026» is up to today: three months back is 2026.07.31 — July is in. + // 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)] @@ -185,10 +194,16 @@ mod tests { g(2, true, 20250101), ]; assert_eq!(newest_at(&typo, today), 20260301); - assert_eq!( - choose_at(&typo, Period::Months(6), today), - vec![(0, true), (1, true)] - ); + 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)] From d4c141a84144be865de30cb0d83211c19301104d Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 21:58:56 +0300 Subject: [PATCH 06/10] Opponent prep: combos as wide as their text, no search or save in no games MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The period and the depth fit at 640 px with their middle captions; the header counts the games of the colour shown; the empty-period note names the colour; the preparations list says «за 2 года · 8 партий» and «последние 100». Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/i18n.rs | 33 +++++++++++++++++++++++++ apps/desktop/src/prep_ui.rs | 49 +++++++++++++++++++++++++++++++------ 2 files changed, 75 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index d0e16b9..96c6398 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -16056,6 +16056,39 @@ const ROWS: &[[&str; 9]] = &[ "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}", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index 5c66bda..c5a63c5 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -1053,10 +1053,21 @@ impl PrepList { .on_hover_text(tr("Double-click to open")); open |= found && title.double_clicked(); let mut about = vec![base_name(&item.path)]; - if item.period != Period::All { - about.push(period_label(item.period)); + // «за 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(crate::i18n::games(item.games as usize)); about.push( match item.color { ColorChoice::White => tr("as White"), @@ -1952,6 +1963,17 @@ 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 { @@ -3002,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); @@ -3043,7 +3065,7 @@ impl PrepScreen { { actions.push(PrepAction::OpenSettings); } - let games = self.report.as_ref().map_or(0, |r| r.games.len()); + 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)) @@ -3163,7 +3185,9 @@ impl PrepScreen { .find(|l| text_width(ui, l, egui::TextStyle::Button) + pad + 20.0 + gap <= room) .unwrap_or_else(|| trf("{n} m.", &[("n", &moves)])); 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] { @@ -3240,7 +3264,10 @@ impl PrepScreen { .find(|t| text_width(ui, t, egui::TextStyle::Button) + pad <= room) .unwrap_or_else(|| number(shown)); 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 { @@ -3377,7 +3404,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() { @@ -4462,7 +4493,11 @@ impl PrepScreen { 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(tr("No games in this period")); + 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))) From eb3b8fd8df3a86eb5078bbc0be8303153cbfc396 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 22:01:11 +0300 Subject: [PATCH 07/10] Opponent prep: more room for the period's middle caption Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/prep_ui.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index c5a63c5..3dec6a3 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -3134,6 +3134,8 @@ impl PrepScreen { 120.0 } else if width < 900.0 { 150.0 + } else if width < 1100.0 { + 180.0 } else { 240.0 }; @@ -3171,7 +3173,7 @@ impl PrepScreen { ) + pad + 20.0 + 2.0 * gap; - let period_room = ui.available_width() - engine_w - board_w - depth_least - 2.0 * gap; + let period_room = ui.available_width() - engine_w - board_w - depth_least; self.period_picker(ui, settings, period_room, actions); ui.separator(); // The depth's caption by the room left: «Opening: 10 moves», «10 moves», «10 m.». From a3532d6a73a79fc143316bbe6e5e291d8c611e95 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 22:01:11 +0300 Subject: [PATCH 08/10] Open a downloaded game on Lichess or Chess.com MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The game screen has a globe after the result and an item in ☰ when the game's Link or Site is a web address: a Lichess game opens at the move shown, from the side at the bottom of the board; a Chess.com game (its Link tag) at its page. The game list's context menu opens it too. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/game_link.rs | 123 ++++++++++++++++++++++++++++++++++ apps/desktop/src/game_view.rs | 50 ++++++++++++-- apps/desktop/src/i18n.rs | 55 +++++++++++++++ apps/desktop/src/large_db.rs | 11 +++ apps/desktop/src/lib.rs | 1 + 5 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/game_link.rs diff --git a/apps/desktop/src/game_link.rs b/apps/desktop/src/game_link.rs new file mode 100644 index 0000000..fa56f44 --- /dev/null +++ b/apps/desktop/src/game_link.rs @@ -0,0 +1,123 @@ +//! 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, +} + +/// The game's web address from its tags (Link first, then Site), if it has one. +pub fn of(tag: impl Fn(&str) -> Option) -> Option { + 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(), + } + } + + /// «🌐 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 { + 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()); + } +} diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 4e54fa6..08a129c 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -328,6 +328,17 @@ impl GameView { } } + /// The game's web page, if its tags have one. + fn link(&self) -> Option { + 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( @@ -1020,17 +1031,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 +1133,14 @@ impl GameView { ) .on_hover_text(result_hint); } + if let Some(l) = &link + && ui + .small_button("🌐") + .on_hover_text(format!("{} — {}", l.label(), tr("in the browser"))) + .clicked() + { + self.open_link(ui.ctx(), l); + } }); let sub: Vec = 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()); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 96c6398..6adefc2 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -16089,6 +16089,61 @@ const ROWS: &[[&str; 9]] = &[ "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 in the browser", + "🌐 Открыть в браузере", + "🌐 Ouvrir dans le navigateur", + "🌐 Im Browser öffnen", + "🌐 Abrir en el navegador", + "🌐 Apri nel browser", + "🌐 Abrir no navegador", + "🌐 Brauzerda ochish", + "🌐 Браузерде ашу", + ], + [ + "in the browser", + "в браузере", + "dans le navigateur", + "im Browser", + "en el navegador", + "nel browser", + "no navegador", + "brauzerda", + "браузерде", + ], ]; #[cfg(test)] diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 0be27f7..d93d60d 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -2260,6 +2260,17 @@ impl LargeView { opened = Some(index); ui.close(); } + // A game downloaded from Lichess or Chess.com: its page. + let online = r.site.to_ascii_lowercase().contains("lichess.org") + || r.site.trim().eq_ignore_ascii_case("chess.com"); + if online && ui.button(tr("🌐 Open in the browser")).clicked() { + if let Some(link) = db.load_game(index).and_then(|p| { + crate::game_link::of(|t| p.game.tag(t).map(str::to_owned)) + }) { + 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(); diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index ed0ecbf..af68f60 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -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; From b682755f0e08259d4d946d2fb47c0b7e1c5df465 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 22:04:09 +0300 Subject: [PATCH 09/10] Prep row shortens in one order; the game link as in its header everywhere The period and the depth captions are chosen together: the depth gives way first at every width. The list's context menu reads the game's link (once per menu) and names the site as the game screen does; the header's subtitle leaves the web address to the globe, whose tooltip says what opens. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/game_link.rs | 10 ++++ apps/desktop/src/game_view.rs | 10 ++-- apps/desktop/src/i18n.rs | 58 ++++++++++++------ apps/desktop/src/large_db.rs | 21 ++++--- apps/desktop/src/prep_ui.rs | 108 +++++++++++++++++++--------------- 5 files changed, 129 insertions(+), 78 deletions(-) diff --git a/apps/desktop/src/game_link.rs b/apps/desktop/src/game_link.rs index fa56f44..a29f587 100644 --- a/apps/desktop/src/game_link.rs +++ b/apps/desktop/src/game_link.rs @@ -69,6 +69,16 @@ impl GameLink { } } + /// 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 { diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 08a129c..025fc06 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -355,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()); } @@ -1134,10 +1137,7 @@ impl GameView { .on_hover_text(result_hint); } if let Some(l) = &link - && ui - .small_button("🌐") - .on_hover_text(format!("{} — {}", l.label(), tr("in the browser"))) - .clicked() + && ui.button("🌐").on_hover_text(l.hint()).clicked() { self.open_link(ui.ctx(), l); } diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 6adefc2..4a01fb5 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -16123,26 +16123,48 @@ const ROWS: &[[&str; 9]] = &[ "🌐 Партия сілтемесін ашу", ], [ - "🌐 Open in the browser", - "🌐 Открыть в браузере", - "🌐 Ouvrir dans le navigateur", - "🌐 Im Browser öffnen", - "🌐 Abrir en el navegador", - "🌐 Apri nel browser", - "🌐 Abrir no navegador", - "🌐 Brauzerda 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-те ашу (браузерде, осы жүрістен)", ], [ - "in the browser", - "в браузере", - "dans le navigateur", - "im Browser", - "en el navegador", - "nel browser", - "no navegador", - "brauzerda", - "браузерде", + "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)", + "Партия сілтемесін ашу (браузерде)", ], ]; diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index d93d60d..a50c0cd 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -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, + /// The web page of the game whose context menu is open (its record, the link). + menu_link: Option<(usize, Option)>, } impl LargeView { @@ -426,6 +428,7 @@ impl LargeView { drawer_asked: false, drawer_top: 0.0, prepare: None, + menu_link: None, } } @@ -2260,15 +2263,17 @@ impl LargeView { opened = Some(index); ui.close(); } - // A game downloaded from Lichess or Chess.com: its page. - let online = r.site.to_ascii_lowercase().contains("lichess.org") - || r.site.trim().eq_ignore_ascii_case("chess.com"); - if online && ui.button(tr("🌐 Open in the browser")).clicked() { - if let Some(link) = db.load_game(index).and_then(|p| { + // 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)) - }) { - ui.ctx().open_url(egui::OpenUrl::new_tab(link.at(0, false))); - } + }); + 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). diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index 3dec6a3..5584388 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -3165,27 +3165,26 @@ impl PrepScreen { } else { 0.0 }; - // The period takes what the depth leaves at its shortest. - let depth_least = text_width( - ui, - &trf("{n} m.", &[("n", &moves)]), - egui::TextStyle::Button, - ) + pad - + 20.0 - + 2.0 * gap; - let period_room = ui.available_width() - engine_w - board_w - depth_least; - self.period_picker(ui, settings, period_room, actions); - ui.separator(); - // The depth's caption by the room left: «Opening: 10 moves», «10 moves», «10 m.». - 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") @@ -3226,45 +3225,60 @@ 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; shorter («2 yrs · 80», «80») when `room` is short. + /// the colour(s) shown; `selected` is the caption the row has room for. fn period_picker( &mut self, ui: &mut Ui, settings: &mut Settings, - room: f32, + selected: String, actions: &mut Vec, ) { 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)); - // Without dates a period by months takes all the games: it is shown as all. - let shown = match self.period { - Period::Months(_) if report.is_some() && !dated => Period::All, - p => p, - }; - let number = |p: Period| -> String { - let Some(r) = report else { - return "…".to_owned(); - }; - match (p, side) { - // «100 + 100»: 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), - } - }; - let pad = 2.0 * ui.spacing().button_padding.x + 20.0; - let selected = [ - format!("{} · {}", period_label(shown), number(shown)), - format!("{} · {}", period_short(shown), number(shown)), - ] - .into_iter() - .find(|t| text_width(ui, t, egui::TextStyle::Button) + pad <= room) - .unwrap_or_else(|| number(shown)); + 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; From 3803165491470a13d7595a859445f0435688ae41 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 22:04:39 +0300 Subject: [PATCH 10/10] Changelog, decisions and tasks: periods, saved preparations, game links Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +++++++++++ docs/decisions.md | 4 ++++ docs/dev/tasks.md | 4 ++-- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1138664..75d1cf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/decisions.md b/docs/decisions.md index 6d3ffc1..57ec315 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -242,3 +242,7 @@ - **Партии без даты** берутся только во «Всех партиях». При выборе периода под списком написано, сколько их не учтено. Если дат нет ни у одной партии, выбор по времени не показывается, остаётся выбор по числу: последние записи базы. - **Сохранённые подготовки.** Кнопка «💾 Сохранить» в шапке отчёта. Подготовка лежит в данных программы (`~/.local/share/chesspenguin/preparations/`, не в кэше): отчёт вместе с найденными ошибками. На каждого игрока базы — одна подготовка: повторное сохранение заменяет прежнюю. После сохранения все изменения (поиск ошибок, период, глубина) записываются туда сами. - **Где их открыть.** Кнопка «📑 Подготовки» в библиотеке: список (имя, база, период, партии, цвет, ошибки, дата), там же «Открыть», «Переименовать», «Удалить» и «♟ Новая подготовка…». Если в базе появились новые партии, подготовка собирается заново с прежними оценками, и движок досчитывает только новые позиции. + +## Партия на Lichess / Chess.com (2026-10-31) + +Владелец: из скачанной партии перейти на её страницу. Ссылка берётся из тега Link (Chess.com), иначе из Site (Lichess), если там веб-адрес. Кнопка «🌐» в шапке партии после результата, пункт в ☰ и в контекстном меню строки списка партий. Партия Lichess открывается на показанном ходу (`#ply`) и со стороны, которая внизу доски (`/black`); у Chess.com такой ссылки нет — открывается страница партии. Адрес из подстроки шапки убран: его открывает глобус. diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index 0215bf0..2ef59b1 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`, «какие партии брать». Время считается от последней партии соперника; партии без даты учитываются только во «Всех»; если дат нет совсем — выбор только по числу. +- **Статус:** сделано в ветке `prep-period-saved` (2026-10-31), проверено тестировщиком и дизайнером. Решения — `docs/decisions.md`, «какие партии брать». Время считается от последней партии соперника; партии без даты учитываются только во «Всех»; если дат нет совсем — выбор только по числу. - **Суть:** выбирать, насколько старые партии соперника учитывать: «за последние N месяцев/лет от сегодня» или «последние N партий». Что делать, если у партий нет дат, — владелец не знает; нужно продумать (например, порядок партий в базе как замена даты, или такие партии всегда учитываются / показываются отдельно). ### 21. Подготовка к сопернику: сохранять анализ и возвращаться к нему — база подготовок (2026-10-28) -- **Статус:** сделано в ветке `prep-period-saved` (2026-10-31), ждёт проверки: «💾 Сохранить» в отчёте, «📑 Подготовки» в библиотеке (открыть, переименовать, удалить, новая). Одна подготовка на игрока базы. +- **Статус:** сделано в ветке `prep-period-saved` (2026-10-31), проверено тестировщиком и дизайнером: «★ Сохранить» в отчёте, «🗐 Подготовки» в библиотеке (открыть, переименовать, удалить, новая). Одна подготовка на игрока базы. - **Суть:** сделанная подготовка (соперник, база, цвет, найденные ошибки, отметки) сохраняется, и к ней можно вернуться позже — по сути своя «база подготовок»: список подготовок к разным соперникам, открыть, обновить по новым партиям. Сейчас отчёт только кэшируется на диске и открывается заново при повторном входе к тому же игроку той же базы. ### 22. Веб-версия: ChessPenguin в браузере (2026-10-30)