From 758856f4581f1ed0cd16a326a32dc9e2a1a317a3 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 31 Oct 2026 21:54:03 +0300 Subject: [PATCH] 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)]