From 3f16ba50feb03eddc37f6479ed6e90112e846d62 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 19 Oct 2026 23:20:37 +0300 Subject: [PATCH 1/7] =?UTF-8?q?=D0=A1=D0=BF=D1=80=D0=B0=D0=B2=D0=BE=D1=87?= =?UTF-8?q?=D0=BD=D0=B8=D0=BA=20(Reference)=20tab:=20moves=20and=20games?= =?UTF-8?q?=20of=20the=20current=20position=20in=20a=20shelf=20database?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two tables (moves with statistics; strongest/newest games with how they went on), theory of the game and its copies in the database, a stack of games opened from it with no lost edits, background work cancellable. Reviewed by independent designer and tester agents; their findings fixed and re-verified. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + apps/desktop/src/app.rs | 119 +- apps/desktop/src/board_search.rs | 6 +- apps/desktop/src/game_view.rs | 142 +- apps/desktop/src/i18n.rs | 477 +++++- apps/desktop/src/library.rs | 28 +- apps/desktop/src/main.rs | 1 + apps/desktop/src/reference.rs | 1646 +++++++++++++++++++++ apps/desktop/src/settings.rs | 3 + crates/chess-import/src/chessbase/base.rs | 11 + docs/design/reference.md | 71 + docs/dev/desktop.md | 2 +- 12 files changed, 2480 insertions(+), 39 deletions(-) create mode 100644 apps/desktop/src/reference.rs create mode 100644 docs/design/reference.md diff --git a/CHANGELOG.md b/CHANGELOG.md index cf882c7..45a1952 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- «Справочник» (Reference) tab of a game: what was played in the current position in a + database of the shelf (Mega for theory, an opening collection, a pupil's games), as two + tables — the moves with games, share, results, White's score, average rating, year and + the best players who played them, and the strongest (or newest) games that reached the + position with how they went on. Click a move to see its games, double-click to play it; + double-click a game to open it at this position (the current game stays a click away: + "⬅ Back to …", unsaved edits included). It also tells how far the game follows the + database ("known up to 13…Bf5") and finds the game itself there (to open, for example, an + annotated copy). +- Russian numbers use a decimal comma ("11,7 млн"). + ## [0.6.3] — 2026-10-19 - Import notes (for example, Chess960 games shown without moves) are a quiet grey "ℹ" now diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 26633af..61a52b3 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -29,6 +29,8 @@ enum Async { enum CloseIntent { BackToLibrary, QuitApp, + /// Back to the game this one was opened from (reference tab). + ReturnToPrevious, } pub struct App { @@ -52,6 +54,13 @@ pub struct App { offer_hook_done: bool, /// A position to find in a database once the game is closed. find_after_close: Option<(PathBuf, shakmaty::Chess, Vec, bool)>, + /// Games left for one opened from the reference tab ("⬅ Back to …"), kept as they + /// were (unsaved edits included). + previous_games: Vec, + /// The last game showed the reference tab: the next one opens with it too. + reference_tab: bool, + /// The reference tab of games (kept across games: its results stay cached). + reference: crate::reference::Reference, allow_quit: bool, applied_dark: Option, debug: DebugStartup, @@ -135,6 +144,9 @@ impl App { confirm_close: None, close_after_save: None, find_after_close: None, + previous_games: Vec::new(), + reference_tab: false, + reference: Default::default(), engine_offer: crate::engine_offer::EngineOffer::new(), offer_hook_done: false, allow_quit: false, @@ -410,6 +422,11 @@ impl App { }), parsed.diagnostics, )); + if self.reference_tab + && let Some(g) = self.game.as_mut() + { + g.show_reference_tab(); + } if let (Some(target), Some(g)) = (at, self.game.as_mut()) { g.goto_position(&target); } @@ -432,7 +449,37 @@ impl App { fn finish_close(&mut self, ctx: &egui::Context, intent: CloseIntent) { self.analysis.stop(); self.live_paused = false; - if let Some(g) = self.game.take() + let closed = self.game.take(); + if intent == CloseIntent::ReturnToPrevious { + self.game = self.previous_games.pop(); + return; + } + // Games left for others (reference tab) with unsaved edits come first: the last + // such one is shown again and, when quitting, asked about; the library (or the + // search board) waits until none is left. + if let Some(k) = self + .previous_games + .iter() + .rposition(|g| g.game.is_modified()) + { + self.previous_games.truncate(k + 1); + self.game = self.previous_games.pop(); + if let Some(g) = &self.game { + let msg = trf( + "Back to {game}: it has unsaved changes", + &[("game", &g.title())], + ); + self.toast(ctx, msg); + } + if intent == CloseIntent::QuitApp { + self.confirm_close = Some(CloseIntent::QuitApp); + } + // The search board asked for was for the game just closed: not later. + self.find_after_close = None; + return; + } + self.previous_games.clear(); + if let Some(g) = closed && let Some(src) = g.source { self.library.reveal(&src.path, src.index); @@ -440,6 +487,7 @@ impl App { if let Some((path, start, line, flipped)) = self.find_after_close.take() { self.library.show_position(&path, start, line, flipped, ctx); } + if intent == CloseIntent::QuitApp { self.allow_quit = true; ctx.send_viewport_cmd(egui::ViewportCommand::Close); @@ -590,6 +638,9 @@ impl App { egui::Modal::new(egui::Id::new("confirm_close")).show(ctx, |ui| { ui.set_width(380.0); ui.heading(tr("Game modified")); + if let Some(g) = &self.game { + ui.label(RichText::new(g.title()).strong()); + } ui.label(tr( "The source PGN is not changed. Save the changes to a separate file?", )); @@ -636,6 +687,19 @@ impl eframe::App for App { }); self.applied_dark = Some(self.settings.dark_mode); } + // Quitting with a modified game left for another (reference tab): show that one, + // so the question "save?" is about the game that has the changes. + if ctx.input(|i| i.viewport().close_requested()) + && !self.allow_quit + && !self.game.as_ref().is_some_and(|g| g.game.is_modified()) + && let Some(k) = self + .previous_games + .iter() + .rposition(|g| g.game.is_modified()) + { + self.previous_games.truncate(k + 1); + self.game = self.previous_games.pop(); + } if ctx.input(|i| i.viewport().close_requested()) && !self.allow_quit && self.game.as_ref().is_some_and(|g| g.game.is_modified()) @@ -671,11 +735,62 @@ impl eframe::App for App { if let Some(game) = &mut self.game { let input_enabled = self.confirm_close.is_none(); - let actions = game.show(ui, &mut self.settings, &mut self.analysis, input_enabled); + // A database opened for the reference tab arrives here (the library is + // not drawn while a game is shown). + self.library.poll(); + self.reference.dbs = self + .settings + .databases + .iter() + .filter(|p| p.exists()) + .map(|p| crate::reference::RefDb { + path: p.clone(), + name: p + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + db: self.library.database(p), + failed: self.library.failure(p).map(str::to_owned), + bytes: self.library.file_size(p), + }) + .collect(); + let actions = game.show( + ui, + &mut self.settings, + &mut self.analysis, + &mut self.reference, + input_enabled, + ); + self.reference_tab = game.reference_tab(); for a in actions { match a { GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary), GameAction::FindPosition(db) => self.find_position(&ctx, db), + GameAction::ReferenceChoose(p) => { + self.settings.reference_db = Some(p); + self.settings_dirty = true; + } + GameAction::ReferenceLoad(p) => self.library.load(&p, &ctx), + GameAction::OpenGame(path, index, at) => { + if let Some(prev) = self.game.take() { + let title = prev.title(); + self.previous_games.push(prev); + self.open_game(&ctx, path, index, Some(at)); + match &mut self.game { + Some(g) => { + g.previous = Some(title); + g.show_reference_tab(); + } + // Not opened: back to where we were. + None => self.game = self.previous_games.pop(), + } + } + } + GameAction::ReturnToPrevious => { + if !self.previous_games.is_empty() { + self.request_close(&ctx, CloseIntent::ReturnToPrevious); + } + } GameAction::NeedEngine => self .engine_offer .ask(crate::engine_offer::Pending::GameAnalysis, &self.settings), diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index 9ce519f..4c2dfb3 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -25,7 +25,7 @@ const WIDE: f32 = 820.0; const CONTINUATIONS_WIDTH: f32 = 360.0; /// Arrow of a previewed move (continuation or a game's next move): blue, unlike the /// engine's green arrows. -const PREVIEW_ARROW: Color32 = Color32::from_rgba_premultiplied(40, 110, 200, 190); +pub const PREVIEW_ARROW: Color32 = Color32::from_rgba_premultiplied(40, 110, 200, 190); /// What the board asks of its owner. pub enum BoardEvent { @@ -661,7 +661,7 @@ fn move_label(pos: &Chess, m: Move, first: bool) -> String { } /// One continuation: number, move, games, share, results bar, average rating, year. -fn continuation_row( +pub fn continuation_row( ui: &mut Ui, i: usize, pos: &Chess, @@ -761,7 +761,7 @@ fn continuation_row( /// White wins (light), draws (grey), Black wins (dark), with the percentages inside /// wide enough segments: readable without telling colours apart. -fn results_bar(ui: &Ui, rect: egui::Rect, t: &Tally, _text: Color32) { +pub fn results_bar(ui: &Ui, rect: egui::Rect, t: &Tally, _text: Color32) { let decided = t.white_wins + t.draws + t.black_wins; let painter = ui.painter(); if decided == 0 { diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 575a791..05a8bba 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -1,6 +1,7 @@ //! Game screen: board with eval bar, engine lines with PV preview, notation, toolbar. use crate::i18n::{tr, trf}; +use crate::reference::RefAction; use std::path::PathBuf; use chess_core::shakmaty::{Chess, Color, Move, Position, Square}; @@ -56,11 +57,15 @@ pub struct GameView { engine_settings_open: bool, review: Review, side_tab: SideTab, + /// The game this one was opened from (reference tab): the title for "← back to". + pub previous: Option, } #[derive(Clone, Copy, PartialEq, Eq)] enum SideTab { Notation, + /// What was played here in a database (`reference.rs`). + Reference, Report, } @@ -85,6 +90,12 @@ pub enum GameAction { FindPosition(Option), /// Game analysis needs an engine that is not there yet (offer to download one). NeedEngine, + /// The reference tab: use / load a database, open one of its games. + ReferenceChoose(std::path::PathBuf), + ReferenceLoad(std::path::PathBuf), + OpenGame(std::path::PathBuf, usize, Chess), + /// Back to the game this one was opened from. + ReturnToPrevious, } impl GameView { @@ -103,7 +114,13 @@ impl GameView { show_diagnostics: false, engine_settings_open: false, review, - side_tab: SideTab::Notation, + // Dev hook (screenshots): `CP_TAB=reference` opens that tab. + side_tab: if std::env::var("CP_TAB").as_deref() == Ok("reference") { + SideTab::Reference + } else { + SideTab::Notation + }, + previous: None, } } @@ -132,6 +149,20 @@ impl GameView { parts.join(" · ") } + /// A move made on the board or picked in the reference tab: goes to it if the + /// game has it, else adds it (undoable). + fn play_move(&mut self, m: Move, actions: &mut Vec) { + match self.game.add_move(self.cursor, m) { + Ok(id) => { + self.goto(id); + if let Some(s) = self.sound_for(id) { + actions.push(GameAction::Sound(s)); + } + } + Err(e) => actions.push(GameAction::Toast(trf("Move not added: {e}", &[("e", &e)]))), + } + } + fn goto(&mut self, id: NodeId) { if id != self.cursor { self.cursor = id; @@ -192,6 +223,7 @@ impl GameView { ui: &mut Ui, settings: &mut Settings, analysis: &mut Analysis, + reference: &mut crate::reference::Reference, input_enabled: bool, ) -> Vec { let mut actions = Vec::new(); @@ -217,16 +249,26 @@ impl GameView { egui::Panel::top("game_header").show(ui, |ui| self.header(ui, &databases, &mut actions)); // Keep room for the board on narrow windows: the side panel never exceeds 60 %. let width = ui.available_width(); - egui::Panel::right("game_side") + // The reference tab has two wide tables: its own (wider) panel width, which + // egui remembers apart from the notation's. + let (side_id, side_width) = if self.side_tab == SideTab::Reference { + ("game_side_reference", (width * 0.55).clamp(360.0, 1100.0)) + } else { + ("game_side", (width * 0.4).clamp(260.0, 460.0)) + }; + egui::Panel::right(side_id) .resizable(true) - .default_size((width * 0.4).clamp(260.0, 460.0)) - .size_range(240.0_f32.min(width * 0.5)..=(width * 0.6).max(240.0)) + .default_size(side_width) + .size_range(240.0_f32.min(width * 0.5)..=(width * 0.7).max(240.0)) .show(ui, |ui| { - self.side_panel(ui, settings, analysis, &mut actions) + self.side_panel(ui, settings, analysis, reference, &mut actions) }); self.sync_analysis(analysis); + let hover = (self.side_tab == SideTab::Reference) + .then(|| reference.hover()) + .flatten(); egui::CentralPanel::default().show(ui, |ui| { - self.board_area(ui, &*settings, analysis, &mut actions) + self.board_area(ui, &*settings, analysis, hover, &mut actions) }); self.sync_analysis(analysis); @@ -366,6 +408,14 @@ impl GameView { { actions.push(GameAction::Back); } + if let Some(t) = &self.previous + && ui + .button(trf("⬅ Back to {game}", &[("game", t)])) + .on_hover_text(tr("The game this one was opened from, as you left it")) + .clicked() + { + actions.push(GameAction::ReturnToPrevious); + } ui.separator(); ui.vertical(|ui| { let modified = if self.game.is_modified() { " •" } else { "" }; @@ -454,6 +504,7 @@ impl GameView { ui: &mut Ui, settings: &Settings, analysis: &Analysis, + reference_hover: Option, actions: &mut Vec, ) { let preview_pos = self.preview.as_ref().map(|p| p.position()); @@ -534,6 +585,19 @@ impl GameView { } } + // A continuation under the pointer in the reference tab (blue, like the library's). + if self.preview.is_none() + && let Some(m) = reference_hover.and_then(|u| u.to_move(&pos).ok()) + && let Some((from, to)) = move_squares(&m) + { + arrows.push(Arrow { + from, + to, + color: crate::board_search::PREVIEW_ARROW, + weight: 1.0, + }); + } + // Center the eval bar + board horizontally between the left edge and the side panel. let area = ui.available_rect_before_wrap(); let show_bar = analysis.is_on(); @@ -617,16 +681,7 @@ impl GameView { pieces: settings.piece_set, }; if let Some(m) = view.show(ui, &mut self.board) { - match self.game.add_move(self.cursor, m) { - Ok(id) => { - self.goto(id); - if let Some(s) = self.sound_for(id) { - actions.push(GameAction::Sound(s)); - } - } - Err(e) => actions - .push(GameAction::Toast(trf("Move not added: {e}", &[("e", &e)]))), - } + self.play_move(m, actions); } }); }); @@ -652,22 +707,54 @@ impl GameView { ui: &mut Ui, settings: &mut Settings, analysis: &mut Analysis, + reference: &mut crate::reference::Reference, actions: &mut Vec, ) { egui::Panel::bottom("game_toolbar").show(ui, |ui| self.toolbar(ui, actions)); egui::Panel::top("engine_panel") .show(ui, |ui| self.engine_panel(ui, settings, analysis, actions)); - let tabs = self.review.visible && (self.review.has_data() || self.review.running()); - if !tabs { + let report = self.review.visible && (self.review.has_data() || self.review.running()); + if !report && self.side_tab == SideTab::Report { self.side_tab = SideTab::Notation; } egui::CentralPanel::default().show(ui, |ui| { - if tabs { - ui.horizontal(|ui| { - ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation")); + ui.horizontal(|ui| { + ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation")); + ui.selectable_value(&mut self.side_tab, SideTab::Reference, tr("Reference")) + .on_hover_text(tr("What was played in this position in a database")); + if report { ui.selectable_value(&mut self.side_tab, SideTab::Report, tr("Report")); - }); - ui.separator(); + } + }); + ui.separator(); + if self.side_tab == SideTab::Reference { + let source = self.source.as_ref().map(|s| (s.path.as_path(), s.index)); + let action = egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| { + reference.ui( + ui, + &self.game, + self.cursor, + settings.reference_db.as_deref(), + source, + ) + }) + .inner; + match action { + Some(RefAction::Play(m)) => self.play_move(m, actions), + Some(RefAction::Goto(id)) => self.goto(id), + Some(RefAction::Choose(p)) => actions.push(GameAction::ReferenceChoose(p)), + Some(RefAction::Load(p)) => actions.push(GameAction::ReferenceLoad(p)), + Some(RefAction::OpenGame(p, i, at)) => { + actions.push(GameAction::OpenGame(p, i, at)) + } + Some(RefAction::FindInLibrary(p)) => { + actions.push(GameAction::FindPosition(Some(p))) + } + None => {} + } + return; } if self.side_tab == SideTab::Report { let action = egui::ScrollArea::vertical() @@ -1122,6 +1209,15 @@ impl GameView { /// The cursor's position as a line of moves from the game's start, for searching /// it in a database; `None` after a null move or in a game that cannot be searched. + /// The reference tab is shown (kept for the next game opened from it). + pub fn reference_tab(&self) -> bool { + self.side_tab == SideTab::Reference + } + + pub fn show_reference_tab(&mut self) { + self.side_tab = SideTab::Reference; + } + pub fn search_line(&self) -> Option<(Chess, Vec, bool)> { let (start, line) = crate::board_search::line_to(&self.game, self.cursor)?; Some((start, line, self.flipped)) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index d8b2861..579993f 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -98,6 +98,45 @@ pub fn tr(key: &'static str) -> &'static str { .unwrap_or(key) } +/// "1 game", "5 games" in the interface language, with Russian plural forms +/// ("1 партия", "3 партии", "5 партий"). +pub fn games(n: usize) -> String { + let num = crate::large_db::grouped(n); + match current() { + Lang::Ru => { + let word = match (n % 10, n % 100) { + (1, x) if x != 11 => "партия", + (2..=4, x) if !(12..=14).contains(&x) => "партии", + _ => "партий", + }; + format!("{num} {word}") + } + Lang::En => format!("{num} {}", if n == 1 { "game" } else { "games" }), + Lang::Fr => format!("{num} {}", if n <= 1 { "partie" } else { "parties" }), + Lang::De => format!("{num} {}", if n == 1 { "Partie" } else { "Partien" }), + Lang::Es => format!("{num} {}", if n == 1 { "partida" } else { "partidas" }), + Lang::It => format!("{num} {}", if n == 1 { "partita" } else { "partite" }), + } +} + +/// "11,7 млн партий" / "267 партий": a database size in a short form. +pub fn games_short(n: usize) -> String { + if n >= 1_000_000 { + let short = crate::large_db::short_count(n); + let word = match current() { + Lang::Ru => "партий", + Lang::En => "games", + Lang::Fr => "parties", + Lang::De => "Partien", + Lang::Es => "partidas", + Lang::It => "partite", + }; + format!("{short} {word}") + } else { + games(n) + } +} + /// Translates and substitutes `{name}` placeholders. pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String { let mut s = tr(key).to_string(); @@ -1144,7 +1183,7 @@ const ROWS: &[[&str; 6]] = &[ "Chess960: las jugadas no se pueden leer; se muestran la cabecera y el resultado", "Chess960: le mosse non possono essere lette; sono mostrati intestazione e risultato", ], - ["decimal comma", ".", ",", ",", ",", ","], + ["decimal comma", ",", ",", ",", ",", ","], [ "{n} more matches…", "ещё совпадений: {n}…", @@ -1566,12 +1605,431 @@ const ROWS: &[[&str; 6]] = &[ "Un indice per la ricerca rapida per posizione viene costruito una volta e tenuto nella cache. Nel frattempo la ricerca funziona, solo più lentamente.", ], [ - "Position search needs about {n} MB of free memory for this database.", - "Поиску по позиции нужно около {n} МБ свободной памяти для этой базы.", - "La recherche par position nécessite environ {n} Mo de mémoire libre pour cette base.", - "Die Stellungssuche braucht für diese Datenbank etwa {n} MB freien Speicher.", - "La búsqueda por posición necesita unos {n} MB de memoria libre para esta base.", - "La ricerca per posizione richiede circa {n} MB di memoria libera per questa base.", + "Add a database to the library to see what was played here.", + "Добавьте базу в библиотеку, чтобы видеть, что здесь играли.", + "Ajoutez une base à la bibliothèque pour voir ce qui a été joué ici.", + "Fügen Sie der Bibliothek eine Datenbank hinzu, um zu sehen, was hier gespielt wurde.", + "Añade una base a la biblioteca para ver qué se jugó aquí.", + "Aggiungi una base alla libreria per vedere cosa è stato giocato qui.", + ], + [ + "Known up to", + "В базе до хода", + "Connu jusqu'à", + "Bekannt bis", + "Conocida hasta", + "Nota fino a", + ], + [ + "Not even the start of the game is in this database", + "Даже начала этой партии нет в базе", + "Même le début de la partie n'est pas dans cette base", + "Nicht einmal der Anfang der Partie ist in dieser Datenbank", + "Ni siquiera el inicio de la partida está en esta base", + "Nemmeno l'inizio della partita è in questa base", + ], + [ + "Nothing was played here in this database", + "В этой базе отсюда не играли", + "Rien n'a été joué ici dans cette base", + "In dieser Datenbank wurde hier nichts gespielt", + "En esta base no se jugó nada aquí", + "In questa base qui non si è giocato nulla", + ], + [ + "Open this game at this position", + "Открыть эту партию на этой позиции", + "Ouvrir cette partie à cette position", + "Diese Partie an dieser Stellung öffnen", + "Abrir esta partida en esta posición", + "Apri questa partita in questa posizione", + ], + [ + "Opening the database…", + "Открываю базу…", + "Ouverture de la base…", + "Datenbank wird geöffnet…", + "Abriendo la base…", + "Apertura della base…", + ], + [ + "Reference", + "Справочник", + "Référence", + "Referenz", + "Referencia", + "Riferimento", + ], + [ + "Strongest games", + "Сильнейшие партии", + "Parties les plus fortes", + "Stärkste Partien", + "Partidas más fuertes", + "Partite più forti", + ], + [ + "The last move of the game still played in other games of this database", + "Последний ход партии, который ещё встречается в других партиях этой базы", + "Le dernier coup de la partie encore joué dans d'autres parties de cette base", + "Der letzte Zug der Partie, der noch in anderen Partien dieser Datenbank vorkommt", + "La última jugada de la partida que aún aparece en otras partidas de esta base", + "L'ultima mossa della partita ancora giocata in altre partite di questa base", + ], + [ + "The whole game is in this database", + "Вся партия есть в этой базе", + "Toute la partie est dans cette base", + "Die ganze Partie ist in dieser Datenbank", + "Toda la partida está en esta base", + "L'intera partita è in questa base", + ], + [ + "This database cannot be opened: {e}", + "Эту базу не удалось открыть: {e}", + "Impossible d'ouvrir cette base : {e}", + "Diese Datenbank lässt sich nicht öffnen: {e}", + "No se puede abrir esta base: {e}", + "Impossibile aprire questa base: {e}", + ], + [ + "What was played in this position in a database", + "Что играли в этой позиции в выбранной базе", + "Ce qui a été joué dans cette position dans une base", + "Was in dieser Stellung in einer Datenbank gespielt wurde", + "Qué se jugó en esta posición en una base", + "Cosa è stato giocato in questa posizione in una base", + ], + ["Database", "База", "Base", "Datenbank", "Base", "Base"], + [ + "This position is not in this database", + "В этой базе такой позиции нет", + "Cette position n'est pas dans cette base", + "Diese Stellung ist nicht in dieser Datenbank", + "Esta posición no está en esta base", + "Questa posizione non è in questa base", + ], + [ + "Click: show its games and an arrow; double click: play it", + "Клик — показать партии с ходом и стрелку; двойной клик — сыграть ход", + "Clic : montrer ses parties et une flèche ; double clic : jouer le coup", + "Klick: Partien und Pfeil zeigen; Doppelklick: Zug spielen", + "Clic: ver sus partidas y una flecha; doble clic: jugarla", + "Clic: mostra partite e freccia; doppio clic: gioca la mossa", + ], + [ + "Games", + "Партии", + "Parties", + "Partien", + "Partidas", + "Partite", + ], + [ + "Games that played the move", + "Партий, где сыграли этот ход", + "Parties où ce coup a été joué", + "Partien mit diesem Zug", + "Partidas con esta jugada", + "Partite con questa mossa", + ], + [ + "Share of the games in this position", + "Доля партий в этой позиции", + "Part des parties dans cette position", + "Anteil der Partien in dieser Stellung", + "Proporción de partidas en esta posición", + "Quota delle partite in questa posizione", + ], + [ + "White wins · draws · Black wins", + "Победы белых · ничьи · победы чёрных", + "Gains des Blancs · nulles · gains des Noirs", + "Weißsiege · Remis · Schwarzsiege", + "Victorias blancas · tablas · victorias negras", + "Vittorie del Bianco · patte · vittorie del Nero", + ], + [ + "White's score", + "Очки белых", + "Score des Blancs", + "Punkte von Weiß", + "Puntuación de las blancas", + "Punteggio del Bianco", + ], + [ + "Avg Elo", + "Ср. Эло", + "Elo moy.", + "Ø Elo", + "Elo med.", + "Elo medio", + ], + [ + "Average rating, games where both are known", + "Средний рейтинг партий, где известны оба", + "Classement moyen, parties où les deux sont connus", + "Durchschnittliche Wertung, Partien mit beiden Wertungen", + "Elo medio, partidas con ambos conocidos", + "Elo medio, partite con entrambi noti", + ], + [ + "The latest game", + "Последняя партия", + "La partie la plus récente", + "Die neueste Partie", + "La partida más reciente", + "La partita più recente", + ], + [ + "Best players", + "Лучшие игроки", + "Meilleurs joueurs", + "Beste Spieler", + "Mejores jugadores", + "Migliori giocatori", + ], + [ + "The strongest players who played the move", + "Сильнейшие игроки, сыгравшие этот ход", + "Les joueurs les plus forts ayant joué ce coup", + "Die stärksten Spieler mit diesem Zug", + "Los jugadores más fuertes que jugaron esta jugada", + "I giocatori più forti che hanno giocato la mossa", + ], + [ + "Ended", + "Закончились", + "Terminées", + "Beendet", + "Terminadas", + "Terminate", + ], + [ + "All moves", + "Все ходы", + "Tous les coups", + "Alle Züge", + "Todas las jugadas", + "Tutte le mosse", + ], + [ + "Strongest first", + "Сильнейшие сверху", + "Les plus fortes d'abord", + "Stärkste zuerst", + "Las más fuertes primero", + "Prima le più forti", + ], + ["Res.", "Рез.", "Rés.", "Erg.", "Res.", "Ris."], + [ + "Newest first", + "Новые сверху", + "Les plus récentes d'abord", + "Neueste zuerst", + "Las más recientes primero", + "Prima le più recenti", + ], + ["Then", "Дальше", "Ensuite", "Weiter", "Después", "Poi"], + [ + "How the game went on from this position", + "Как партия продолжилась из этой позиции", + "Comment la partie a continué depuis cette position", + "Wie die Partie von hier weiterging", + "Cómo siguió la partida desde esta posición", + "Come è proseguita la partita da qui", + ], + [ + "Double click: open this game at this position", + "Двойной клик — открыть партию на этой позиции", + "Double clic : ouvrir la partie à cette position", + "Doppelklick: Partie an dieser Stellung öffnen", + "Doble clic: abrir la partida en esta posición", + "Doppio clic: apri la partita in questa posizione", + ], + [ + "Games with {m}", + "Партии с ходом {m}", + "Parties avec {m}", + "Partien mit {m}", + "Partidas con {m}", + "Partite con {m}", + ], + [ + "· the {n} strongest shown", + "· показаны {n} сильнейших", + "· les {n} plus fortes affichées", + "· die {n} stärksten gezeigt", + "· se muestran las {n} más fuertes", + "· mostrate le {n} più forti", + ], + [ + "Back to {game}: it has unsaved changes", + "Возврат к партии {game}: в ней несохранённые изменения", + "Retour à {game} : elle a des modifications non enregistrées", + "Zurück zu {game}: sie hat ungespeicherte Änderungen", + "Vuelta a {game}: tiene cambios sin guardar", + "Ritorno a {game}: ha modifiche non salvate", + ], + [ + "The game this one was opened from, as you left it", + "Партия, из которой открыта эта, — в том виде, как вы её оставили", + "La partie d'où celle-ci a été ouverte, telle que vous l'avez laissée", + "Die Partie, aus der diese geöffnet wurde, so wie Sie sie verlassen haben", + "La partida desde la que se abrió esta, tal como la dejaste", + "La partita da cui è stata aperta questa, come l'hai lasciata", + ], + [ + "⬅ Back to {game}", + "⬅ К партии {game}", + "⬅ Retour à {game}", + "⬅ Zurück zu {game}", + "⬅ Volver a {game}", + "⬅ Torna a {game}", + ], + [ + "not open", + "не открыта", + "non ouverte", + "nicht geöffnet", + "no abierta", + "non aperta", + ], + [ + "Comparing the game with the database…", + "Сверяю партию с базой…", + "Comparaison de la partie avec la base…", + "Partie wird mit der Datenbank verglichen…", + "Comparando la partida con la base…", + "Confronto la partita con la base…", + ], + [ + "This game is in the database", + "Эта партия есть в базе", + "Cette partie est dans la base", + "Diese Partie ist in der Datenbank", + "Esta partida está en la base", + "Questa partita è nella base", + ], + [ + "open it", + "открыть", + "l'ouvrir", + "öffnen", + "abrirla", + "aprila", + ], + [ + "Open the copy of this game from the database at this position", + "Открыть копию этой партии из базы на этой позиции", + "Ouvrir la copie de cette partie de la base à cette position", + "Die Kopie dieser Partie aus der Datenbank an dieser Stellung öffnen", + "Abrir la copia de esta partida de la base en esta posición", + "Apri la copia di questa partita dalla base in questa posizione", + ], + [ + "This position could not be counted", + "Не удалось посчитать эту позицию", + "Impossible de compter cette position", + "Diese Stellung konnte nicht gezählt werden", + "No se pudo contar esta posición", + "Impossibile contare questa posizione", + ], + [ + "Click: show its games and an arrow. Double click: play the move (it is added to the game as a variation if the game has another move; Ctrl+Z undoes it)", + "Клик — показать партии с этим ходом и стрелку. Двойной клик — сыграть ход (если в партии другой ход, добавится вариант; Ctrl+Z отменяет)", + "Clic : montrer ses parties et une flèche. Double clic : jouer le coup (ajouté en variante si la partie a un autre coup ; Ctrl+Z annule)", + "Klick: Partien und Pfeil zeigen. Doppelklick: Zug spielen (als Variante, wenn die Partie anders weitergeht; Strg+Z macht es rückgängig)", + "Clic: ver sus partidas y una flecha. Doble clic: jugarla (se añade como variante si la partida tiene otra jugada; Ctrl+Z deshace)", + "Clic: mostra partite e freccia. Doppio clic: gioca la mossa (aggiunta come variante se la partita ha un'altra mossa; Ctrl+Z annulla)", + ], + [ + "Chapters", + "Главы", + "Chapitres", + "Kapitel", + "Capítulos", + "Capitoli", + ], + [ + "Chapters that play the move", + "Главы, где сыгран этот ход", + "Chapitres où ce coup est joué", + "Kapitel mit diesem Zug", + "Capítulos con esta jugada", + "Capitoli con questa mossa", + ], + [ + "The move played in this game", + "Ход, сыгранный в этой партии", + "Le coup joué dans cette partie", + "Der in dieser Partie gespielte Zug", + "La jugada de esta partida", + "La mossa giocata in questa partita", + ], + [ + "all in the library ➡", + "все в библиотеке ➡", + "toutes dans la bibliothèque ➡", + "alle in der Bibliothek ➡", + "todas en la biblioteca ➡", + "tutte nella libreria ➡", + ], + [ + "Open this position on the search board of this database", + "Открыть эту позицию на доске поиска этой базы", + "Ouvrir cette position sur l'échiquier de recherche de cette base", + "Diese Stellung auf dem Suchbrett dieser Datenbank öffnen", + "Abrir esta posición en el tablero de búsqueda de esta base", + "Apri questa posizione sulla scacchiera di ricerca di questa base", + ], + [ + "in the game {m}", + "в партии {m}", + "dans la partie {m}", + "in der Partie {m}", + "en la partida {m}", + "nella partita {m}", + ], + [ + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + "Не хватает памяти для поиска по позиции в этой базе: нужно ещё около {n} МБ. Закройте другие программы и попробуйте ещё раз.", + "Mémoire insuffisante pour la recherche par position dans cette base : il manque environ {n} Mo. Fermez d'autres programmes et réessayez.", + "Nicht genug Speicher für die Stellungssuche in dieser Datenbank: es fehlen etwa {n} MB. Schließen Sie andere Programme und versuchen Sie es erneut.", + "No hay memoria suficiente para buscar por posición en esta base: faltan unos {n} MB. Cierra otros programas y vuelve a intentarlo.", + "Memoria insufficiente per la ricerca per posizione in questa base: mancano circa {n} MB. Chiudi altri programmi e riprova.", + ], + [ + "The games of this database leave this one at its first move", + "Партии этой базы расходятся с этой уже на первом ходу", + "Les parties de cette base quittent celle-ci dès le premier coup", + "Die Partien dieser Datenbank weichen schon im ersten Zug ab", + "Las partidas de esta base se separan de esta ya en la primera jugada", + "Le partite di questa base si separano da questa già alla prima mossa", + ], + [ + "Try again", + "Попробовать ещё раз", + "Réessayer", + "Erneut versuchen", + "Reintentar", + "Riprova", + ], + [ + "· the {n} newest shown", + "· показаны {n} новых", + "· les {n} plus récentes affichées", + "· die {n} neuesten gezeigt", + "· se muestran las {n} más recientes", + "· mostrate le {n} più recenti", + ], + [ + "No other games reached this position", + "Других партий с этой позицией нет", + "Aucune autre partie n'a atteint cette position", + "Keine andere Partie erreichte diese Stellung", + "Ninguna otra partida llegó a esta posición", + "Nessun'altra partita ha raggiunto questa posizione", ], [ "Checking engine…", @@ -2836,6 +3294,11 @@ mod tests { include_str!("settings.rs"), include_str!("settings_ui.rs"), include_str!("widgets.rs"), + include_str!("reference.rs"), + include_str!("report.rs"), + include_str!("board.rs"), + include_str!("engine_download.rs"), + include_str!("main.rs"), ]; let mut missing = Vec::new(); let mut found = 0; diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 3aa7bbb..41c49b8 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -197,6 +197,8 @@ pub struct Library { view: Vec, view_key: Option<(PathBuf, String, SortKey, bool)>, scroll_to_selected: bool, + /// File sizes of databases (`file_size`). + sizes: HashMap, } impl Library { @@ -216,6 +218,7 @@ impl Library { view: Vec::new(), view_key: None, scroll_to_selected: false, + sizes: HashMap::new(), } } @@ -307,6 +310,22 @@ impl Library { } } + /// Size of a database's file (cached: asked every frame by the reference tab). + pub fn file_size(&mut self, path: &Path) -> u64 { + *self + .sizes + .entry(path.to_owned()) + .or_insert_with(|| std::fs::metadata(path).map_or(0, |m| m.len())) + } + + /// Why the database could not be opened, if it could not. + pub fn failure(&self, path: &Path) -> Option<&str> { + match self.slots.get(path) { + Some(Slot::Failed(e)) => Some(e.as_str()), + _ => None, + } + } + pub fn database(&self, path: &Path) -> Option> { match self.slots.get(path) { Some(Slot::Ready(db)) => Some(db.clone()), @@ -314,7 +333,8 @@ impl Library { } } - fn poll(&mut self) { + /// Takes the databases that finished opening (also while a game is shown). + pub fn poll(&mut self) { for (path, slot) in self.slots.iter_mut() { if let Slot::Loading { rx, .. } = slot && let Ok(res) = rx.try_recv() @@ -460,10 +480,12 @@ impl Library { let mut events = Vec::new(); small.board.keys(ui.ctx(), outcome.as_ref(), &mut events); if let Some(need) = small.blocked { + let free = chess_import::memory::available().unwrap_or(0); + let missing = (need + (256 << 20)).saturating_sub(free) / 1_000_000; ui.label( egui::RichText::new(trf( - "Position search needs about {n} MB of free memory for this database.", - &[("n", &((need + (256 << 20)) / 1_000_000))], + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + &[("n", &missing.max(1))], )) .color(ui.visuals().warn_fg_color), ); diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 531f84c..e3ad22d 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -15,6 +15,7 @@ mod i18n; mod large_db; mod library; mod notation; +mod reference; mod report; mod review; mod settings; diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs new file mode 100644 index 0000000..85968da --- /dev/null +++ b/apps/desktop/src/reference.rs @@ -0,0 +1,1646 @@ +//! The "Reference" tab of a game («Справочник»): what was played in the current +//! position in a database of the shelf (Mega for theory, an opening collection, a +//! pupil's games), following the game's moves. Two tables, as in ChessBase: the moves +//! played from the position with their statistics, and the strongest games that +//! reached it. The database is picked in the panel and remembered; by default the +//! largest one on the shelf. The same position search as the library's search board +//! (`docs/dev/import.md`), run in the background for each new position. It also tells +//! how long the game's main line stays in the database ("theory") and whether the game +//! itself is there. Layout: `docs/design/reference.md`. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use chess_core::{Game, NodeId}; +use chess_import::Database; +use chess_import::position::{Match, MoveStat, PositionOutcome, PositionQuery, Tally}; +use egui::{RichText, Sense, Ui, vec2}; +use egui_extras::{Column, TableBuilder}; +use shakmaty::uci::UciMove; +use shakmaty::{Chess, Color, Move, Position}; + +use crate::board_search::{self, Background}; +use crate::i18n::{tr, trf}; +use crate::large_db::grouped; + +/// A database of the shelf as the panel offers it. +pub struct RefDb { + pub path: PathBuf, + pub name: String, + /// Loaded (with its number of records), or not yet. + pub db: Option>, + /// It could not be opened (why). + pub failed: Option, + /// Size of its file, to pick the largest one before any is opened. + pub bytes: u64, +} + +/// What the panel asks of the game view and the application. +pub enum RefAction { + /// Play this move in the game (as a move on the board: added, undoable). + Play(Move), + /// Use this database from now on. + Choose(PathBuf), + /// Load the chosen database (it is on the shelf but not open yet). + Load(PathBuf), + /// Open a game of the reference database at this position. + OpenGame(PathBuf, usize, Chess), + /// Go to this node of the game (the last move still in the database). + Goto(NodeId), + /// Show the position on the library's search board of this database. + FindInLibrary(PathBuf), +} + +/// A game of the games table. +#[derive(Clone, Debug)] +struct GameRow { + index: usize, + white: String, + white_elo: u16, + black: String, + black_elo: u16, + result: String, + year: u16, + event: String, + /// The move the game played from the position in the line it is listed for + /// (`None`: it ends here). + next: Option, + /// The three half-moves from the position, "5.Nc3 a6 6.Be2". + then: String, +} + +#[cfg(test)] +impl GameRow { + fn average(&self) -> u32 { + average(self.white_elo, self.black_elo) + } +} + +fn average(w: u16, b: u16) -> u32 { + if w > 0 && b > 0 { + (u32::from(w) + u32::from(b)) / 2 + } else { + 0 + } +} + +/// A search result with what the tables show already worked out (picking the strongest +/// of millions of matches, reading the games' moves: work for the background). +pub struct Found { + out: PositionOutcome, + /// The strongest games, the newest games; per move the strongest that played it. + strongest: Vec, + newest: Vec, + by_move: HashMap>, + by_move_newest: HashMap>, + /// Per move: the strongest players who played it (their own rating). + players: HashMap, + /// Most games have no result: a book of chapters (counts are chapters, no results). + books: bool, +} + +/// Identity of a request: database, position and the moves that reached it. +#[derive(Clone, PartialEq, Eq, Hash)] +struct Key { + path: PathBuf, + position: u64, + line: Option>, +} + +/// How far a game's main line stays in the database. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BookEnd { + /// The last node of the main line still found in other games (`None`: not even + /// the start position). + pub last: Option, + /// The whole main line is in the database (a game with moves). + pub to_the_end: bool, + /// Copies of this very game in the database (same players and year, same final + /// position), and the game itself when it comes from it: left out of "theory" and + /// of the games table. + pub copies: Vec, +} + +/// The theory of one game: the main line it was worked out for (UCI moves) and the +/// answer. A longer line that starts with it keeps the answer when the theory ended +/// inside it. +struct Book { + path: PathBuf, + line: Vec, + end: BookEnd, +} + +/// Database and main line (UCI) of a theory request. +type BookKey = (PathBuf, Vec); + +/// Results kept per database and position, at most this many matches in all; a single +/// bigger result is shown but not kept. +const CACHE_MATCHES: usize = 5_000_000; +/// Games listed: overall and per move; "then" is read for the most played moves. +const GAMES_SHOWN: usize = 100; +const GAMES_PER_MOVE: usize = 40; +const MOVES_WITH_GAMES: usize = 12; +/// A PGN database up to this many matches has the continuations of every game read +/// from its tree (a game can reach the position in several variations). +const PGN_TREE_MATCHES: usize = 5_000; +/// Results bigger than the cache kept apart (the start position, 1.e4). +const BIG_KEPT: usize = 2; +/// Plies of the theory checked one by one before it is found by halving. +const BOOK_LINEAR: usize = 12; + +/// Sort of the games table. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +enum GameSort { + #[default] + Strongest, + Newest, +} + +#[derive(Default)] +pub struct Reference { + /// Databases of the shelf (set by the application every frame). + pub dbs: Vec, + job: Option<(Key, Background)>, + shown: Option<(Key, Arc)>, + cache: HashMap>, + /// The fast-search files of a large base, built when it is first used here. + prepare: Option<(PathBuf, Background)>, + prepared: Vec, + /// The theory of the game shown, the job working it out, and a request that failed + /// (not retried until the game or the database changes). + book: Option, + book_job: Option<(BookKey, Background)>, + book_failed: Option, + /// The move of the moves table under the pointer; the selected one (it filters the + /// games), for its database and position. + hover: Option, + selected: Option<(PathBuf, u64, UciMove)>, + sort: GameSort, + /// A request that could not be answered (no memory for a PGN table…): not retried. + failed: Option, + /// The last results too big for the cache (the start position of Mega: 11.7 + /// million matches), kept apart so going back to them is instant. + big: Vec<(Key, Arc)>, +} + +/// The position of `node` and the moves that reach it from the usual start (`None` +/// for a game from a set-up position, or a line with a null move). +fn query_for(game: &Game, node: NodeId) -> Option { + let pos = game.position(node)?.clone(); + let line = board_search::line_to(game, node).and_then(|(start, line)| { + chess_import::position::same_position(&start, &Chess::default()).then_some(line) + }); + Some(PositionQuery::new(pos, line)) +} + +fn key(path: &Path, q: &PositionQuery) -> Key { + Key { + path: path.to_owned(), + position: q.key(), + line: q.line.as_ref().map(|l| { + l.iter() + .map(|m| chess_import::position::uci(m).to_string()) + .collect() + }), + } +} + +/// The main line as UCI moves (a null move as "--"). +fn main_line(game: &Game) -> Vec { + let mut out = Vec::new(); + let mut node = game.root(); + while let Some(next) = game.main_child(node) { + out.push( + game.game_move(next) + .and_then(|m| m.uci()) + .unwrap_or_else(|| "--".into()), + ); + node = next; + } + out +} + +/// "40…Ke5": a move of the game with the number and side of the position before it +/// (games from a set-up position count from their FEN). +fn node_label(game: &Game, node: NodeId) -> Option { + let m = game.game_move(node)?; + let before = game.position(game.parent(node)?)?; + let n = before.fullmoves().get(); + Some(match before.turn() { + Color::White => format!("{n}.{}", m.san), + Color::Black => format!("{n}…{}", m.san), + }) +} + +/// "5.Nc3" / "5…Nc6". +fn move_label(pos: &Chess, m: Move) -> String { + let san = shakmaty::san::SanPlus::from_move(pos.clone(), m).to_string(); + let n = pos.fullmoves().get(); + match pos.turn() { + Color::White => format!("{n}.{san}"), + Color::Black => format!("{n}…{san}"), + } +} + +/// The surname of "Carlsen, Magnus" / "Alekhine Alexander (RUS)" (the first word, as +/// databases write names surname first); empty for an unknown player. +fn surname(name: &str) -> String { + let name = match name.find('(') { + Some(i) => &name[..i], + None => name, + } + .trim(); + // The first word before a comma: "Carlsen, Magnus", "Duke of Brunswick, Count" + // and "Duke Karl / Count Isouard" all compare by it. + let before = name.split_once(',').map_or(name, |(s, _)| s); + let s = before.split_whitespace().next().unwrap_or(""); + if s == "?" || s == "NN" { + String::new() + } else { + s.to_owned() + } +} + +/// Ratings and year of a match without reading names (cheap for millions). +fn ratings(db: &Database, index: usize) -> (u16, u16, u16) { + match db { + Database::ChessBase(b) => { + let r = b.record(index); + let u = |at: usize, n: usize| -> u32 { + r.get(at..at + n) + .map_or(0, |s| s.iter().fold(0, |a, x| (a << 8) | u32::from(*x))) + }; + ( + u(0x1f, 2) as u16, + u(0x21, 2) as u16, + ((u(0x18, 3) >> 9) & 0xfff) as u16, + ) + } + Database::Pgn(p) => { + let e = &p.entries()[index]; + let elo = |k: &str| e.tag(k).and_then(|v| v.parse().ok()).unwrap_or(0); + let year = e + .tag("Date") + .and_then(|d| d.get(..4)) + .and_then(|y| y.parse().ok()) + .unwrap_or(0); + (elo("WhiteElo"), elo("BlackElo"), year) + } + } +} + +/// The header fields of a game of the database (no moves). +fn row_of(db: &Database, index: usize, next: Option) -> GameRow { + let (white_elo, black_elo, year) = ratings(db, index); + let (white, black, result, event) = match db { + Database::ChessBase(b) => { + let r = b.row(index); + (r.white, r.black, r.result.to_owned(), r.event) + } + Database::Pgn(p) => { + let e = &p.entries()[index]; + let t = |k: &str| e.tag(k).unwrap_or("").to_owned(); + (t("White"), t("Black"), t("Result"), t("Event")) + } + }; + GameRow { + index, + white, + white_elo, + black, + black_elo, + result, + year, + event, + next, + then: String::new(), + } +} + +/// "5.Nc3 a6 6.Be2" from `node` on: its child playing `next`, then the main line. +fn then_from(game: &Game, node: NodeId, next: Option) -> String { + let Some(next) = next else { + return String::new(); + }; + let next = next.to_string(); + let Some(mut child) = game.children(node).iter().copied().find(|c| { + game.game_move(*c) + .and_then(|m| m.uci()) + .is_some_and(|u| u == next) + }) else { + return String::new(); + }; + let mut out = Vec::new(); + for k in 0..3 { + let Some(m) = game.game_move(child) else { + break; + }; + let Some(before) = game.parent(child).and_then(|p| game.position(p)) else { + break; + }; + let n = before.fullmoves().get(); + out.push(match before.turn() { + Color::White => format!("{n}.{}", m.san), + Color::Black if k == 0 => format!("{n}…{}", m.san), + Color::Black => m.san.clone(), + }); + match game.main_child(child) { + Some(c) => child = c, + None => break, + } + } + out.join(" ") +} + +/// The nodes of `game` in the position `key`, in tree order (main line first). +fn occurrences(game: &Game, key: u64) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![game.root()]; + while let Some(n) = stack.pop() { + if game + .position(n) + .is_some_and(|p| chess_import::position::key(p) == key) + { + out.push(n); + } + stack.extend(game.children(n).iter().rev().copied()); + } + out +} + +/// What a game of a PGN database played from the position, in every branch, each +/// with its "then": `(next, then)`; the game's own `Match::next` first. +fn pgn_continuations(db: &Database, m: &Match, key: u64) -> Vec<(Option, String)> { + let Some(parsed) = db.load_game(m.index as usize) else { + return vec![(m.next, String::new())]; + }; + let g = &parsed.game; + let mut out: Vec<(Option, String)> = Vec::new(); + for node in occurrences(g, key) { + let children = g.children(node); + if children.is_empty() { + if !out.iter().any(|(n, _)| n.is_none()) { + out.push((None, String::new())); + } + continue; + } + for c in children { + let Some(u) = g + .game_move(*c) + .and_then(|x| x.uci()) + .and_then(|u| u.parse::().ok()) + else { + continue; + }; + if !out.iter().any(|(n, _)| *n == Some(u)) { + out.push((Some(u), then_from(g, node, Some(u)))); + } + } + } + // The match's own continuation leads (it is the one counted for the game first). + if let Some(i) = out.iter().position(|(n, _)| *n == m.next) { + out.swap(0, i); + } + if out.is_empty() { + out.push((m.next, String::new())); + } + out +} + +/// "Then" of a game whose main line reaches the position at `m.ply` (a ChessBase +/// search looks at main lines only). +fn main_line_then(db: &Database, m: &Match) -> String { + let Some(parsed) = db.load_game(m.index as usize) else { + return String::new(); + }; + let g = &parsed.game; + let mut node = g.root(); + for _ in 0..m.ply { + match g.main_child(node) { + Some(n) => node = n, + None => return String::new(), + } + } + then_from(g, node, m.next) +} + +/// The `n` best of `items` by `score` (highest first), without sorting all of them. +fn best(mut items: Vec, n: usize, score: impl Fn(&T) -> K) -> Vec { + if items.len() > n { + items.select_nth_unstable_by(n, |a, b| score(b).cmp(&score(a))); + items.truncate(n); + } + items.sort_by_key(|x| std::cmp::Reverse(score(x))); + items +} + +/// One match for picking: its number among the matches, average rating, year and the +/// rating of the player to move. +type Fact = (usize, u32, u16, u16); + +/// Works out what the tables show for an outcome. `None` when cancelled (a newer +/// position was asked for). +fn tables( + db: &Database, + position: &Chess, + out: PositionOutcome, + cancel: &AtomicBool, +) -> Option { + use std::sync::atomic::Ordering; + let stopped = || cancel.load(Ordering::Relaxed); + let key = chess_import::position::key(position); + let mover_white = position.turn() == Color::White; + let facts: Vec = out + .matches + .iter() + .enumerate() + .map(|(k, m)| { + let (w, b, y) = ratings(db, m.index as usize); + (k, average(w, b), y, if mover_white { w } else { b }) + }) + .collect(); + if stopped() { + return None; + } + let by_strength = |x: &Fact| (x.1, x.2, std::cmp::Reverse(x.0)); + let by_year = |x: &Fact| (x.2, x.1, std::cmp::Reverse(x.0)); + let pgn = matches!(db, Database::Pgn(_)); + // What each match played from the position: every branch of a PGN game when the + // result is small enough to read them all, else the chosen occurrence's move. + let mut continuations: HashMap, String)>> = HashMap::new(); + if pgn && out.matches.len() <= PGN_TREE_MATCHES { + for (k, m) in out.matches.iter().enumerate() { + if k % 256 == 0 && stopped() { + return None; + } + continuations.insert(k, pgn_continuations(db, m, key)); + } + } + let moves_of = |k: usize| -> Vec> { + match continuations.get(&k) { + Some(c) => c.iter().map(|(n, _)| *n).collect(), + None => vec![out.matches[k].next], + } + }; + // A row of the games table; "then" (reading the game's moves) only when asked. + let row = |k: usize, next: Option, then: bool| -> GameRow { + let m = &out.matches[k]; + let mut r = row_of(db, m.index as usize, next); + if !then { + return r; + } + r.then = match continuations.get(&k) { + Some(c) => c + .iter() + .find(|(n, _)| *n == next) + .map(|(_, t)| t.clone()) + .unwrap_or_default(), + None if pgn => pgn_continuations(db, m, key) + .into_iter() + .find(|(n, _)| *n == next) + .map(|(_, t)| t) + .unwrap_or_default(), + None => main_line_then(db, m), + }; + r + }; + let strongest = best(facts.clone(), GAMES_SHOWN, by_strength) + .into_iter() + .map(|f| row(f.0, out.matches[f.0].next, true)) + .collect(); + if stopped() { + return None; + } + let newest = best(facts.clone(), GAMES_SHOWN, by_year) + .into_iter() + .map(|f| row(f.0, out.matches[f.0].next, true)) + .collect(); + // Per move of the table: its strongest and newest games and its strongest players + // ("then" for the most played moves; the rest are rarely looked at). + let main_moves: Vec = out + .moves + .iter() + .take(MOVES_WITH_GAMES) + .map(|m| m.uci) + .collect(); + let mut groups: HashMap> = HashMap::new(); + for f in &facts { + for n in moves_of(f.0).into_iter().flatten() { + groups.entry(n).or_default().push(*f); + } + } + let mut by_move = HashMap::new(); + let mut by_move_newest = HashMap::new(); + let mut players = HashMap::new(); + for (mv, list) in groups { + if stopped() { + return None; + } + let then = main_moves.contains(&mv); + let mut names: Vec = Vec::new(); + for f in best(list.clone(), 400, |x: &Fact| { + (x.3, x.2, std::cmp::Reverse(x.0)) + }) { + let r = row_of(db, out.matches[f.0].index as usize, None); + let s = surname(if mover_white { &r.white } else { &r.black }); + if !s.is_empty() && !names.contains(&s) { + names.push(s); + } + if names.len() == 2 { + break; + } + } + players.insert(mv, names.join(", ")); + let rows: Vec = best(list.clone(), GAMES_PER_MOVE, by_strength) + .into_iter() + .map(|f| row(f.0, Some(mv), then)) + .collect(); + by_move.insert(mv, rows); + let rows: Vec = best(list, GAMES_PER_MOVE, by_year) + .into_iter() + .map(|f| row(f.0, Some(mv), then)) + .collect(); + by_move_newest.insert(mv, rows); + } + let books = match db { + Database::Pgn(p) => { + let decided = p + .entries() + .iter() + .filter(|e| matches!(e.result(), Some("1-0" | "0-1" | "1/2-1/2"))) + .count(); + decided * 2 < p.len() + } + Database::ChessBase(_) => false, + }; + Some(Found { + out, + strongest, + newest, + by_move, + by_move_newest, + players, + books, + }) +} + +/// Games among `matches` with the players and year of `game` (the same game, maybe +/// from another source). +fn same_game(db: &Database, game: &Game, matches: &[Match]) -> Vec { + let (w, b) = ( + surname(game.tag("White").unwrap_or("")).to_lowercase(), + surname(game.tag("Black").unwrap_or("")).to_lowercase(), + ); + if w.is_empty() || b.is_empty() { + return Vec::new(); + } + let year: u16 = game + .tag("Date") + .and_then(|d| d.get(..4)) + .and_then(|y| y.parse().ok()) + .unwrap_or(0); + matches + .iter() + .filter(|m| { + let r = row_of(db, m.index as usize, None); + surname(&r.white).to_lowercase() == w + && surname(&r.black).to_lowercase() == b + && (year == 0 || r.year == 0 || r.year == year) + }) + .map(|m| m.index as usize) + .collect() +} + +/// The theory of `game`'s main line in `db`. `exclude`: the game itself when it comes +/// from this database. +fn book_end( + db: &Database, + game: &Game, + exclude: Option, + from: usize, + cancel: &AtomicBool, +) -> Option { + let mut nodes = vec![game.root()]; + while let Some(n) = game.main_child(*nodes.last()?) { + nodes.push(n); + } + let search = |q: &PositionQuery| db.search_position(None, q, &Default::default(), cancel); + // Copies: games with the same players and year that reach the final position. + let mut copies: Vec = exclude.into_iter().collect(); + if nodes.len() > 1 + && let Some(q) = query_for(game, *nodes.last()?) + { + let out = search(&q)?; + if out.matches.len() <= 10_000 { + copies.extend(same_game(db, game, &out.matches)); + } + } + copies.sort_unstable(); + copies.dedup(); + let known = |ply: usize| -> Option { + let Some(q) = query_for(game, nodes[ply]) else { + return Some(false); + }; + let out = search(&q)?; + Some( + out.matches + .iter() + .any(|m| copies.binary_search(&(m.index as usize)).is_err()), + ) + }; + // The first plies one by one (the opening index answers them at once), then by + // doubling and halving: a position is nearly always in the database when a later + // one of the same line is. + // `from`: the plies before it are known already (the game grew past a theory that + // reached its end). + let total = nodes.len(); + let from = from.min(total); + let linear_end = if from > 0 { + from + } else { + total.min(BOOK_LINEAR) + }; + let mut last_known: Option = from.checked_sub(1); + let mut first_unknown = None; + for ply in from..linear_end { + if known(ply)? { + last_known = Some(ply); + } else { + first_unknown = Some(ply); + break; + } + } + if first_unknown.is_none() && total > linear_end { + let mut lo = linear_end - 1; + let mut step = 2; + let mut hi = total; + while lo + step < total { + if known(lo + step)? { + lo += step; + step *= 2; + } else { + hi = lo + step; + break; + } + } + if hi == total && lo + 1 < total { + // Past the last doubling: the end of the line itself. + if known(total - 1)? { + lo = total - 1; + } + } + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if known(mid)? { + lo = mid; + } else { + hi = mid; + } + } + last_known = Some(lo); + if hi < total { + first_unknown = Some(hi); + } + } + Some(BookEnd { + last: last_known.map(|p| nodes[p]), + to_the_end: total > 1 && first_unknown.is_none(), + copies, + }) +} + +impl Reference { + /// The move under the pointer, or the selected one (an arrow on the board). + pub fn hover(&self) -> Option { + self.hover.or(self.selected.as_ref().map(|(_, _, m)| *m)) + } + + /// The database in use: the chosen one if it is on the shelf, else the largest + /// file on the shelf. + fn current<'a>(&'a self, chosen: Option<&Path>) -> Option<&'a RefDb> { + chosen + .and_then(|c| self.dbs.iter().find(|d| d.path == c)) + .or_else(|| self.dbs.iter().max_by_key(|d| d.bytes)) + } + + /// Collects finished work. + fn poll(&mut self) { + if let Some((k, job)) = &self.job + && let Some(r) = job.poll() + { + let k = k.clone(); + self.job = None; + match r { + Some(found) => { + let found = Arc::new(found); + let n = found.out.matches.len(); + if n <= CACHE_MATCHES { + let kept: usize = self.cache.values().map(|o| o.out.matches.len()).sum(); + if kept + n > CACHE_MATCHES { + self.cache.clear(); + } + self.cache.insert(k.clone(), found.clone()); + } else { + self.big.retain(|(bk, _)| *bk != k); + self.big.push((k.clone(), found.clone())); + if self.big.len() > BIG_KEPT { + self.big.remove(0); + } + } + self.shown = Some((k, found)); + } + None => self.failed = Some(k), + } + } + if let Some((path, job)) = &self.prepare + && job.poll().is_some() + { + self.prepared.push(path.clone()); + self.prepare = None; + } + if let Some(((path, line), job)) = &self.book_job + && let Some(r) = job.poll() + { + let (path, line) = (path.clone(), line.clone()); + self.book_job = None; + match r { + Some(end) => self.book = Some(Book { path, line, end }), + None => self.book_failed = Some((path, line)), + } + } + } + + /// The theory for this game and database, if worked out: also for a longer line + /// when the theory ended inside the one it was worked out for. + fn book_for(&self, path: &Path, line: &[String]) -> Option<&BookEnd> { + let b = self.book.as_ref().filter(|b| b.path == path)?; + if b.line == line { + return Some(&b.end); + } + (!b.line.is_empty() && line.starts_with(&b.line) && !b.end.to_the_end).then_some(&b.end) + } + + /// Starts what the position and the database need. + fn request( + &mut self, + ctx: &egui::Context, + path: &Path, + db: &Arc, + game: &Game, + query: &PositionQuery, + exclude: Option, + ) { + let now = ctx.input(|i| i.time); + // A large base gets its search index once (as the search board does). + if let Some(b) = db.as_chessbase() + && self.prepare.is_none() + && !self.prepared.iter().any(|p| p == path) + && b.prepare_wanted() + { + let db2 = db.clone(); + if let Some(job) = Background::spawn(ctx, now, move |progress, cancel| { + db2.as_chessbase()?.prepare(progress, cancel).ok() + }) { + self.prepare = Some((path.to_owned(), job)); + } + } + let k = key(path, query); + let kept = self + .cache + .get(&k) + .or_else(|| self.big.iter().find(|(bk, _)| *bk == k).map(|(_, f)| f)); + if let Some(found) = kept { + self.shown = Some((k.clone(), found.clone())); + self.job = None; + } else if self.failed.as_ref() != Some(&k) + && self.shown.as_ref().is_none_or(|(sk, _)| *sk != k) + && self.job.as_ref().is_none_or(|(jk, _)| *jk != k) + { + let (db2, q) = (db.clone(), query.clone()); + self.job = Background::spawn(ctx, now, move |progress, cancel| { + let out = db2.search_position(None, &q, progress, cancel)?; + tables(&db2, &q.position, out, cancel) + }) + .map(|j| (k, j)); + } + // The theory of the main line, once per game and database (kept while the + // game grows past its end). + let line = main_line(game); + let bk = (path.to_owned(), line.clone()); + let known = self.book_for(path, &line).is_some() + || self.book_job.as_ref().is_some_and(|(k, _)| *k == bk) + || self.book_failed.as_ref() == Some(&bk); + if !known && line.is_empty() { + // An empty game: no theory and no copies to look for. + self.book = Some(Book { + path: path.to_owned(), + line, + end: BookEnd { + last: None, + to_the_end: false, + copies: exclude.into_iter().collect(), + }, + }); + } else if !known && self.job.is_none() { + // After the tables (both searching at once would compete for the machine). + // A game grown past a theory that reached its end checks the new moves only. + let from = self + .book + .as_ref() + .filter(|b| b.path == path && b.end.to_the_end && line.starts_with(&b.line)) + .map_or(0, |b| b.line.len() + 1); + let (db2, g) = (db.clone(), game.clone()); + self.book_job = Background::spawn(ctx, now, move |_, cancel| { + book_end(&db2, &g, exclude, from, cancel) + }) + .map(|j| (bk, j)); + } + } + + /// The panel. `chosen`: the database picked last time; `source`: where the game + /// comes from (it is left out of "theory" when it is the same database). + pub fn ui( + &mut self, + ui: &mut Ui, + game: &Game, + cursor: NodeId, + chosen: Option<&Path>, + source: Option<(&Path, usize)>, + ) -> Option { + self.poll(); + self.hover = None; + let mut action = None; + let Some(current) = self.current(chosen) else { + ui.add_space(8.0); + ui.label( + RichText::new(tr( + "Add a database to the library to see what was played here.", + )) + .weak(), + ); + return None; + }; + let path = current.path.clone(); + let db = current.db.clone(); + // The database picker. + ui.horizontal(|ui| { + ui.label(tr("Database")); + let label = |d: &RefDb| match &d.db { + Some(db) => format!("{} · {}", d.name, crate::i18n::games_short(db.len())), + None => format!("{} · {}", d.name, tr("not open")), + }; + egui::ComboBox::from_id_salt("reference_db") + .selected_text(label(current)) + .width(ui.available_width().min(380.0)) + .truncate() + .show_ui(ui, |ui| { + for d in &self.dbs { + if ui.selectable_label(d.path == path, label(d)).clicked() && d.path != path + { + action = Some(RefAction::Choose(d.path.clone())); + } + } + }); + }); + if let Some(e) = ¤t.failed { + ui.add_space(8.0); + ui.label( + RichText::new(trf("This database cannot be opened: {e}", &[("e", e)])) + .color(ui.visuals().warn_fg_color), + ); + return action; + } + let Some(db) = db else { + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(tr("Opening the database…")).weak()); + }); + return action.or(Some(RefAction::Load(path))); + }; + let Some(query) = query_for(game, cursor) else { + return action; + }; + let pos = query.position.clone(); + let exclude = source.filter(|(p, _)| *p == path).map(|(_, i)| i); + self.request(ui.ctx(), &path, &db, game, &query, exclude); + if self.job.is_some() || self.prepare.is_some() || self.book_job.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(100)); + } + if let Some((p, job)) = &self.prepare + && *p == path + { + let work = db.as_chessbase().map_or(1, |b| b.prepare_work()).max(1); + let pct = 100.0 * job.progress() as f32 / work as f32; + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(12.0)); + ui.label( + RichText::new(trf( + "Speeding up search in this database (once)… {p} %", + &[("p", &format!("{:.0}", pct.min(100.0)))], + )) + .weak(), + ) + .on_hover_text(tr( + "An index for fast position search is built once and kept in the cache. Searching works meanwhile, only slower.", + )); + }); + } + // Where we are: the position and what the game played from it. + let side = if pos.turn() == Color::White { + tr("White to move") + } else { + tr("Black to move") + }; + let mut context = match node_label(game, cursor) { + Some(m) => format!("{side} · {}", trf("after {move}", &[("move", &m)])), + None => side.to_owned(), + }; + let played = game + .main_child(cursor) + .and_then(|n| game.game_move(n)) + .and_then(|m| m.uci()) + .and_then(|u| u.parse::().ok()); + if let Some(m) = played.and_then(|u| u.to_move(&pos).ok()) { + context.push_str(&format!( + " · {}", + trf("in the game {m}", &[("m", &move_label(&pos, m))]) + )); + } + ui.label(RichText::new(context).weak()); + // Theory: where the main line leaves the database (the line keeps its height + // while it is worked out, so nothing jumps). + let line = main_line(game); + let book = self.book_for(&path, &line).cloned(); + let failed_book = self.book_failed.as_ref() == Some(&(path.clone(), line.clone())); + ui.horizontal(|ui| match &book { + _ if line.is_empty() => {} + Some(b) if b.to_the_end => { + ui.label(RichText::new(tr("The whole game is in this database")).weak()); + } + Some(BookEnd { + last: Some(node), .. + }) if *node == game.root() => { + ui.label( + RichText::new(tr( + "The games of this database leave this one at its first move", + )) + .weak(), + ); + } + Some(BookEnd { + last: Some(node), .. + }) => { + ui.label(RichText::new(tr("Known up to")).weak()); + if ui + .link(node_label(game, *node).unwrap_or_default()) + .on_hover_text(tr( + "The last move of the game still played in other games of this database", + )) + .clicked() + { + action = Some(RefAction::Goto(*node)); + } + } + Some(_) => { + ui.label( + RichText::new(tr("Not even the start of the game is in this database")).weak(), + ); + } + None if failed_book => {} + None => { + ui.label(RichText::new(tr("Comparing the game with the database…")).weak()); + } + }); + // The game itself is in the database (maybe annotated there): open it. + if let Some(copy) = book + .as_ref() + .and_then(|b| b.copies.iter().find(|c| Some(**c) != exclude)) + { + ui.horizontal(|ui| { + ui.label(RichText::new(tr("This game is in the database")).weak()); + if ui + .link(tr("open it")) + .on_hover_text(tr( + "Open the copy of this game from the database at this position", + )) + .clicked() + { + action = Some(RefAction::OpenGame(path.clone(), *copy, pos.clone())); + } + }); + } + ui.separator(); + let current_key = key(&path, &query); + let shown = self + .shown + .as_ref() + .filter(|(k, _)| *k == current_key) + .map(|(_, o)| o.clone()); + let Some(found) = shown else { + if self.failed.as_ref() == Some(¤t_key) { + let text = match db.positions_blocked() { + Some(need) => { + let free = chess_import::memory::available().unwrap_or(0); + let missing = (need + (256 << 20)).saturating_sub(free) / 1_000_000; + trf( + "Not enough memory for position search in this database: about {n} MB more is needed. Close other programs and try again.", + &[("n", &missing.max(1))], + ) + } + None => tr("This position could not be counted").to_owned(), + }; + ui.label(RichText::new(text).color(ui.visuals().warn_fg_color)); + if ui.small_button(tr("Try again")).clicked() { + self.failed = None; + self.book_failed = None; + } + return action; + } + // A short search shows nothing at all rather than a blinking spinner. + let started = self.job.as_ref().map_or(0.0, |(_, j)| j.started); + if ui.input(|i| i.time) - started > 0.3 { + let total = db.len().max(1); + let p = self.job.as_ref().map_or(0, |(_, j)| j.progress()); + ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); + let text = if p > 0 { + trf( + "Counting… {p} %", + &[("p", &format!("{:.0}", (100 * p / total).min(100)))], + ) + } else { + tr("Counting…").to_owned() + }; + ui.label(RichText::new(text).weak()); + }); + } + return action; + }; + if found.out.matches.is_empty() { + ui.add_space(8.0); + ui.label(RichText::new(tr("This position is not in this database")).weak()); + return action; + } + // A selection belongs to its database and position. + let pos_key = query.key(); + if self + .selected + .as_ref() + .is_some_and(|(p, k, _)| *p != path || *k != pos_key) + { + self.selected = None; + } + if let Some(a) = self.moves_table(ui, &path, &pos, &found, pos_key, played) { + action = Some(a); + } + ui.add_space(4.0); + ui.separator(); + ui.add_space(4.0); + let copies = book.map(|b| b.copies).unwrap_or_default(); + if let Some(a) = self.games_table(ui, &path, &pos, &found, &copies) { + action = Some(a); + } + action + } + + /// The moves from the position: statistics, click selects, double click plays. + /// `played`: the move the game played here (marked). + fn moves_table( + &mut self, + ui: &mut Ui, + path: &Path, + pos: &Chess, + found: &Found, + pos_key: u64, + played: Option, + ) -> Option { + let out = &found.out; + let books = found.books; + let total: u32 = out.moves.iter().map(|m| m.tally.games).sum::() + out.ended.games; + let mut action = None; + let rows = out.moves.len() + usize::from(out.ended.games > 0); + if rows == 0 { + // The games go on with a null move (a teaching "--"), which is not a move. + ui.label(RichText::new(tr("Nothing was played here in this database")).weak()); + return None; + } + // As tall as its rows, but at most 40 % of the panel (at least 120 px of it). + let natural = 26.0 * (rows as f32 + 1.0) + 8.0; + let height = natural.min((ui.available_height() * 0.4).max(120.0)); + // Columns that give way in a narrow panel: players, year, White's score, rating. + let width = ui.available_width(); + let show_players = width > 600.0 && !books; + let show_year = width > 470.0; + let show_score = width > 400.0 && !books; + let show_elo = width > 330.0 && !books; + let show_bar = !books; + let mut table = TableBuilder::new(ui) + .id_salt("reference_moves") + .striped(true) + .sense(Sense::click()) + .max_scroll_height(height) + .min_scrolled_height(height) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::exact(86.0)) + .column(Column::exact(64.0)) + .column(Column::exact(44.0)); + if show_bar { + table = table.column(Column::exact(86.0)); + } + if show_score { + table = table.column(Column::exact(48.0)); + } + if show_elo { + table = table.column(Column::exact(56.0)); + } + if show_year { + table = table.column(Column::exact(44.0)); + } + if show_players { + table = table.column(Column::remainder().at_least(80.0).clip(true)); + } + let selected = self + .selected + .as_ref() + .filter(|(p, k, _)| p == path && *k == pos_key) + .map(|(_, _, m)| *m); + let mut hovered = None; + let mut clicked = None; + let mut play = None; + table + .header(24.0, |mut h| { + let mut head = |text: &str, hint: &str| { + h.col(|ui| { + ui.label(RichText::new(text).strong()).on_hover_text(hint); + }); + }; + head( + tr("Move"), + tr("Click: show its games and an arrow. Double click: play the move (it is added to the game as a variation if the game has another move; Ctrl+Z undoes it)"), + ); + if books { + head(tr("Chapters"), tr("Chapters that play the move")); + } else { + head(tr("Games"), tr("Games that played the move")); + } + head("%", tr("Share of the games in this position")); + if show_bar { + head(tr("Result"), tr("White wins · draws · Black wins")); + } + if show_score { + head(tr("White"), tr("White's score")); + } + if show_elo { + head(tr("Avg Elo"), tr("Average rating, games where both are known")); + } + if show_year { + head(tr("Year"), tr("The latest game")); + } + if show_players { + head(tr("Best players"), tr("The strongest players who played the move")); + } + }) + .body(|body| { + body.rows(24.0, rows, |mut row| { + let i = row.index(); + let stat: Option<&MoveStat> = out.moves.get(i); + let tally: &Tally = stat.map_or(&out.ended, |s| &s.tally); + row.set_selected(stat.is_some_and(|s| Some(s.uci) == selected)); + let in_game = stat.is_some_and(|s| Some(s.uci) == played); + let label = match stat { + Some(s) => s + .uci + .to_move(pos) + .map(|m| move_label(pos, m)) + .unwrap_or_else(|_| s.san.clone()), + None => tr("Ended").to_owned(), + }; + row.col(|ui| { + let text = if in_game { + RichText::new(format!("⏵ {label}")).strong() + } else if stat.is_some() { + RichText::new(format!(" {label}")) + } else { + RichText::new(format!(" {label}")).weak() + }; + let r = ui.label(text); + if in_game { + r.on_hover_text(tr("The move played in this game")); + } + }); + row.col(|ui| { + ui.label(grouped(tally.games as usize)); + }); + row.col(|ui| { + let pct = 100.0 * tally.games as f32 / total.max(1) as f32; + ui.label(RichText::new(format!("{pct:.0}%")).weak()); + }); + if show_bar { + row.col(|ui| { + let (rect, _) = + ui.allocate_exact_size(vec2(78.0, 14.0), Sense::hover()); + board_search::results_bar(ui, rect, tally, ui.visuals().text_color()); + }); + } + if show_score { + row.col(|ui| { + let decided = tally.white_wins + tally.draws + tally.black_wins; + if decided > 0 { + let score = (tally.white_wins as f32 + tally.draws as f32 / 2.0) + / decided as f32; + ui.label(format!("{:.0}%", 100.0 * score)); + } + }); + } + if show_elo { + row.col(|ui| { + if let Some(avg) = tally.average_elo() { + ui.label(avg.to_string()); + } + }); + } + if show_year { + row.col(|ui| { + if tally.last_year > 0 { + ui.label(RichText::new(tally.last_year.to_string()).weak()); + } + }); + } + if show_players { + row.col(|ui| { + if let Some(p) = stat.and_then(|s| found.players.get(&s.uci)) { + ui.label(RichText::new(p).weak()); + } + }); + } + let r = row.response(); + if let Some(s) = stat { + if r.hovered() { + hovered = Some(s.uci); + } + if r.double_clicked() { + play = Some(s.uci); + } else if r.clicked() { + clicked = Some(s.uci); + } + } + }); + }); + self.hover = hovered; + if let Some(m) = clicked { + self.selected = if selected == Some(m) { + None + } else { + Some((path.to_owned(), pos_key, m)) + }; + } + if let Some(m) = play.and_then(|u| u.to_move(pos).ok()) { + self.selected = None; + action = Some(RefAction::Play(m)); + } + action + } + + /// The strongest (or newest) games that reached the position, of the selected move + /// if one is; without this game and its copies. + fn games_table( + &mut self, + ui: &mut Ui, + path: &Path, + pos: &Chess, + found: &Found, + copies: &[usize], + ) -> Option { + let selected = self + .selected + .as_ref() + .filter(|(p, _, _)| p == path) + .map(|(_, _, m)| *m); + let is_copy = |i: usize| copies.binary_search(&i).is_ok(); + // The games counted, without this game and its copies. + let (list, count): (Vec<&GameRow>, usize) = match selected { + Some(m) => { + let lists = match self.sort { + GameSort::Strongest => &found.by_move, + GameSort::Newest => &found.by_move_newest, + }; + let rows: Vec<&GameRow> = lists + .get(&m) + .map(|v| v.iter().collect()) + .unwrap_or_default(); + let n = found + .out + .moves + .iter() + .find(|s| s.uci == m) + .map_or(0, |s| s.tally.games as usize); + let own = found + .out + .matches + .iter() + .filter(|x| x.next == Some(m) && is_copy(x.index as usize)) + .count(); + (rows, n.saturating_sub(own)) + } + None => { + let rows = match self.sort { + GameSort::Strongest => &found.strongest, + GameSort::Newest => &found.newest, + }; + let own = found + .out + .matches + .iter() + .filter(|x| is_copy(x.index as usize)) + .count(); + ( + rows.iter().collect(), + found.out.matches.len().saturating_sub(own), + ) + } + }; + let rows: Vec<&GameRow> = list.into_iter().filter(|g| !is_copy(g.index)).collect(); + let mut action = None; + ui.horizontal(|ui| { + match selected.and_then(|m| m.to_move(pos).ok()) { + Some(m) => { + ui.label( + RichText::new(trf("Games with {m}", &[("m", &move_label(pos, m))])) + .strong(), + ); + ui.label(RichText::new(format!("· {}", crate::i18n::games(count))).weak()); + if ui + .small_button("🗙") + .on_hover_text(tr("All moves")) + .clicked() + { + self.selected = None; + } + } + None if count == 0 => { + ui.label(RichText::new(tr("No other games reached this position")).weak()); + } + None => { + ui.label(RichText::new(crate::i18n::games(count)).strong()); + } + } + if count > rows.len() && !rows.is_empty() { + let text = match self.sort { + GameSort::Strongest => trf("· the {n} strongest shown", &[("n", &rows.len())]), + GameSort::Newest => trf("· the {n} newest shown", &[("n", &rows.len())]), + }; + ui.label(RichText::new(text).weak()); + } + if ui + .link(tr("all in the library ➡")) + .on_hover_text(tr( + "Open this position on the search board of this database", + )) + .clicked() + { + action = Some(RefAction::FindInLibrary(path.to_owned())); + } + }); + if rows.is_empty() { + return action; + } + let width = ui.available_width(); + let show_event = width > 720.0; + let show_then = width > 520.0; + let show_year = width > 380.0; + let mut table = TableBuilder::new(ui) + .id_salt("reference_games") + .striped(true) + .sense(Sense::click()) + .auto_shrink([false, false]) + .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) + .column(Column::initial(150.0).at_least(60.0).clip(true)) + .column(Column::exact(44.0)) + .column(Column::initial(150.0).at_least(60.0).clip(true)) + .column(Column::exact(44.0)) + .column(Column::exact(44.0)); + if show_year { + table = table.column(Column::exact(52.0)); + } + if show_then { + table = table.column(Column::initial(150.0).at_least(80.0).clip(true)); + } + if show_event { + table = table.column(Column::remainder().at_least(80.0).clip(true)); + } + let mut hovered = None; + let mut opened = None; + let mut sort_click = None; + let sort = self.sort; + table + .header(24.0, |mut h| { + h.col(|ui| { + ui.label(RichText::new(tr("White")).strong()); + }); + h.col(|ui| { + let arrow = if sort == GameSort::Strongest { + " ⏷" + } else { + "" + }; + if ui + .add( + egui::Button::new(RichText::new(format!("Elo{arrow}")).strong()) + .frame(false), + ) + .on_hover_text(tr("Strongest first")) + .clicked() + { + sort_click = Some(GameSort::Strongest); + } + }); + h.col(|ui| { + ui.label(RichText::new(tr("Black")).strong()); + }); + h.col(|ui| { + ui.label(RichText::new("Elo").strong()); + }); + h.col(|ui| { + ui.label(RichText::new(tr("Res.")).strong()); + }); + if show_year { + h.col(|ui| { + let arrow = if sort == GameSort::Newest { " ⏷" } else { "" }; + if ui + .add( + egui::Button::new( + RichText::new(format!("{}{arrow}", tr("Year"))).strong(), + ) + .frame(false), + ) + .on_hover_text(tr("Newest first")) + .clicked() + { + sort_click = Some(GameSort::Newest); + } + }); + } + if show_then { + h.col(|ui| { + ui.label(RichText::new(tr("Then")).strong()) + .on_hover_text(tr("How the game went on from this position")); + }); + } + if show_event { + h.col(|ui| { + ui.label(RichText::new(tr("Event")).strong()); + }); + } + }) + .body(|body| { + body.rows(24.0, rows.len(), |mut row| { + let g = rows[row.index()]; + let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() }; + row.col(|ui| { + ui.label(&g.white); + }); + row.col(|ui| { + ui.label(RichText::new(elo(g.white_elo)).weak()); + }); + row.col(|ui| { + ui.label(&g.black); + }); + row.col(|ui| { + ui.label(RichText::new(elo(g.black_elo)).weak()); + }); + row.col(|ui| { + ui.label(if g.result == "1/2-1/2" { + "½-½" + } else { + g.result.as_str() + }); + }); + if show_year { + row.col(|ui| { + if g.year > 0 { + ui.label(RichText::new(g.year.to_string()).weak()); + } + }); + } + if show_then { + row.col(|ui| { + ui.label(&g.then); + }); + } + if show_event { + row.col(|ui| { + ui.label(RichText::new(&g.event).italics().weak()); + }); + } + let r = row + .response() + .on_hover_text(tr("Double click: open this game at this position")); + if r.hovered() { + hovered = g.next; + } + if r.double_clicked() { + opened = Some(g.index); + } + }); + }); + if let Some(s) = sort_click { + self.sort = s; + } + if hovered.is_some() { + self.hover = hovered; + } + if let Some(i) = opened { + action = Some(RefAction::OpenGame(path.to_owned(), i, pos.clone())); + } + action + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn surnames() { + assert_eq!(surname("Carlsen, Magnus"), "Carlsen"); + assert_eq!(surname("Alekhine Alexander (RUS)"), "Alekhine"); + assert_eq!(surname("Kasparov"), "Kasparov"); + assert_eq!( + surname("Duke Karl / Count Isouard"), + surname("Duke of Brunswick, Count") + ); + assert_eq!(surname("?"), ""); + assert_eq!(surname("NN"), ""); + } + + #[test] + fn best_of_many() { + let v: Vec = (0..1000).collect(); + let top = best(v, 5, |x| (*x % 97, *x)); + assert_eq!(top.len(), 5); + assert!(top.iter().all(|x| x % 97 == 96)); + assert!(top.windows(2).all(|w| w[0] > w[1])); + } + + fn classics() -> Arc { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples/classics.pgn"); + let db = chess_core::PgnDatabase::open(&path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + Arc::new(Database::Pgn(chess_import::PgnDb::new(db))) + } + + /// The tables of a small database: every listed game reaches the position, the + /// games of a move played it, strongest first, and "then" starts with that move. + #[test] + fn tables_of_the_classics() { + let db = classics(); + let mut pos = Chess::default(); + let e4: Move = "e2e4".parse::().unwrap().to_move(&pos).unwrap(); + pos.play_unchecked(e4); + let q = PositionQuery::new(pos.clone(), Some(vec![e4])); + let out = db + .search_position(None, &q, &Default::default(), &Default::default()) + .expect("searches"); + let n = out.matches.len(); + let found = tables(&db, &pos, out, &AtomicBool::new(false)).expect("not cancelled"); + assert_eq!(found.strongest.len(), n.min(GAMES_SHOWN)); + for w in found.strongest.windows(2) { + assert!((w[0].average(), w[0].year) >= (w[1].average(), w[1].year)); + } + for w in found.newest.windows(2) { + assert!(w[0].year >= w[1].year); + } + for (m, rows) in &found.by_move { + let first = move_label(&pos, m.to_move(&pos).unwrap()); + let stat = found.out.moves.iter().find(|s| s.uci == *m).unwrap(); + assert_eq!(rows.len(), (stat.tally.games as usize).min(GAMES_PER_MOVE)); + for r in rows { + assert_eq!(r.next, Some(*m)); + assert!(r.then.starts_with(&first), "{} vs {first}", r.then); + } + } + } + + /// Theory and copies: a game of the database against the same database. + #[test] + fn book_of_a_game_of_the_database() { + let db = classics(); + let parsed = db.load_game(0).expect("game"); + let never = AtomicBool::new(false); + // The game itself excluded, nothing else is the same game. + let end = book_end(&db, &parsed.game, Some(0), 0, &never).expect("theory"); + assert_eq!(end.copies, vec![0]); + assert!(!end.to_the_end); + // Not excluded: the game is its own copy (same players, year, final position). + let end = book_end(&db, &parsed.game, None, 0, &never).expect("theory"); + assert_eq!(end.copies, vec![0]); + // An empty game has no theory and no copies. + let empty = Game::new(); + let end = book_end(&db, &empty, None, 0, &never).expect("theory"); + assert!(end.copies.is_empty() && !end.to_the_end); + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index e02f7d3..7aaaef5 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -84,6 +84,8 @@ pub struct Settings { pub engines_discovered: bool, /// The sample databases were put on the shelf (see `examples::first_run_setup`). pub examples_added: bool, + /// The database of the reference tab (`None`: the largest one on the shelf). + pub reference_db: Option, } /// Options of the whole-game analysis (the engine is the active one). @@ -137,6 +139,7 @@ impl Default for Settings { review: ReviewSettings::default(), engines_discovered: false, examples_added: false, + reference_db: None, } } } diff --git a/crates/chess-import/src/chessbase/base.rs b/crates/chess-import/src/chessbase/base.rs index 816636a..a846e0d 100644 --- a/crates/chess-import/src/chessbase/base.rs +++ b/crates/chess-import/src/chessbase/base.rs @@ -56,6 +56,9 @@ pub struct Base { own_booster: OnceLock, /// The opening index, once loaded (`openings.rs`; kept in the same directory). openings: Mutex>>, + /// Held by [`Base::prepare`]: two callers (the search board, the reference panel) + /// never build the same files at once; the second finds them done. + preparing: Mutex<()>, cba: Option>, /// Titles of guiding texts read so far (they are stored with the text). text_titles: Mutex>, @@ -441,6 +444,7 @@ impl Base { booster_dir: OnceLock::new(), own_booster: OnceLock::new(), openings: Mutex::new(None), + preparing: Mutex::new(()), cba: cba.map(Mutex::new), text_titles: Mutex::new(HashMap::new()), notes: Vec::new(), @@ -677,6 +681,13 @@ impl Base { /// pass over the games (`progress` counts the records done, and again while the /// index is sorted), then loads the index. `Ok(false)` when cancelled. pub fn prepare(&self, progress: &AtomicUsize, cancel: &AtomicBool) -> std::io::Result { + let _one_at_a_time = self + .preparing + .lock() + .map_err(|_| std::io::Error::other("prepare lock"))?; + if cancel.load(Ordering::Relaxed) { + return Ok(false); + } let Some(stem) = self.cache_stem() else { return Err(std::io::Error::other("no cache directory")); }; diff --git a/docs/design/reference.md b/docs/design/reference.md new file mode 100644 index 0000000..8e53a50 --- /dev/null +++ b/docs/design/reference.md @@ -0,0 +1,71 @@ +# Вкладка «Справочник» (reference) + +Статус: проект, 2026-10-19. Образец — вкладка Reference в ChessBase (`designExample/reference.png`): сверху ходы из позиции со статистикой, снизу партии, дошедшие до позиции. Наша вкладка повторяет эту схему двумя таблицами того же вида, что таблица партий библиотеки (полосатые строки, заголовки, обычный размер шрифта, а не мелкий текст). + +## Где + +Вкладка в правой панели окна партии: `Нотация | Справочник | Отчёт` (не «Справка»: её читают как «Помощь») («Отчёт» — только когда есть анализ партии). Справочнику нужна ширина: у панели с открытым «Справочником» своя ширина по умолчанию — 55 % окна (а не 40 %, как у нотации); пользователь меняет её перетаскиванием, egui запоминает отдельно для каждой вкладки. + +## Сверху: база и теория + +``` +База [ Mega Database 2026 · 11 743 083 ▾] +В базе до хода 12…Nd7 (дальше партия своя) ← ссылка: перейти к ходу +``` + +- «База» — список баз полки (имя · число партий); по умолчанию самая большая по размеру файла, выбор запоминается. +- Теория: «В базе до хода N» (ссылка), «Вся партия есть в этой базе», «Партии этой базы расходятся с этой уже на первом ходу», «Даже начала партии нет в этой базе». Сама партия и её копии не считаются. Первые 12 полуходов проверяются по одному, дальше граница ищется удвоением и делением пополам (позиция почти всегда есть в базе, если в ней есть более поздняя позиция той же линии). Ответ сохраняется, пока партия удлиняется за его пределы; номера ходов у партий с FEN — от их начала. +- Пока большая база строит индекс: «Ускоряю поиск по этой базе (один раз)… N %». + +Под выбором базы: +- строка позиции: «Ход белых · после 4…Nc6 · в партии 5.Nb5»; +- теория (строка держит высоту, пока считается: «Сверяю партию с базой…»); +- «Эта партия есть в базе — открыть», если в базе нашлась копия: партия с теми же игроками (фамилии) и годом, доходящая до финальной позиции этой. Тренеру ценно открыть, например, комментированную версию. У пустой партии копий и теории нет. + +Копии партии и сама партия (если она из этой базы) не входят в «теорию» и в таблицу партий; в счётчиках ходов остаются, как в ChessBase. + +Между блоками — горизонтальные разделители. + +## Таблица ходов + +| Ход | Партий | % | Результат | Белые | Ср. Эло | Год | Лучшие игроки | +| --- | --- | --- | --- | --- | --- | --- | --- | +| 5.Nc3 | 70 608 | 74 % | ▕██▒▒░░▏ | 55 % | 2236 | 2025 | Carlsen, Caruana | + +- **Ход** — SAN с номером; **Партий** и **%** — сколько партий сыграли ход; **Результат** — полоса белые/ничьи/чёрные (как на доске поиска), **Белые** — очки белых в процентах; **Ср. Эло** — средний рейтинг партий, где известны оба; **Год** — последний; **Лучшие игроки** — две фамилии сильнейших (по рейтингу в партии) игроков, сыгравших этот ход. +- Последняя строка — «Закончились» (партии, кончившиеся в позиции), без хода. +- Ход, сыгранный в партии, отмечен «⏵» и полужирным. +- Для книги (большинство партий без результата) — «Главы» вместо «Партий», без колонок результата, очков и Эло. +- **Один клик** выделяет ход: синяя стрелка на доске, таблица партий ниже показывает только партии с этим ходом. Повторный клик снимает выделение. **Двойной клик** играет ход в партии: переход, если такой ход в партии есть, иначе новый вариант (Ctrl+Z отменяет). +- Наведение — синяя стрелка этого хода. +- Высота — до 40 % панели, дальше прокрутка. + +## Таблица партий + +`Партии · 95 949` (или `Партии с ходом 5.Nc3 · 70 608 ✕`), под заголовком — «показаны 100 сильнейших» когда партий больше. + +| Белые | Эло | Чёрные | Эло | Рез. | Год | Дальше | Турнир | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Carlsen, Magnus | 2863 | Caruana, Fabiano | 2835 | ½-½ | 2020 | 5.Nc3 a6 6.Be2 | Chessable Masters | + +- Сильнейшие сверху (средний рейтинг, затем новее) или новые сверху — заголовки «Эло» и «Год»; это разные выборки (100 партий, у хода — 40), а не перестановка одной. Списки есть у каждого хода; «Дальше» читается для 12 самых частых. Лучшие игроки хода — по собственному рейтингу игрока, сделавшего ход. +- В PGN (до 5000 совпадений) партия учитывается во всех своих ветках: в списке каждого хода, сыгранного из позиции в любом варианте, и «Дальше» идёт от той ветки. +- **Дальше** — три полухода партии после позиции (откуда она отличается от текущей). +- Наведение — синяя стрелка следующего хода этой партии. **Двойной клик** открывает партию на этой позиции; текущая не закрывается, а остаётся в стеке (см. ниже). +- В узкой панели колонки прячутся по очереди: Турнир, Дальше, Год; у таблицы ходов — Лучшие игроки, Год, Белые, Ср. Эло. +- Ссылка «все в библиотеке ➡» открывает позицию на доске поиска этой базы. +- Открытая из списка партия не закрывает текущую: в шапке «⬅ К партии …» возвращает её как была (с несохранёнными правками). «⬅ Библиотека» и выход из программы сначала возвращают к оставленной партии с несохранёнными изменениями, чтобы вопрос «сохранить?» был о ней. Вкладка «Справочник» остаётся открытой и в следующей партии, открытой из библиотеки или из справочника. + +## Состояния + +- Нет баз на полке: «Добавьте базу в библиотеку, чтобы видеть, что здесь играли». +- База открывается: спиннер «Открываю базу…». +- База не открылась: причина, без повторов. +- Идёт подсчёт: первые 0,3 с пусто (без мигания при листании), потом «Считаю… N %»; прежний результат другой позиции не показывается. +- Поиск не удался (PGN, для таблицы позиций которого нет памяти): «Не хватает памяти…: нужно ещё около N МБ», кнопка «Попробовать ещё раз», без повторов каждый кадр. +- Позиция в базе не встречалась: «В этой базе такой позиции нет» и строка теории. +- Партия с заданной позиции (FEN): поиск по позиции работает, «тем же порядком» и теория считаются от её начала. + +## Русские числительные + +Счётчики со словом «партия» склоняются: 1 партия, 2 партии, 5 партий (`i18n::games`). diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index cc24c1a..358c711 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -42,7 +42,7 @@ XDG_CONFIG_HOME=/tmp/cfg CP_OPEN=11 CP_PLY=3 CP_ANALYZE=1 ./target/debug/chesspe ``` `CP_OPEN` — индекс партии (с 0) в первой базе списка, `CP_PLY` — шагов по основной линии, -`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). +`CP_TAB=reference` — открыть у партии вкладку «Справочник», `CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки (`=board`, `=about` — сразу эту вкладку), `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_REPORT=1` — открыть вкладку «Отчёт» (нужен готовый анализ), `CP_BEST=k` — показать на доске k-й ход лучшей линии у первой отметки движка (нужен готовый анализ), `CP_ENGINE_OFFER=1` — окно предложения скачать Stockfish (`=download` — сразу начать загрузку), `CP_BOARD="e4 c5 Nf3"` — доска поиска большой базы с этими ходами (SAN), `CP_SORT=date` — большая база по дате (новые сверху), `CP_PANE=hidden` — большая база без правой панели, `CP_FILTER="player=carlsen;years=2015-2026;elo=2600"` — несколько фильтров большой базы, `CP_FILTER_PLAYER=имя` — фильтр «Игрок» большой базы ChessBase при запуске, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. Ключ `--bench <база> [отчёт.txt]` печатает замеры базы вместо окна (`docs/dev/import.md`, «Замер на другой машине»). `CP_MEMORY_LIMIT=<МБ>` — считать доступной памятью не больше этого (пути без дебютного индекса и без таблицы позиций PGN). ## Языки From 6b1523b1b94e94b1848c724082783c56075ef41c Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 19 Oct 2026 23:48:02 +0300 Subject: [PATCH 2/7] =?UTF-8?q?=D0=A1=D0=BF=D1=80=D0=B0=D0=B2=D0=BE=D1=87?= =?UTF-8?q?=D0=BD=D0=B8=D0=BA:=20novelty=20instead=20of=20"known=20up=20to?= =?UTF-8?q?",=20"Game=20over"=20row,=20whole=20rows=20clickable,=20leaving?= =?UTF-8?q?=20asks=20about=20each=20modified=20game;=20no=20second=20Stock?= =?UTF-8?q?fish=20offer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/app.rs | 21 ++++--------- apps/desktop/src/i18n.rs | 32 +++++++++++++++++++ apps/desktop/src/reference.rs | 55 +++++++++++++++------------------ apps/desktop/src/settings_ui.rs | 8 ++++- docs/design/reference.md | 8 ++--- 5 files changed, 74 insertions(+), 50 deletions(-) diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 61a52b3..f2618d0 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -454,9 +454,9 @@ impl App { self.game = self.previous_games.pop(); return; } - // Games left for others (reference tab) with unsaved edits come first: the last - // such one is shown again and, when quitting, asked about; the library (or the - // search board) waits until none is left. + // Games left for others (reference tab) with unsaved edits are asked about one + // by one (each shown with the question) before the library, the search board or + // quitting. if let Some(k) = self .previous_games .iter() @@ -464,18 +464,9 @@ impl App { { self.previous_games.truncate(k + 1); self.game = self.previous_games.pop(); - if let Some(g) = &self.game { - let msg = trf( - "Back to {game}: it has unsaved changes", - &[("game", &g.title())], - ); - self.toast(ctx, msg); - } - if intent == CloseIntent::QuitApp { - self.confirm_close = Some(CloseIntent::QuitApp); - } - // The search board asked for was for the game just closed: not later. - self.find_after_close = None; + // Ask about it right away; its answer continues to where the user was going + // (the library, the search board, quitting). + self.confirm_close = Some(intent); return; } self.previous_games.clear(); diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 579993f..e8c146e 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -2031,6 +2031,38 @@ const ROWS: &[[&str; 6]] = &[ "Ninguna otra partida llegó a esta posición", "Nessun'altra partita ha raggiunto questa posizione", ], + [ + "Novelty:", + "Новинка:", + "Nouveauté :", + "Neuerung:", + "Novedad:", + "Novità:", + ], + [ + "The first move of this game that no other game of this database played; before it the game followed games of the database", + "Первый ход этой партии, которого нет ни в одной другой партии базы; до него партия шла по партиям базы", + "Le premier coup de cette partie qu'aucune autre partie de la base n'a joué ; avant, la partie suivait des parties de la base", + "Der erste Zug dieser Partie, den keine andere Partie der Datenbank spielte; davor folgte sie Partien der Datenbank", + "La primera jugada de esta partida que ninguna otra partida de la base jugó; antes seguía partidas de la base", + "La prima mossa di questa partita che nessun'altra partita della base ha giocato; prima seguiva partite della base", + ], + [ + "Game over", + "Конец партии", + "Fin de partie", + "Partieende", + "Fin de la partida", + "Fine partita", + ], + [ + "Games that ended in this position (resignation, draw, mate, time)", + "Столько партий закончилось в этой позиции (сдача, ничья, мат, время)", + "Parties terminées dans cette position (abandon, nulle, mat, temps)", + "Partien, die in dieser Stellung endeten (Aufgabe, Remis, Matt, Zeit)", + "Partidas que terminaron en esta posición (abandono, tablas, mate, tiempo)", + "Partite finite in questa posizione (abbandono, patta, matto, tempo)", + ], [ "Checking engine…", "Проверка движка…", diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs index 85968da..f347202 100644 --- a/apps/desktop/src/reference.rs +++ b/apps/desktop/src/reference.rs @@ -976,42 +976,30 @@ impl Reference { let line = main_line(game); let book = self.book_for(&path, &line).cloned(); let failed_book = self.book_failed.as_ref() == Some(&(path.clone(), line.clone())); - ui.horizontal(|ui| match &book { + // The novelty: the first move of the game no other game of the database played + // (the line keeps its height while it is worked out, so nothing jumps). + let novelty = book.as_ref().and_then(|b| match b.last { + _ if b.to_the_end => None, + Some(last) => game.main_child(last), + None => game.main_child(game.root()), + }); + ui.horizontal(|ui| match (&book, novelty) { _ if line.is_empty() => {} - Some(b) if b.to_the_end => { - ui.label(RichText::new(tr("The whole game is in this database")).weak()); - } - Some(BookEnd { - last: Some(node), .. - }) if *node == game.root() => { - ui.label( - RichText::new(tr( - "The games of this database leave this one at its first move", - )) - .weak(), - ); - } - Some(BookEnd { - last: Some(node), .. - }) => { - ui.label(RichText::new(tr("Known up to")).weak()); + (Some(_), Some(node)) => { + ui.label(RichText::new(tr("Novelty:")).weak()); if ui - .link(node_label(game, *node).unwrap_or_default()) + .link(node_label(game, node).unwrap_or_default()) .on_hover_text(tr( - "The last move of the game still played in other games of this database", + "The first move of this game that no other game of this database played; before it the game followed games of the database", )) .clicked() { - action = Some(RefAction::Goto(*node)); + action = Some(RefAction::Goto(node)); } } - Some(_) => { - ui.label( - RichText::new(tr("Not even the start of the game is in this database")).weak(), - ); - } - None if failed_book => {} - None => { + (Some(_), None) => {} + (None, _) if failed_book => {} + (None, _) => { ui.label(RichText::new(tr("Comparing the game with the database…")).weak()); } }); @@ -1138,6 +1126,8 @@ impl Reference { let show_score = width > 400.0 && !books; let show_elo = width > 330.0 && !books; let show_bar = !books; + // Text in the rows must not take the clicks meant for the row. + ui.style_mut().interaction.selectable_labels = false; let mut table = TableBuilder::new(ui) .id_salt("reference_moves") .striped(true) @@ -1217,7 +1207,7 @@ impl Reference { .to_move(pos) .map(|m| move_label(pos, m)) .unwrap_or_else(|_| s.san.clone()), - None => tr("Ended").to_owned(), + None => tr("Game over").to_owned(), }; row.col(|ui| { let text = if in_game { @@ -1227,9 +1217,13 @@ impl Reference { } else { RichText::new(format!(" {label}")).weak() }; - let r = ui.label(text); + let r = ui.add(egui::Label::new(text).selectable(false)); if in_game { r.on_hover_text(tr("The move played in this game")); + } else if stat.is_none() { + r.on_hover_text(tr( + "Games that ended in this position (resignation, draw, mate, time)", + )); } }); row.col(|ui| { @@ -1412,6 +1406,7 @@ impl Reference { let show_event = width > 720.0; let show_then = width > 520.0; let show_year = width > 380.0; + ui.style_mut().interaction.selectable_labels = false; let mut table = TableBuilder::new(ui) .id_salt("reference_games") .striped(true) diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index b9e51cd..fc96373 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -304,8 +304,14 @@ impl SettingsWindow { } } // ChessPenguin's Stockfish can always be (re)downloaded from here. + // Not when a Stockfish of the user's is there already (it would be the same + // engine twice). let own = crate::engines::own_stockfish().is_some(); - if !s.engines.is_empty() && !own && crate::engine_download::available() { + let has_stockfish = s + .engines + .iter() + .any(|e| e.name.to_lowercase().contains("stockfish") && e.executable().is_some()); + if !s.engines.is_empty() && !own && !has_stockfish && crate::engine_download::available() { ui.add_space(6.0); ui.horizontal(|ui| { if downloading { diff --git a/docs/design/reference.md b/docs/design/reference.md index 8e53a50..589a706 100644 --- a/docs/design/reference.md +++ b/docs/design/reference.md @@ -14,7 +14,7 @@ ``` - «База» — список баз полки (имя · число партий); по умолчанию самая большая по размеру файла, выбор запоминается. -- Теория: «В базе до хода N» (ссылка), «Вся партия есть в этой базе», «Партии этой базы расходятся с этой уже на первом ходу», «Даже начала партии нет в этой базе». Сама партия и её копии не считаются. Первые 12 полуходов проверяются по одному, дальше граница ищется удвоением и делением пополам (позиция почти всегда есть в базе, если в ней есть более поздняя позиция той же линии). Ответ сохраняется, пока партия удлиняется за его пределы; номера ходов у партий с FEN — от их начала. +- Новинка: «Новинка: 14.Nf3» (ссылка) — первый ход партии, которого нет ни в одной другой партии базы; если такого хода нет (все ходы партии встречаются в базе), строки нет. Сама партия и её копии не считаются. Первые 12 полуходов проверяются по одному, дальше граница ищется удвоением и делением пополам (позиция почти всегда есть в базе, если в ней есть более поздняя позиция той же линии). Ответ сохраняется, пока партия удлиняется за его пределы; номера ходов у партий с FEN — от их начала. - Пока большая база строит индекс: «Ускоряю поиск по этой базе (один раз)… N %». Под выбором базы: @@ -33,11 +33,11 @@ | 5.Nc3 | 70 608 | 74 % | ▕██▒▒░░▏ | 55 % | 2236 | 2025 | Carlsen, Caruana | - **Ход** — SAN с номером; **Партий** и **%** — сколько партий сыграли ход; **Результат** — полоса белые/ничьи/чёрные (как на доске поиска), **Белые** — очки белых в процентах; **Ср. Эло** — средний рейтинг партий, где известны оба; **Год** — последний; **Лучшие игроки** — две фамилии сильнейших (по рейтингу в партии) игроков, сыгравших этот ход. -- Последняя строка — «Закончились» (партии, кончившиеся в позиции), без хода. +- Последняя строка — «Конец партии»: столько партий закончилось в этой позиции (сдача, ничья, мат, время). - Ход, сыгранный в партии, отмечен «⏵» и полужирным. - Для книги (большинство партий без результата) — «Главы» вместо «Партий», без колонок результата, очков и Эло. - **Один клик** выделяет ход: синяя стрелка на доске, таблица партий ниже показывает только партии с этим ходом. Повторный клик снимает выделение. **Двойной клик** играет ход в партии: переход, если такой ход в партии есть, иначе новый вариант (Ctrl+Z отменяет). -- Наведение — синяя стрелка этого хода. +- Наведение — синяя стрелка этого хода. Строки кликаются целиком, и по тексту тоже (текст в ячейках не выделяется). - Высота — до 40 % панели, дальше прокрутка. ## Таблица партий @@ -54,7 +54,7 @@ - Наведение — синяя стрелка следующего хода этой партии. **Двойной клик** открывает партию на этой позиции; текущая не закрывается, а остаётся в стеке (см. ниже). - В узкой панели колонки прячутся по очереди: Турнир, Дальше, Год; у таблицы ходов — Лучшие игроки, Год, Белые, Ср. Эло. - Ссылка «все в библиотеке ➡» открывает позицию на доске поиска этой базы. -- Открытая из списка партия не закрывает текущую: в шапке «⬅ К партии …» возвращает её как была (с несохранёнными правками). «⬅ Библиотека» и выход из программы сначала возвращают к оставленной партии с несохранёнными изменениями, чтобы вопрос «сохранить?» был о ней. Вкладка «Справочник» остаётся открытой и в следующей партии, открытой из библиотеки или из справочника. +- Открытая из списка партия не закрывает текущую: в шапке «⬅ К партии …» возвращает её как была (с несохранёнными правками). «⬅ Библиотека» и выход из программы по очереди спрашивают «сохранить?» про каждую оставленную партию с несохранёнными изменениями (показывая её), затем идут, куда просили. Вкладка «Справочник» остаётся открытой и в следующей партии, открытой из библиотеки или из справочника. ## Состояния From 5d6a73aff5b21e0ce78da02c16d2b65fbc98fdaf Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Mon, 19 Oct 2026 23:54:48 +0300 Subject: [PATCH 3/7] =?UTF-8?q?=D0=A1=D0=BF=D1=80=D0=B0=D0=B2=D0=BE=D1=87?= =?UTF-8?q?=D0=BD=D0=B8=D0=BA:=20"Without=20moves"=20in=20the=20start=20po?= =?UTF-8?q?sition,=20no=20"comparing"=20text?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/i18n.rs | 16 ++++++++++++++++ apps/desktop/src/reference.rs | 13 ++++++++++--- docs/design/reference.md | 4 ++-- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index e8c146e..8e2966f 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -2063,6 +2063,22 @@ const ROWS: &[[&str; 6]] = &[ "Partidas que terminaron en esta posición (abandono, tablas, mate, tiempo)", "Partite finite in questa posizione (abbandono, patta, matto, tempo)", ], + [ + "Without moves", + "Без ходов", + "Sans coups", + "Ohne Züge", + "Sin jugadas", + "Senza mosse", + ], + [ + "Games of the database with only the players and the result, no moves", + "Партии базы, у которых записаны только игроки и результат, без ходов", + "Parties de la base avec seulement les joueurs et le résultat, sans coups", + "Partien der Datenbank nur mit Spielern und Ergebnis, ohne Züge", + "Partidas de la base solo con los jugadores y el resultado, sin jugadas", + "Partite della base con solo giocatori e risultato, senza mosse", + ], [ "Checking engine…", "Проверка движка…", diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs index f347202..9cb7280 100644 --- a/apps/desktop/src/reference.rs +++ b/apps/desktop/src/reference.rs @@ -975,7 +975,6 @@ impl Reference { // while it is worked out, so nothing jumps). let line = main_line(game); let book = self.book_for(&path, &line).cloned(); - let failed_book = self.book_failed.as_ref() == Some(&(path.clone(), line.clone())); // The novelty: the first move of the game no other game of the database played // (the line keeps its height while it is worked out, so nothing jumps). let novelty = book.as_ref().and_then(|b| match b.last { @@ -998,9 +997,10 @@ impl Reference { } } (Some(_), None) => {} - (None, _) if failed_book => {} + // Still being worked out: an empty line of the same height, so the tables + // do not jump when the novelty appears. (None, _) => { - ui.label(RichText::new(tr("Comparing the game with the database…")).weak()); + ui.label(" "); } }); // The game itself is in the database (maybe annotated there): open it. @@ -1110,6 +1110,7 @@ impl Reference { let books = found.books; let total: u32 = out.moves.iter().map(|m| m.tally.games).sum::() + out.ended.games; let mut action = None; + let start = chess_import::position::same_position(pos, &Chess::default()); let rows = out.moves.len() + usize::from(out.ended.games > 0); if rows == 0 { // The games go on with a null move (a teaching "--"), which is not a move. @@ -1207,6 +1208,8 @@ impl Reference { .to_move(pos) .map(|m| move_label(pos, m)) .unwrap_or_else(|_| s.san.clone()), + // In the start position "ended" are games recorded without moves. + None if start => tr("Without moves").to_owned(), None => tr("Game over").to_owned(), }; row.col(|ui| { @@ -1220,6 +1223,10 @@ impl Reference { let r = ui.add(egui::Label::new(text).selectable(false)); if in_game { r.on_hover_text(tr("The move played in this game")); + } else if stat.is_none() && start { + r.on_hover_text(tr( + "Games of the database with only the players and the result, no moves", + )); } else if stat.is_none() { r.on_hover_text(tr( "Games that ended in this position (resignation, draw, mate, time)", diff --git a/docs/design/reference.md b/docs/design/reference.md index 589a706..eb8c5e0 100644 --- a/docs/design/reference.md +++ b/docs/design/reference.md @@ -19,7 +19,7 @@ Под выбором базы: - строка позиции: «Ход белых · после 4…Nc6 · в партии 5.Nb5»; -- теория (строка держит высоту, пока считается: «Сверяю партию с базой…»); +- новинка (пока считается, строка пустая, но держит высоту); - «Эта партия есть в базе — открыть», если в базе нашлась копия: партия с теми же игроками (фамилии) и годом, доходящая до финальной позиции этой. Тренеру ценно открыть, например, комментированную версию. У пустой партии копий и теории нет. Копии партии и сама партия (если она из этой базы) не входят в «теорию» и в таблицу партий; в счётчиках ходов остаются, как в ChessBase. @@ -33,7 +33,7 @@ | 5.Nc3 | 70 608 | 74 % | ▕██▒▒░░▏ | 55 % | 2236 | 2025 | Carlsen, Caruana | - **Ход** — SAN с номером; **Партий** и **%** — сколько партий сыграли ход; **Результат** — полоса белые/ничьи/чёрные (как на доске поиска), **Белые** — очки белых в процентах; **Ср. Эло** — средний рейтинг партий, где известны оба; **Год** — последний; **Лучшие игроки** — две фамилии сильнейших (по рейтингу в партии) игроков, сыгравших этот ход. -- Последняя строка — «Конец партии»: столько партий закончилось в этой позиции (сдача, ничья, мат, время). +- Последняя строка — «Конец партии»: столько партий закончилось в этой позиции (сдача, ничья, мат, время). В начальной позиции это партии, записанные без ходов (только игроки и результат), строка называется «Без ходов». - Ход, сыгранный в партии, отмечен «⏵» и полужирным. - Для книги (большинство партий без результата) — «Главы» вместо «Партий», без колонок результата, очков и Эло. - **Один клик** выделяет ход: синяя стрелка на доске, таблица партий ниже показывает только партии с этим ходом. Повторный клик снимает выделение. **Двойной клик** играет ход в партии: переход, если такой ход в партии есть, иначе новый вариант (Ctrl+Z отменяет). From 24326abeb4ef4c1bac01583fde5a33d50f2a1b21 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 00:04:13 +0300 Subject: [PATCH 4/7] =?UTF-8?q?Game=20view:=20the=20board=20always=20keeps?= =?UTF-8?q?=20the=20full=20height=20(side=20panel=20capped);=20=D0=A1?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BE=D1=87=D0=BD=D0=B8=D0=BA:=20novel?= =?UTF-8?q?ty=20and=20copy=20on=20the=20database=20line?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/game_view.rs | 23 ++++-- apps/desktop/src/reference.rs | 136 +++++++++++++++++----------------- docs/design/reference.md | 5 +- 3 files changed, 87 insertions(+), 77 deletions(-) diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 05a8bba..db29558 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -247,19 +247,28 @@ impl GameView { self.sync_analysis(analysis); let databases = settings.databases.clone(); egui::Panel::top("game_header").show(ui, |ui| self.header(ui, &databases, &mut actions)); - // Keep room for the board on narrow windows: the side panel never exceeds 60 %. + // The board takes the full height of the window: the side panel is never wider + // than what is left beside it (the user can make it narrower, not wider). The + // reference tab has two wide tables and its own width (egui remembers each). let width = ui.available_width(); - // The reference tab has two wide tables: its own (wider) panel width, which - // egui remembers apart from the notation's. - let (side_id, side_width) = if self.side_tab == SideTab::Reference { - ("game_side_reference", (width * 0.55).clamp(360.0, 1100.0)) + let height = ui.available_height(); + let graph = self.review.visible && (self.review.has_data() || self.review.running()); + let board = if graph { + height - (height * 0.14).clamp(80.0, 130.0) - 8.0 } else { - ("game_side", (width * 0.4).clamp(260.0, 460.0)) + height + } - 16.0; + let room = (width - board - 24.0).max(240.0); + let (side_id, side_width) = if self.side_tab == SideTab::Reference { + ("game_side_ref", room.min(1100.0)) + } else { + ("game_side", (width * 0.4).clamp(260.0, 460.0).min(room)) }; + let max = room.max(side_width).min((width * 0.7).max(240.0)); egui::Panel::right(side_id) .resizable(true) .default_size(side_width) - .size_range(240.0_f32.min(width * 0.5)..=(width * 0.7).max(240.0)) + .size_range(240.0_f32.min(width * 0.5).min(max)..=max) .show(ui, |ui| { self.side_panel(ui, settings, analysis, reference, &mut actions) }); diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs index 9cb7280..af35c3d 100644 --- a/apps/desktop/src/reference.rs +++ b/apps/desktop/src/reference.rs @@ -711,6 +711,14 @@ fn book_end( }) } +/// "Mega Database 2026 · 11,7 млн партий" for the database picker. +fn db_label(d: &RefDb) -> String { + match &d.db { + Some(db) => format!("{} · {}", d.name, crate::i18n::games_short(db.len())), + None => format!("{} · {}", d.name, tr("not open")), + } +} + impl Reference { /// The move under the pointer, or the selected one (an arrow on the board). pub fn hover(&self) -> Option { @@ -884,27 +892,77 @@ impl Reference { }; let path = current.path.clone(); let db = current.db.clone(); - // The database picker. - ui.horizontal(|ui| { + let failed = current.failed.clone(); + let current_label = db_label(current); + let query = query_for(game, cursor); + let exclude = source.filter(|(p, _)| *p == path).map(|(_, i)| i); + if let (Some(db), Some(q)) = (&db, &query) { + self.request(ui.ctx(), &path, db, game, q, exclude); + if self.job.is_some() || self.prepare.is_some() || self.book_job.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(100)); + } + } + // The novelty (the first move of the game no other game of the database played) + // and a copy of the game in the database, once worked out. + let line = main_line(game); + let book = db + .is_some() + .then(|| self.book_for(&path, &line).cloned()) + .flatten(); + let novelty = book.as_ref().and_then(|b| match b.last { + _ if b.to_the_end || line.is_empty() => None, + Some(last) => game.main_child(last), + None => game.main_child(game.root()), + }); + let copy = book + .as_ref() + .and_then(|b| b.copies.iter().copied().find(|c| Some(*c) != exclude)); + // The first line: the database, then the novelty and the copy beside it (they + // come a moment later; on this line they take no room of their own). + ui.horizontal_wrapped(|ui| { ui.label(tr("Database")); - let label = |d: &RefDb| match &d.db { - Some(db) => format!("{} · {}", d.name, crate::i18n::games_short(db.len())), - None => format!("{} · {}", d.name, tr("not open")), - }; egui::ComboBox::from_id_salt("reference_db") - .selected_text(label(current)) - .width(ui.available_width().min(380.0)) + .selected_text(current_label) + .width(ui.available_width().min(340.0)) .truncate() .show_ui(ui, |ui| { for d in &self.dbs { - if ui.selectable_label(d.path == path, label(d)).clicked() && d.path != path + if ui.selectable_label(d.path == path, db_label(d)).clicked() + && d.path != path { action = Some(RefAction::Choose(d.path.clone())); } } }); + if let Some(node) = novelty { + ui.add_space(8.0); + ui.label(RichText::new(tr("Novelty:")).weak()); + if ui + .link(node_label(game, node).unwrap_or_default()) + .on_hover_text(tr( + "The first move of this game that no other game of this database played; before it the game followed games of the database", + )) + .clicked() + { + action = Some(RefAction::Goto(node)); + } + } + if let (Some(c), Some(q)) = (copy, &query) { + ui.add_space(8.0); + ui.label(RichText::new(tr("This game is in the database")).weak()); + if ui + .link(tr("open it")) + .on_hover_text(tr( + "Open the copy of this game from the database at this position", + )) + .clicked() + { + action = Some(RefAction::OpenGame(path.clone(), c, q.position.clone())); + } + } }); - if let Some(e) = ¤t.failed { + if let Some(e) = &failed { ui.add_space(8.0); ui.label( RichText::new(trf("This database cannot be opened: {e}", &[("e", e)])) @@ -920,16 +978,10 @@ impl Reference { }); return action.or(Some(RefAction::Load(path))); }; - let Some(query) = query_for(game, cursor) else { + let Some(query) = query else { return action; }; let pos = query.position.clone(); - let exclude = source.filter(|(p, _)| *p == path).map(|(_, i)| i); - self.request(ui.ctx(), &path, &db, game, &query, exclude); - if self.job.is_some() || self.prepare.is_some() || self.book_job.is_some() { - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - } if let Some((p, job)) = &self.prepare && *p == path { @@ -971,56 +1023,6 @@ impl Reference { )); } ui.label(RichText::new(context).weak()); - // Theory: where the main line leaves the database (the line keeps its height - // while it is worked out, so nothing jumps). - let line = main_line(game); - let book = self.book_for(&path, &line).cloned(); - // The novelty: the first move of the game no other game of the database played - // (the line keeps its height while it is worked out, so nothing jumps). - let novelty = book.as_ref().and_then(|b| match b.last { - _ if b.to_the_end => None, - Some(last) => game.main_child(last), - None => game.main_child(game.root()), - }); - ui.horizontal(|ui| match (&book, novelty) { - _ if line.is_empty() => {} - (Some(_), Some(node)) => { - ui.label(RichText::new(tr("Novelty:")).weak()); - if ui - .link(node_label(game, node).unwrap_or_default()) - .on_hover_text(tr( - "The first move of this game that no other game of this database played; before it the game followed games of the database", - )) - .clicked() - { - action = Some(RefAction::Goto(node)); - } - } - (Some(_), None) => {} - // Still being worked out: an empty line of the same height, so the tables - // do not jump when the novelty appears. - (None, _) => { - ui.label(" "); - } - }); - // The game itself is in the database (maybe annotated there): open it. - if let Some(copy) = book - .as_ref() - .and_then(|b| b.copies.iter().find(|c| Some(**c) != exclude)) - { - ui.horizontal(|ui| { - ui.label(RichText::new(tr("This game is in the database")).weak()); - if ui - .link(tr("open it")) - .on_hover_text(tr( - "Open the copy of this game from the database at this position", - )) - .clicked() - { - action = Some(RefAction::OpenGame(path.clone(), *copy, pos.clone())); - } - }); - } ui.separator(); let current_key = key(&path, &query); let shown = self diff --git a/docs/design/reference.md b/docs/design/reference.md index eb8c5e0..7ff63df 100644 --- a/docs/design/reference.md +++ b/docs/design/reference.md @@ -4,7 +4,7 @@ ## Где -Вкладка в правой панели окна партии: `Нотация | Справочник | Отчёт` (не «Справка»: её читают как «Помощь») («Отчёт» — только когда есть анализ партии). Справочнику нужна ширина: у панели с открытым «Справочником» своя ширина по умолчанию — 55 % окна (а не 40 %, как у нотации); пользователь меняет её перетаскиванием, egui запоминает отдельно для каждой вкладки. +Вкладка в правой панели окна партии: `Нотация | Справочник | Отчёт` (не «Справка»: её читают как «Помощь») («Отчёт» — только когда есть анализ партии). Справочнику нужна ширина: у панели с открытым «Справочником» своя ширина — всё, что остаётся рядом с доской во всю высоту окна (у нотации — 40 %, не больше 460). Панель никогда не шире этого, доска не уменьшается; уже — можно, перетаскиванием (egui запоминает отдельно для каждой вкладки). ## Сверху: база и теория @@ -17,9 +17,8 @@ - Новинка: «Новинка: 14.Nf3» (ссылка) — первый ход партии, которого нет ни в одной другой партии базы; если такого хода нет (все ходы партии встречаются в базе), строки нет. Сама партия и её копии не считаются. Первые 12 полуходов проверяются по одному, дальше граница ищется удвоением и делением пополам (позиция почти всегда есть в базе, если в ней есть более поздняя позиция той же линии). Ответ сохраняется, пока партия удлиняется за его пределы; номера ходов у партий с FEN — от их начала. - Пока большая база строит индекс: «Ускоряю поиск по этой базе (один раз)… N %». -Под выбором базы: +В строке выбора базы, справа от него (появляются через мгновение и не занимают своей строки): «Новинка: 14.Bg5» и «Эта партия есть в базе — открыть». Под ней: - строка позиции: «Ход белых · после 4…Nc6 · в партии 5.Nb5»; -- новинка (пока считается, строка пустая, но держит высоту); - «Эта партия есть в базе — открыть», если в базе нашлась копия: партия с теми же игроками (фамилии) и годом, доходящая до финальной позиции этой. Тренеру ценно открыть, например, комментированную версию. У пустой партии копий и теории нет. Копии партии и сама партия (если она из этой базы) не входят в «теорию» и в таблицу партий; в счётчиках ходов остаются, как в ChessBase. From eb923234af44ff9384c1228e95c720268959fd1d Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 00:11:36 +0300 Subject: [PATCH 5/7] ChessPenguin 0.7.0 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++++++--- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- .../io.github.vrubelroman.chessPenguin.metainfo.xml | 5 +++++ 4 files changed, 16 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45a1952..4d6a705 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). -## [Unreleased] +## [0.7.0] — 2026-10-20 - «Справочник» (Reference) tab of a game: what was played in the current position in a database of the shelf (Mega for theory, an opening collection, a pupil's games), as two @@ -11,8 +11,11 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https position with how they went on. Click a move to see its games, double-click to play it; double-click a game to open it at this position (the current game stays a click away: "⬅ Back to …", unsaved edits included). It also tells how far the game follows the - database ("known up to 13…Bf5") and finds the game itself there (to open, for example, an - annotated copy). + database (the novelty: the first move no other game of the database played) and finds the + game itself there (to open, for example, an annotated copy). +- The board of a game always keeps the full height of the window (the side panel is never + wider than the room beside it). +- Settings → Engines no longer offers to download Stockfish when one is already set up. - Russian numbers use a decimal comma ("11,7 млн"). ## [0.6.3] — 2026-10-19 diff --git a/Cargo.lock b/Cargo.lock index 99aff22..faa95a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -661,7 +661,7 @@ dependencies = [ [[package]] name = "chess-core" -version = "0.6.3" +version = "0.7.0" dependencies = [ "encoding_rs", "pgn-reader", @@ -671,7 +671,7 @@ dependencies = [ [[package]] name = "chess-import" -version = "0.6.3" +version = "0.7.0" dependencies = [ "chess-core", "encoding_rs", @@ -684,7 +684,7 @@ dependencies = [ [[package]] name = "chesspenguin" -version = "0.6.3" +version = "0.7.0" dependencies = [ "arboard", "chess-core", @@ -4284,7 +4284,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "uci" -version = "0.6.3" +version = "0.7.0" dependencies = [ "thiserror 2.0.21", ] diff --git a/Cargo.toml b/Cargo.toml index b8dd710..c965437 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/chess-core", "crates/chess-import", "crates/uci", "apps/desktop"] [workspace.package] -version = "0.6.3" +version = "0.7.0" edition = "2024" rust-version = "1.97" license = "GPL-3.0-or-later" diff --git a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml index 1f4a1b1..eb88df1 100644 --- a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml +++ b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml @@ -43,6 +43,11 @@ BoardGame + + +

The «Reference» tab of a game: what was played in the current position in a database of the shelf — the moves with their statistics and the strongest games, the novelty of the game, and its copy in the database. The board always keeps the full height of the window.

+
+

Faster position search in large ChessBase databases: an opening index (when there is enough memory) and a search index of its own for databases without one. Quieter import notes; the email in Settings → About is copied on click.

From d670d63bcc95bc47556784051e3f6e2b233d79b9 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 00:12:14 +0300 Subject: [PATCH 6/7] publish-github.sh: publish main and tags only (work-in-progress branches stay on Forgejo) Co-Authored-By: Claude Opus 5.5 --- scripts/publish-github.sh | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/scripts/publish-github.sh b/scripts/publish-github.sh index 2cad09d..5e81a51 100755 --- a/scripts/publish-github.sh +++ b/scripts/publish-github.sh @@ -38,6 +38,11 @@ work="$(mktemp -d)" trap 'rm -rf "${work}"' EXIT git clone --quiet --bare --no-local "${root}" "${work}/repo.git" cd "${work}/repo.git" +# Only main and the tags are published: other branches (work in progress) are dropped +# from this copy before filtering. +git for-each-ref --format='%(refname)' refs/heads | grep -vx 'refs/heads/main' | while read -r ref; do + git update-ref -d "${ref}" +done quoted="" for p in "${internal[@]}"; do From b4621bc07771b93d185b166fab1509075134b303 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 00:23:34 +0300 Subject: [PATCH 7/7] AUR PKGBUILD for chesspenguin-bin 0.7.0 Co-Authored-By: Claude Opus 5.5 --- packaging/aur/chesspenguin-bin/.SRCINFO | 6 +++--- packaging/aur/chesspenguin-bin/PKGBUILD | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packaging/aur/chesspenguin-bin/.SRCINFO b/packaging/aur/chesspenguin-bin/.SRCINFO index 3f3d63c..f080dbf 100644 --- a/packaging/aur/chesspenguin-bin/.SRCINFO +++ b/packaging/aur/chesspenguin-bin/.SRCINFO @@ -1,6 +1,6 @@ pkgbase = chesspenguin-bin pkgdesc = Chess database: view, enter and analyse PGN and ChessBase games; Stockfish on request - pkgver = 0.6.3 + pkgver = 0.7.0 pkgrel = 1 url = https://github.com/vrubelroman/chessPenguin arch = x86_64 @@ -17,7 +17,7 @@ pkgbase = chesspenguin-bin provides = chesspenguin conflicts = chesspenguin options = !debug - source = https://github.com/vrubelroman/chessPenguin/releases/download/v0.6.3/ChessPenguin-0.6.3-linux-x86_64.tar.gz - sha256sums = c94801bc455a35888ffe13fb79732c859ca1b1f0d9c18ee4e8a6c434da54f03a + source = https://github.com/vrubelroman/chessPenguin/releases/download/v0.7.0/ChessPenguin-0.7.0-linux-x86_64.tar.gz + sha256sums = e8ca8d548aa2543ee0e83e96cfb6bd4dde3460d0f37cf69d0acf2e11c150589c pkgname = chesspenguin-bin diff --git a/packaging/aur/chesspenguin-bin/PKGBUILD b/packaging/aur/chesspenguin-bin/PKGBUILD index 368cb0e..e243e07 100644 --- a/packaging/aur/chesspenguin-bin/PKGBUILD +++ b/packaging/aur/chesspenguin-bin/PKGBUILD @@ -1,7 +1,7 @@ # Maintainer: vrubelroman pkgname=chesspenguin-bin _appid=io.github.vrubelroman.chessPenguin -pkgver=0.6.3 +pkgver=0.7.0 pkgrel=1 pkgdesc="Chess database: view, enter and analyse PGN and ChessBase games; Stockfish on request" arch=('x86_64') @@ -14,7 +14,7 @@ provides=('chesspenguin') conflicts=('chesspenguin') options=('!debug') source=("${url}/releases/download/v${pkgver}/ChessPenguin-${pkgver}-linux-x86_64.tar.gz") -sha256sums=('c94801bc455a35888ffe13fb79732c859ca1b1f0d9c18ee4e8a6c434da54f03a') +sha256sums=('e8ca8d548aa2543ee0e83e96cfb6bd4dde3460d0f37cf69d0acf2e11c150589c') package() { cd "ChessPenguin-${pkgver}-linux-x86_64"