Справочник (Reference) tab: moves and games of the current position in a shelf database

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 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-19 23:20:37 +03:00
parent 7f62369dea
commit 3f16ba50fe
12 changed files with 2480 additions and 39 deletions

View file

@ -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<shakmaty::Move>, bool)>,
/// Games left for one opened from the reference tab ("⬅ Back to …"), kept as they
/// were (unsaved edits included).
previous_games: Vec<GameView>,
/// 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<bool>,
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),

View file

@ -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 {

View file

@ -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<String>,
}
#[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<std::path::PathBuf>),
/// 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<GameAction>) {
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<GameAction> {
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<shakmaty::uci::UciMove>,
actions: &mut Vec<GameAction>,
) {
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<GameAction>,
) {
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<shakmaty::Move>, bool)> {
let (start, line) = crate::board_search::line_to(&self.game, self.cursor)?;
Some((start, line, self.flipped))

View file

@ -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;

View file

@ -197,6 +197,8 @@ pub struct Library {
view: Vec<usize>,
view_key: Option<(PathBuf, String, SortKey, bool)>,
scroll_to_selected: bool,
/// File sizes of databases (`file_size`).
sizes: HashMap<PathBuf, u64>,
}
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<Arc<Database>> {
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),
);

View file

@ -15,6 +15,7 @@ mod i18n;
mod large_db;
mod library;
mod notation;
mod reference;
mod report;
mod review;
mod settings;

File diff suppressed because it is too large Load diff

View file

@ -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<PathBuf>,
}
/// 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,
}
}
}