Opponent prep: the tester's and designer's review

Core: the most precise opening name stays down a line (a deeper position the
table names more generally, «Sicilian Defense» after 3.d4, does not take it
back), in the games' names and in the tree; one name per position across move
orders; the games and the last date of a position over all its move orders;
`evaluated()` (evaluations from the cache count). Report version 3.

Screen: errors judged from cached evaluations show without a run; «Checked N of
M positions · Continue» after «Stop» or a new depth; the report shows the book
only when it was computed with the chosen one; the dialog keeps the remembered
book and the same player reopens with the dialog's colour and book; «Deeper»
and the depth list share one path (setting kept, report from the cache); a
chosen error survives re-judging during the run; quitting during the run asks
first; Ctrl+W returns from a game opened from the report; a game opened at an
error opens after the move, a repeated error at its newest game.

Design (§12): the summary as a grid whose columns give way, counts in the
colours of the signs; result bars without numbers, faint over few games; move
lines numbered at White's moves; whole-move first-move lines; colour icons in
the openings table; ECO kept beside the name; the errors tab as one table with
row selection and keys (↑/↓/→/←/Enter); colour lines there only in the stack;
«Inaccuracies» switch (kept in settings) for the tab, the summary, the tree and
the games; «▾» at the right end; one colour order; the depth caption by the
room left; names first in narrow game lists; two-row games minimum in a low
window; the caption beside the stacked board; «others (N)» when narrow.
Designer's review recorded in docs/design/opponent-prep.md §12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-28 16:21:16 +03:00
parent 5cfadcc7f6
commit d654223665
9 changed files with 1720 additions and 748 deletions

View file

@ -249,6 +249,9 @@ pub struct App {
/// between the library and the game (opponent-prep.md §3.1).
prep_dialog: Option<PrepDialog>,
prep: Option<PrepScreen>,
/// Quitting while the opening errors are searched: asked first; «Quit» answered.
prep_quit_ask: bool,
prep_quit_ok: bool,
allow_quit: bool,
applied_dark: Option<bool>,
debug: DebugStartup,
@ -421,6 +424,8 @@ impl App {
reference: Default::default(),
prep_dialog: None,
prep: None,
prep_quit_ask: false,
prep_quit_ok: false,
engine_offer: crate::engine_offer::EngineOffer::new(),
offer_hook_done: false,
online_probe: crate::online::Probe::start(ctx),
@ -668,7 +673,7 @@ impl App {
exact: None,
side,
};
self.prep_dialog = Some(PrepDialog::new(path, entry, &self.settings));
self.prep_dialog = Some(PrepDialog::new(path, entry));
}
let Some(index) = self.debug.open else { return };
let Some(path) = self.settings.databases.first().cloned() else {
@ -793,7 +798,8 @@ impl App {
if let Some(p) = self.prep.as_mut()
&& p.matches(&start.path, &start.player)
{
p.shown = true;
// The report as it was, with the colour and the book of the dialog.
p.reopen(start.side, start.book);
return;
}
if let Some(mut old) = self.prep.take() {
@ -802,6 +808,44 @@ impl App {
self.prep = Some(PrepScreen::new(start, db, &self.settings, ctx));
}
/// «Opening errors are being searched. Quit and stop?»
fn prep_quit_question(&mut self, ctx: &egui::Context) {
if !self.prep_quit_ask {
return;
}
let mut choice = None;
egui::Modal::new(egui::Id::new("prep_quit")).show(ctx, |ui| {
ui.set_width(400.0);
ui.label(tr("Opening errors are being searched. Quit and stop?"));
ui.label(RichText::new(tr("What was found is kept.")).weak());
ui.add_space(8.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Cancel")).clicked() {
choice = Some(false);
}
if crate::widgets::primary(ui, tr("Quit")).clicked() {
choice = Some(true);
}
});
});
if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) {
choice = Some(false);
}
match choice {
Some(true) => {
self.prep_quit_ask = false;
self.prep_quit_ok = true;
if let Some(p) = self.prep.as_mut() {
p.stop();
}
// The usual way out from here (unsaved games are asked about).
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
}
Some(false) => self.prep_quit_ask = false,
None => {}
}
}
/// The preparation's dialog, when it is open.
fn prep_dialog(&mut self, ctx: &egui::Context) {
if self.prep_dialog.is_none() {
@ -2808,9 +2852,21 @@ impl eframe::App for App {
});
self.applied_dark = Some(self.settings.dark_mode);
}
// Quitting while the opening errors are searched: asked first (what was found
// is kept either way).
if ctx.input(|i| i.viewport().close_requested())
&& !self.allow_quit
&& !self.prep_quit_ok
&& self.prep.as_ref().is_some_and(|p| p.running())
{
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.prep_quit_ask = true;
}
let quitting = !self.prep_quit_ask;
// Quitting: a comment being written goes into the game first, so the question
// about unsaved changes counts it.
if ctx.input(|i| i.viewport().close_requested())
if quitting
&& ctx.input(|i| i.viewport().close_requested())
&& !self.allow_quit
&& let Some(g) = self.game.as_mut()
{
@ -2829,7 +2885,8 @@ impl eframe::App for App {
}
// 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())
if quitting
&& 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
@ -2841,7 +2898,8 @@ impl eframe::App for App {
self.game = self.previous_games.pop();
}
// (A game against Maia in progress has asked «The game is on» instead.)
if ctx.input(|i| i.viewport().close_requested())
if quitting
&& ctx.input(|i| i.viewport().close_requested())
&& !self.allow_quit
&& self
.game
@ -2920,6 +2978,7 @@ impl eframe::App for App {
// The analysis options (its dialog) are kept.
self.settings_dirty |= self.settings.review != review;
self.reference_tab = game.reference_tab();
let game_back_previous = game.previous_prep && game.previous.is_some();
// Before the actions: leaving may take the game away.
if let Some(res) = game.record_news.take() {
let name = game.player_name();
@ -2928,6 +2987,16 @@ impl eframe::App for App {
for a in actions {
match a {
GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary),
GameAction::BackKey => {
// Ctrl+W: back where the game was opened from (the report, a
// game), else to the library.
let intent = if game_back_previous {
CloseIntent::ReturnToPrevious
} else {
CloseIntent::BackToLibrary
};
self.request_close(&ctx, intent);
}
// The game's database in the library, the game's row shown (its row is
// revealed as the game closes).
GameAction::OpenDatabase(path) => {
@ -3114,11 +3183,7 @@ impl eframe::App for App {
}) && self.prep_dialog.is_none()
&& let Some((path, entry)) = self.library.prep_entry()
{
self.prep_dialog = Some(PrepDialog::new(
path,
entry.unwrap_or_default(),
&self.settings,
));
self.prep_dialog = Some(PrepDialog::new(path, entry.unwrap_or_default()));
}
self.online_probe.poll();
self.library.online = self.online_probe.any();
@ -3188,7 +3253,7 @@ impl eframe::App for App {
self.edit_game_data();
}
LibraryAction::PrepareAgainst { path, entry } => {
self.prep_dialog = Some(PrepDialog::new(path, entry, &self.settings));
self.prep_dialog = Some(PrepDialog::new(path, entry));
}
}
}
@ -3331,6 +3396,7 @@ impl eframe::App for App {
self.confirm_dialog(&ctx);
self.own_dialogs(&ctx);
self.prep_dialog(&ctx);
self.prep_quit_question(&ctx);
// Whether the database the dialog names is there, as last found.
if let Some(d) = self.play_dialog.as_mut() {
d.target_there = d

View file

@ -120,6 +120,8 @@ enum SideTab {
pub enum GameAction {
Back,
/// Ctrl+W: back to what the game was opened from, else to the library.
BackKey,
/// Back to the library with this database chosen (the game's own).
OpenDatabase(PathBuf),
/// «Play on from here»: the play dialog for this position.
@ -1016,7 +1018,9 @@ impl GameView {
ui.horizontal(|ui| {
if ui
.button(if compact { "⬅" } else { tr("⬅ Library") })
.on_hover_text(if self.previous.is_some() {
.on_hover_text(if self.previous_prep {
tr("Back to the game list")
} else if self.previous.is_some() {
tr("Back to the game list (Ctrl+W)")
} else {
tr("Back to the game list (Esc, Ctrl+W)")
@ -1028,13 +1032,13 @@ impl GameView {
if let Some(b) = &back_to
&& ui
.button(if compact { "⬅" } else { b.as_str() })
.on_hover_text(if compact {
format!(
"{b}\n{}",
.on_hover_text({
let hint = if self.previous_prep {
tr("The preparation this game was opened from, as you left it (Esc, Ctrl+W)")
} else {
tr("The game this one was opened from, as you left it (Esc)")
)
} else {
tr("The game this one was opened from, as you left it (Esc)").to_owned()
};
if compact { format!("{b}\n{hint}") } else { hint.to_owned() }
})
.clicked()
{
@ -4826,7 +4830,7 @@ impl GameView {
}
"add_to_db" => actions.push(GameAction::AddToDatabase),
"game_data" => actions.push(GameAction::EditGameData),
"back" => actions.push(GameAction::Back),
"back" => actions.push(GameAction::BackKey),
"find" if self.search_line().is_some() => {
actions.push(GameAction::FindPosition(None))
}

View file

@ -14060,17 +14060,6 @@ const ROWS: &[[&str; 9]] = &[
"Daraxt va dvijok qanchalik chuqur qaraydi",
"Ағаш пен қозғалтқыш қаншалықты терең қарайды",
],
[
"♙ Board",
"♙ Доска",
"♙ Échiquier",
"♙ Brett",
"♙ Tablero",
"♙ Scacchiera",
"♙ Tabuleiro",
"♙ Taxta",
"♙ Тақта",
],
[
"The board of the chosen position",
"Доска выбранной позиции",
@ -14346,28 +14335,6 @@ const ROWS: &[[&str; 9]] = &[
"Birinchi yurishlar",
"Алғашқы жүрістер",
],
[
"♙ White",
"♙ Белыми",
"♙ Blancs",
"♙ Weiß",
"♙ Blancas",
"♙ Bianco",
"♙ Brancas",
"♙ Oq",
"♙ Ақ",
],
[
"♟ Black",
"♟ Чёрными",
"♟ Noirs",
"♟ Schwarz",
"♟ Negras",
"♟ Nero",
"♟ Pretas",
"♟ Qora",
"♟ Қара",
],
[
"no name",
"без названия",
@ -14434,17 +14401,6 @@ const ROWS: &[[&str; 9]] = &[
"O‘sha pozitsiyalar «Oddiy» sifatda",
"Сол позициялар «Қалыпты» сапада",
],
[
"of the checked positions",
"из проверенных позиций",
"sur les positions vérifiées",
"von den geprüften Stellungen",
"de las posiciones comprobadas",
"delle posizioni verificate",
"das posições verificadas",
"tekshirilgan pozitsiyalardan",
"тексерілген позициялардан",
],
[
"Repeated errors — the same position, the same move",
"Повторяющиеся ошибки — одна и та же позиция, тот же ход",
@ -14456,28 +14412,6 @@ const ROWS: &[[&str; 9]] = &[
"Takrorlanuvchi xatolar — o‘sha pozitsiya, o‘sha yurish",
"Қайталанатын қателер — сол позиция, сол жүріс",
],
[
"None so far",
"Пока нет",
"Aucune pour l'instant",
"Bisher keine",
"Ninguno por ahora",
"Nessuno finora",
"Nenhum até agora",
"Hozircha yo‘q",
"Әзірге жоқ",
],
[
"Position",
"Позиция",
"Position",
"Stellung",
"Posición",
"Posizione",
"Posição",
"Pozitsiya",
"Позиция",
],
[
"Played",
"Сыграл",
@ -14687,17 +14621,6 @@ const ROWS: &[[&str; 9]] = &[
"▶ Xatolar ≈ {time}",
"▶ Қателер ≈ {time}",
],
[
"Analyse {n} more positions ≈ {time}",
"Доразобрать {n} позиций ≈ {time}",
"Analyser {n} positions de plus ≈ {time}",
"{n} weitere Stellungen analysieren ≈ {time}",
"Analizar {n} posiciones más ≈ {time}",
"Analizza altre {n} posizioni ≈ {time}",
"Analisar mais {n} posições ≈ {time}",
"Yana {n} pozitsiyani tahlil qilish ≈ {time}",
"Тағы {n} позицияны талдау ≈ {time}",
],
[
"▶ Find opening errors ≈ {time}",
"▶ Найти ошибки в дебютах ≈ {time}",
@ -14753,17 +14676,6 @@ const ROWS: &[[&str; 9]] = &[
"kitobdan {n}-yurishda chiqadi, partiyalarning {p} % ida birinchi bo‘lib",
"кітаптан {n}-жүрісте шығады, партиялардың {p} % інде бірінші болып",
],
[
"Opening errors: {i} inaccuracies · {m} mistakes · {b} blunders — in {g} games ({p} %)",
"Ошибок в дебюте: неточностей {i} · ошибок {m} · зевков {b} — в {g} партиях ({p} %)",
"Erreurs d'ouverture : {i} imprécisions · {m} erreurs · {b} gaffes — dans {g} parties ({p} %)",
"Eröffnungsfehler: {i} Ungenauigkeiten · {m} Fehler · {b} grobe Fehler — in {g} Partien ({p} %)",
"Errores de apertura: {i} imprecisiones · {m} errores · {b} errores graves — en {g} partidas ({p} %)",
"Errori di apertura: {i} imprecisioni · {m} errori · {b} svarioni — in {g} partite ({p} %)",
"Erros de abertura: {i} imprecisões · {m} erros · {b} erros graves — em {g} partidas ({p} %)",
"Debyut xatolari: {i} noaniqlik · {m} xato · {b} qo‘pol xato — {g} partiyada ({p} %)",
"Дебют қателері: {i} дәлсіздік · {m} қате · {b} өрескел қате — {g} партияда ({p} %)",
],
[
"Few games ({n}): percentages and scores are unreliable",
"Партий мало ({n}) — проценты и счёт ненадёжны",
@ -14819,17 +14731,6 @@ const ROWS: &[[&str; 9]] = &[
"Boshqa tartibda ham kelingan: {orders}",
"Басқа жүріс ретімен де келген: {orders}",
],
[
"Mistake: better {best} ({before} → {after}) · in {n} games",
"Ошибка: лучше {best} (оценка {before} → {after}) · в {n} партиях",
"Erreur : mieux {best} ({before} → {after}) · dans {n} parties",
"Fehler: besser {best} ({before} → {after}) · in {n} Partien",
"Error: mejor {best} ({before} → {after}) · en {n} partidas",
"Errore: meglio {best} ({before} → {after}) · in {n} partite",
"Erro: melhor {best} ({before} → {after}) · em {n} partidas",
"Xato: yaxshisi {best} ({before} → {after}) · {n} partiyada",
"Қате: жақсысы {best} ({before} → {after}) · {n} партияда",
],
[
"Here he leaves the book: in “{book}” this position occurs {n} times",
"Здесь он выходит из книги: в «{book}» такая позиция встречается {n} раз",
@ -14885,17 +14786,6 @@ const ROWS: &[[&str; 9]] = &[
"{total} dan {done} pozitsiya tekshirildi",
"{total} ішінен {done} позиция тексерілді",
],
[
"{i} inaccuracies · {m} mistakes · {b} blunders — in {g} games of {t} ({p} %)",
"неточностей {i} · ошибок {m} · зевков {b} — в {g} партиях из {t} ({p} %)",
"{i} imprécisions · {m} erreurs · {b} gaffes — dans {g} parties sur {t} ({p} %)",
"{i} Ungenauigkeiten · {m} Fehler · {b} grobe Fehler — in {g} von {t} Partien ({p} %)",
"{i} imprecisiones · {m} errores · {b} errores graves — en {g} partidas de {t} ({p} %)",
"{i} imprecisioni · {m} errori · {b} svarioni — in {g} partite su {t} ({p} %)",
"{i} imprecisões · {m} erros · {b} erros graves — em {g} partidas de {t} ({p} %)",
"{i} noaniqlik · {m} xato · {b} qo‘pol xato — {t} tadan {g} partiyada ({p} %)",
"{i} дәлсіздік · {m} қате · {b} өрескел қате — {t} ішінен {g} партияда ({p} %)",
],
[
"No errors in the first {n} moves ({i} inaccuracies).",
"В первых {n} ходах ошибок не нашлось (неточностей {i}).",
@ -14984,6 +14874,204 @@ const ROWS: &[[&str; 9]] = &[
"{played} — yaxshisi {best} · {before} → {after}",
"{played} — жақсысы {best} · {before} → {after}",
],
[
"Opening errors are being searched. Quit and stop?",
"Идёт поиск ошибок в дебютах. Выйти и остановить?",
"La recherche d'erreurs d'ouverture est en cours. Quitter et l'arrêter ?",
"Die Suche nach Eröffnungsfehlern läuft. Beenden und stoppen?",
"Se están buscando errores de apertura. ¿Salir y detenerla?",
"È in corso la ricerca degli errori di apertura. Uscire e fermarla?",
"A busca de erros de abertura está em andamento. Sair e parar?",
"Debyut xatolari qidirilmoqda. Chiqib, to‘xtatilsinmi?",
"Дебют қателері ізделуде. Шығып, тоқтату керек пе?",
],
[
"What was found is kept.",
"Найденное сохранится.",
"Ce qui a été trouvé est conservé.",
"Was gefunden wurde, bleibt erhalten.",
"Lo encontrado se conserva.",
"Quanto trovato viene conservato.",
"O que foi encontrado é mantido.",
"Topilganlar saqlanadi.",
"Табылғаны сақталады.",
],
[
"Quit",
"Выйти",
"Quitter",
"Beenden",
"Salir",
"Esci",
"Sair",
"Chiqish",
"Шығу",
],
[
"Back to the game list",
"Назад к списку партий",
"Retour à la liste des parties",
"Zurück zur Partienliste",
"Volver a la lista de partidas",
"Torna all'elenco delle partite",
"Voltar à lista de partidas",
"Partiyalar ro‘yxatiga qaytish",
"Партиялар тізіміне оралу",
],
[
"The preparation this game was opened from, as you left it (Esc, Ctrl+W)",
"Подготовка, из которой открыта партия, — такой, как вы её оставили (Esc, Ctrl+W)",
"La préparation d'où cette partie a été ouverte, telle que vous l'avez laissée (Échap, Ctrl+W)",
"Die Vorbereitung, aus der diese Partie geöffnet wurde, so wie Sie sie verlassen haben (Esc, Strg+W)",
"La preparación desde la que se abrió esta partida, tal como la dejó (Esc, Ctrl+W)",
"La preparazione da cui è stata aperta questa partita, come l'hai lasciata (Esc, Ctrl+W)",
"A preparação de onde esta partida foi aberta, como você a deixou (Esc, Ctrl+W)",
"Bu partiya ochilgan tayyorgarlik — siz qoldirgan holatda (Esc, Ctrl+W)",
"Осы партия ашылған дайындық — сіз қалдырған күйінде (Esc, Ctrl+W)",
],
[
"no errors",
"ошибок нет",
"aucune erreur",
"keine Fehler",
"sin errores",
"nessun errore",
"sem erros",
"xatolar yo‘q",
"қателер жоқ",
],
[
"Share of the colour's games; a variation's — of its family's",
"Доля от партий цветом; у варианта — от семейства",
"Part des parties de cette couleur ; pour une variante — de sa famille",
"Anteil an den Partien dieser Farbe; bei einer Variante — an ihrer Familie",
"Parte de las partidas de ese color; de una variante — de su familia",
"Quota delle partite di quel colore; di una variante — della sua famiglia",
"Parte das partidas dessa cor; de uma variante — da sua família",
"Shu rangdagi partiyalardan ulush; variantda — oilasidan",
"Осы түстегі партиялардан үлес; нұсқада — тобынан",
],
[
"The counts are of the checked positions",
"Числа — по проверенным позициям",
"Les nombres portent sur les positions vérifiées",
"Die Zahlen gelten für die geprüften Stellungen",
"Las cifras son de las posiciones comprobadas",
"I numeri riguardano le posizioni verificate",
"Os números são das posições verificadas",
"Sonlar tekshirilgan pozitsiyalar bo‘yicha",
"Сандар тексерілген позициялар бойынша",
],
[
"Show the inaccuracies (?!) with the mistakes and blunders",
"Показывать неточности (?!) вместе с ошибками и зевками",
"Afficher les imprécisions (?!) avec les erreurs et les gaffes",
"Ungenauigkeiten (?!) mit Fehlern und groben Fehlern zeigen",
"Mostrar las imprecisiones (?!) con los errores y errores graves",
"Mostra le imprecisioni (?!) con errori e svarioni",
"Mostrar as imprecisões (?!) com os erros e erros graves",
"Noaniqliklarni (?!) xato va qo‘pol xatolar bilan ko‘rsatish",
"Дәлсіздіктерді (?!) қателер мен өрескел қателермен бірге көрсету",
],
[
"Book: {name}",
"Книга: {name}",
"Livre : {name}",
"Buch: {name}",
"Libro: {name}",
"Libro: {name}",
"Livro: {name}",
"Kitob: {name}",
"Кітап: {name}",
],
[
"White wins {w} % · draws {d} % · Black wins {b} %",
"Победы белых {w} % · ничьи {d} % · победы чёрных {b} %",
"Victoires des Blancs {w} % · nulles {d} % · victoires des Noirs {b} %",
"Weißsiege {w} % · Remis {d} % · Schwarzsiege {b} %",
"Victorias blancas {w} % · tablas {d} % · victorias negras {b} %",
"Vittorie del Bianco {w} % · patte {d} % · vittorie del Nero {b} %",
"Vitórias das brancas {w} % · empates {d} % · vitórias das pretas {b} %",
"Oq g‘alabalari {w} % · durang {d} % · qora g‘alabalari {b} %",
"Ақ жеңістері {w} % · тең {d} % · қара жеңістері {b} %",
],
[
"{n} moves",
"{n} ходов",
"{n} coups",
"{n} Züge",
"{n} jugadas",
"{n} mosse",
"{n} lances",
"{n} yurish",
"{n} жүріс",
],
[
"{n} m.",
"{n} х.",
"{n} c.",
"{n} Z.",
"{n} j.",
"{n} m.",
"{n} l.",
"{n} yur.",
"{n} ж.",
],
[
"Continue ≈ {time}",
"Продолжить ≈ {time}",
"Continuer ≈ {time}",
"Fortsetzen ≈ {time}",
"Continuar ≈ {time}",
"Continua ≈ {time}",
"Continuar ≈ {time}",
"Davom ettirish ≈ {time}",
"Жалғастыру ≈ {time}",
],
[
"Errors found · {quality} · {n} positions",
"Ошибки найдены · {quality} · {n} позиций",
"Erreurs trouvées · {quality} · {n} positions",
"Fehler gefunden · {quality} · {n} Stellungen",
"Errores encontrados · {quality} · {n} posiciones",
"Errori trovati · {quality} · {n} posizioni",
"Erros encontrados · {quality} · {n} posições",
"Xatolar topildi · {quality} · {n} pozitsiya",
"Қателер табылды · {quality} · {n} позиция",
],
[
"in {p} % of games",
"в {p} % партий",
"dans {p} % des parties",
"in {p} % der Partien",
"en el {p} % de las partidas",
"nel {p} % delle partite",
"em {p} % das partidas",
"partiyalarning {p} % ida",
"партиялардың {p} % інде",
],
[
"others ({n})",
"другие ({n})",
"autres ({n})",
"andere ({n})",
"otras ({n})",
"altre ({n})",
"outros ({n})",
"boshqalar ({n})",
"басқалары ({n})",
],
[
"{judgement}: better {best} ({before} → {after}) · in {n} games",
"{judgement}: лучше {best} (оценка {before} → {after}) · в {n} партиях",
"{judgement} : mieux {best} ({before} → {after}) · dans {n} parties",
"{judgement}: besser {best} ({before} → {after}) · in {n} Partien",
"{judgement}: mejor {best} ({before} → {after}) · en {n} partidas",
"{judgement}: meglio {best} ({before} → {after}) · in {n} partite",
"{judgement}: melhor {best} ({before} → {after}) · em {n} partidas",
"{judgement}: yaxshisi {best} ({before} → {after}) · {n} partiyada",
"{judgement}: жақсысы {best} ({before} → {after}) · {n} партияда",
],
];
#[cfg(test)]

File diff suppressed because it is too large Load diff

View file

@ -167,6 +167,8 @@ pub struct PrepSettings {
pub branches_from: u32,
/// The engine was started from the dialog once: the button starts it at once.
pub chosen: bool,
/// Inaccuracies (?!) are shown with the mistakes and blunders.
pub inaccuracies: bool,
}
impl Default for PrepSettings {
@ -177,6 +179,7 @@ impl Default for PrepSettings {
plies: 20,
branches_from: 3,
chosen: false,
inaccuracies: true,
}
}
}

View file

@ -138,7 +138,7 @@ pub struct BookInfo {
pub left: u32,
}
const REPORT_VERSION: u32 = 2;
const REPORT_VERSION: u32 = 3;
/// Everything the preparation knows about the player.
#[derive(Clone, Debug, Serialize, Deserialize)]
@ -400,6 +400,12 @@ impl PrepReport {
out
}
/// Some position has an engine evaluation (from a run or from the cache): the
/// errors are judged.
pub fn evaluated(&self) -> bool {
self.evals.values().any(|e| e.nodes != EXACT)
}
/// Distinct positions an engine run looks at.
pub fn distinct_positions(&self) -> usize {
self.positions().len()
@ -890,6 +896,7 @@ mod tests {
}
assert_eq!(report.missing(1000), 0);
assert_eq!(report.missing(2000), total);
assert!(report.evaluated());
report.refresh();
assert_eq!(report.engine.as_ref().map(|e| e.nodes), Some(1000));
let w = &report.white;
@ -921,7 +928,9 @@ mod tests {
assert!(PrepReport::load(&dir, &db, &other, &Options::default()).is_none());
let mut fresh = build(&db, &player, &Options::default(), &AtomicUsize::new(0), &never)
.expect("report");
assert!(!fresh.evaluated());
assert_eq!(fresh.take_cached(&cache, 1000), total);
assert!(fresh.evaluated(), "evaluations from the cache judge the errors too");
assert_eq!(fresh.white.repeated, report.white.repeated);
assert_eq!(fresh.take_cached(&cache, 1000), 0);
let _ = std::fs::remove_dir_all(&dir);

View file

@ -122,13 +122,34 @@ pub fn get(id: usize) -> &'static Opening {
&table().entries[id]
}
/// The deepest named position among `keys` (the positions of a line, in order): its
/// index in `keys` and its entry.
/// The name of a line (the positions `keys`, in order): its deepest named position,
/// its index in `keys` and its entry — but a deeper position whose name is only a
/// more general one ("Sicilian Defense" after 3.d4 in the "Modern Variations") does
/// not take the name back: the most precise name met stays.
pub fn deepest(keys: &[u64]) -> Option<(usize, usize)> {
keys.iter()
.enumerate()
.rev()
.find_map(|(i, k)| by_position(*k).map(|id| (i, id)))
let mut out: Option<(usize, usize)> = None;
for (i, k) in keys.iter().enumerate() {
if let Some(id) = by_position(*k)
&& out.is_none_or(|(_, cur)| !more_general(id, cur))
{
out = Some((i, id));
}
}
out
}
/// Entry `a`'s name is a more general form of entry `b`'s ("Sicilian Defense" of
/// "Sicilian Defense: Modern Variations"; "…: Najdorf Variation" of "…: Najdorf
/// Variation, English Attack").
pub fn more_general(a: usize, b: usize) -> bool {
is_prefix_name(&get(a).name, &get(b).name)
}
/// `general` names a family or a variation `precise` is part of.
pub fn is_prefix_name(general: &str, precise: &str) -> bool {
precise.len() > general.len()
&& precise.starts_with(general)
&& matches!(precise[general.len()..].chars().next(), Some(':' | ','))
}
/// The openings a report refers to, each once, in the order they were first met.
@ -198,6 +219,17 @@ mod tests {
assert_eq!(o.variation(), None);
// Nothing before the first move.
assert_eq!(deepest(&keys(&[])), None);
// A deeper position with a more general name keeps the precise one: the
// table names 1.e4 c5 2.Nf3 d6 3.d4 just «Sicilian Defense».
let line = keys(&["e4", "c5", "Nf3", "d6", "d4"]);
let after_d4 = by_position(line[5]).map(|id| get(id).name.clone());
assert_eq!(after_d4.as_deref(), Some("Sicilian Defense"));
let (at, id) = deepest(&line).expect("named");
assert_eq!((at, get(id).name.as_str()), (4, "Sicilian Defense: Modern Variations"));
assert!(is_prefix_name("Sicilian Defense", "Sicilian Defense: Modern Variations"));
assert!(is_prefix_name("A: B", "A: B, C"));
assert!(!is_prefix_name("Sicilian Defense", "Sicilian Defense"));
assert!(!is_prefix_name("English", "English Opening"));
}
#[test]

View file

@ -96,7 +96,14 @@ impl Tree {
Some(&c) => c as usize,
None => {
let key = game.keys[i + 1];
let named = openings::by_position(key);
// A more general name than the path's keeps the path's
// (see `openings::deepest`).
let parent = tree.nodes[at].opening.map(|o| openings.list[o].name.clone());
let named = openings::by_position(key).filter(|&id| {
parent
.as_deref()
.is_none_or(|p| !openings::is_prefix_name(&openings::get(id).name, p))
});
let opening = named
.map(|id| openings.intern(id))
.or(tree.nodes[at].opening);
@ -139,9 +146,52 @@ impl Tree {
for n in &mut tree.nodes {
n.transposition = seen.get(&n.key).is_some_and(|c| *c > 1);
}
// One position, one name: the most precise of its move orders' names; a node
// is «named» where its name differs from its parent's.
let mut best: HashMap<u64, usize> = HashMap::new();
for n in tree.nodes.iter().filter(|n| n.transposition) {
if let Some(o) = n.opening {
let e = best.entry(n.key).or_insert(o);
if openings::is_prefix_name(&openings.list[*e].name, &openings.list[o].name) {
*e = o;
}
}
}
for i in 0..tree.nodes.len() {
if let Some(&o) = best.get(&tree.nodes[i].key) {
tree.nodes[i].opening = Some(o);
}
let parent = tree.nodes[i].parent.and_then(|p| tree.nodes[p as usize].opening);
let name = |o: Option<usize>| o.map(|o| openings.list[o].name.as_str());
tree.nodes[i].named = tree.nodes[i].opening.is_some() && name(tree.nodes[i].opening) != name(parent);
}
tree
}
/// The games through the position `key` by any move order (indices into
/// [`crate::PrepReport::games`], in order).
pub fn position_games(&self, key: u64) -> Vec<u32> {
let mut out: Vec<u32> = self
.nodes
.iter()
.filter(|n| n.key == key)
.flat_map(|n| n.games.iter().copied())
.collect();
out.sort_unstable();
out.dedup();
out
}
/// The latest date among the games through the position `key`.
pub fn position_last_date(&self, key: u64) -> &str {
self.nodes
.iter()
.filter(|n| n.key == key)
.map(|n| n.last_date.as_str())
.max_by_key(|d| chess_import::pgn_catalog::date_number(d))
.unwrap_or("")
}
fn count(&mut self, node: usize, g: u32, game: &GameInfo) {
let n = &mut self.nodes[node];
n.tally.add(game.outcome);
@ -244,6 +294,8 @@ pub(crate) mod tests {
let after_d4 = tree.nodes.iter().find(|n| n.ply == 3 && n.san == "d4").unwrap();
assert_eq!(after_nf3.key, after_d4.key);
assert_eq!(tree.position_tally(after_nf3.key).games, 2);
assert_eq!(tree.position_games(after_nf3.key), vec![0, 1]);
assert_eq!(tree.position_last_date(after_nf3.key), "2026.03.01");
assert!(!tree.nodes.iter().find(|n| n.san == "c4").unwrap().transposition);
assert_eq!(tree.path(after_d4.parent.unwrap() as usize), vec!["Nf3", "d5"]);
// Names: 1.d4 d5 2.Nf3 is named in the table, 2...Nf6 is too (Zukertort);

View file

@ -477,6 +477,55 @@
9. **Период** (последний год / всё) как переключатель в отчёте — не делаю (объём «только дебюты», фильтр библиотеки закрывает); подтвердить.
10. **«Играть отсюда…» и «Открыть как партию»** с доски отчёта — в первую версию (рекомендация: это существующие действия) или после?
## 12. Ревью реализации (f02f140, 2026-10-28)
Проверено по снимкам разработчика (1400×1000 тёмная, 640×1000, 640×480) и своим: светлая тема (репертуар, ошибки), «Чёрные» с книгой «Эта же база», «Дебюты» при «Чёрные», диалог движка, ход движка, 804/803×900, 960×1050, диалог при 640×480, «Ошибки» и «Дебюты» при 640×1000, вход из панели фильтров. Снимки — `scratchpad/prep-design/*.png`. Не снято: выбранная ошибка со стрелками на доске (выбрать её можно только мышью — см. А6).
Общее: архитектура экрана, диалог, три вкладки, список партий, книга, движок, стопка и низкое окно — по дизайну; палитра отметок и пилюли — как в нотации, в обеих темах читаются. Замечания ниже — по приоритету: **А** мешает читать и понимать данные, **Б** расходится с визуальной системой, **В** узкие окна. У каждого — правка.
### А. Данные и понимание
1. **Сводка — одно длинное предложение.** С книгой и после движка строка цвета — ~130 знаков из семи частей через «·»; при 960 и 804 она переносится посреди фразы («Ошибок в / дебюте: …», `w960.png`, `w804.png`), и вторая строка читается как новая запись. Правка: сводка — `egui::Grid` в две строки с колонками «Цвет · Партий · Счёт (+= −) · Соперники · Последняя · Книга · Ошибки»; при нехватке ширины колонки прячутся справа налево (Книга → Соперники → Последняя), как в дереве, — переносов не бывает. Счётчики ошибок — через уже существующий `counts_text` («60 ?! · 14 ? · 8 ??» цветом отметок; плюс «в 40 % партий»): три числа одного вида в простом тексте («неточностей 60 · ошибок 14 · зевков 8») глаз не различает и они не связаны с колонками «Ошибки» в таблицах, где те же счётчики цветные. «Последняя» в сводке дублирует корень дерева — можно убрать первой.
2. **Числа в полосе счёта спорят с «Счётом».** В строке «Белыми · 138» рядом стоят «78 %» (очки) и «75» внутри полосы (доля побед белых); у чёрных внутри светлого сегмента стоит доля побед **соперника** («Queen's Pawn Game · 56 % · [56]», `openings_black.png`). Два разных числа в одной ячейке без подписи — главный источник непонимания колонки «Счёт». Правка: в полосе 56 точек чисел не рисовать (`results_bar` с флагом без текста либо своя узкая версия); проценты — только в подсказке «+10 =1 −3». Полоса остаётся абсолютной (Б светлый слева, Ч тёмный справа), как на доске поиска. Заодно: при «мало партий» полоса не приглушается (`painter_alpha` вычислен и выброшен) — рисовать её с `gamma_multiply(0.5)` или не рисовать вовсе.
3. **Линия под доской нумерует чёрные ходы:** «1.e4 1…c5 2.Nf3 2…d6». Нигде в программе так не пишут. Правка: `short_label` только для первого хода и для белых ходов; чёрные — голым SAN («1.e4 c5 2.Nf3 d6»). Та же линия нужна в «Первые ходы» таблицы дебютов, где сейчас формат таблицы lichess «1. e4 c5» (с пробелом после номера) — привести к `line_text`.
4. **«Первые ходы» нет на 1400×1000 при «Оба»** (`openings.png`): колонка «Цвет» 90 + «Дебют» ≥ 200 не оставляют 160 для ходов, и между «Дебют» и «ECO» пустота. Это именно те данные, ради которых владелец просил «всегда с первыми ходами». Правка: «Цвет» — только значок `♙`/`♟` шириной 24 с подсказкой (слово «Белыми» 11 раз подряд — шум); минимум «Дебют» 180, «Первые ходы» 140; порядок скрытия как в §6. Альтернатива лучше, но дороже: вместо колонки — строки-заголовки «Белыми · 138» / «Чёрными · 133», как корни дерева. Также сокращение линии режет ход пополам и даёт двойное многоточие («…5 4. Bg2 Be7 5. …», `openings_black.png`): `shorten_middle` — по границам ходов и по измеренной ширине, без второго `truncate`.
5. **Имя дебюта в дереве «откатывается»:** под «2…d6 Sicilian Defense: Modern Variations» стоит «3.d4 Sicilian Defense» — таблица даёт менее точное имя глубже, и правило «показывать, когда меняется» печатает его как новое. Правка: не показывать имя, если оно — префикс имени родителя (семейство без варианта); лучше — в `prep` сделать имя узла «липким» (самое глубокое имя по пути), тогда и подсказка, и таблица дебютов согласуются.
6. **Вкладка «Ошибки» без клавиатуры и без строк.** Стрелки там ничего не выбирают (`keyboard` → только Enter), а щелчок ловит лишь подпись «Позиция» / имя дебюта, не строка (`egui::Grid` без ответа строки). В «По дебютам» счётчики ошибок стоят на разной высоте — не сравнить. Правка: обе части — `TableBuilder` со `striped`, `sense(click)` и выделением строки, как дерево; клавиши ↑/↓/→/← по общему списку строк (повторяющиеся + дебюты + раскрытые партии), Enter — открыть партию. Это же даст хук для снимка выбранной ошибки (`CP_KEYS`).
7. **Четыре строки одних и тех же чисел** на 1400 (`errors.png`): сводка (2 строки) и сразу под ней в «Ошибках» «Белыми: … / Чёрными: …». Правка: во вкладке строки цветов показывать только в стопке (там сводка их не несёт, §6); рядом — только строка состояния «Ошибки найдены · Stockfish 19 · Быстро · 2 947 позиций · Точнее…».
8. **Колонка «Дебют» в дереве теряет ECO:** длинное имя забирает всю ширину, ECO обрезается до «··» («Nyezhmetdinov-Rossolimo Attack ··», `repertoire.png`). Правка: ECO класть первым в `right_to_left`, имя — в остаток с `truncate`.
9. Мелкое: «2947 позиций» без разделителя тысяч (статус, диалог, прогресс) — `large_db::grouped`; «%» в таблице дебютов без подсказки (в дереве есть) — «Доля от партий цветом; у варианта — от семейства»; «Книга [Нет ▾]» без слова «Книга» при W < 640 читается как «Нет» неизвестно чего — текст в самом списке «Книга: Нет».
### Б. Визуальная система
1. **«▾» слева от «Ошибки найдены»** (все снимки): в `right_to_left` кнопка параметров добавлена второй и встала левее подписи — выглядит как сворачивалка. Правка: добавлять «▾» первой (окажется справа), как `[Точнее…] [▾]` в §4.4.
2. **Три порядка цветов:** диалог «Оба · Белые · Чёрные», диалог движка «Белые · Чёрные · Оба», переключатель «Белые · Чёрные · Оба». Правка: везде «Белые · Чёрные · Оба».
3. **«🗙» у заголовка списка партий** — крупная рамочная кнопка тяжелее заголовка. Правка: `widgets::small_close_button`, как в диалоге у поля «Игрок» и у чипов.
4. **Полоса счёта в светлой теме** почти сливается с фоном строки (`light_rep.png`) — общее свойство `results_bar`, не этого экрана; если править п. А2 своей версией полосы — дать светлому сегменту обводку 1 px `weak_text_color` в светлой теме.
5. Глубина «Дебют: 10 ходов» при W < 760 превращается в голое «10» (`narrow640.png`), хотя в строке остаётся ~150 точек. Правка: выбирать подпись по измеренной ширине («Дебют: 10 ходов» → «10 ходов» → «10 х.»), а не по порогу окна.
### В. Узкие и низкие окна
1. **Имена в списке партий уже `NAME_MIN` 110** при 640–804 («Вафин Рад…», «Конюшенко С…», `narrow640.png`, `w804.png`): Elo и «Дальше» остаются, имена ужимаются до 82–95. Правка (как §3.10 и `board-search.md` §2.7): сначала считать `player_w`; если < 110 — прятать «Дальше», затем Elo (в ячейку имени слабым), и только потом резать имена.
2. **640×480: дереву остаётся 6 строк** (`low640.png`) — минимум списка партий 4 строки + 60 и доля 35 %. Правка: при H < 600 минимум списка — 2 строки, доля 25 %; дерево получает ≈ 10 строк.
3. В стопке над доской нет подписи «Ход белых · после 2.Nf3» (`board_caption` не вызывается, `w803.png`): добавить первой строкой в колонку справа от доски.
4. «другие ходы (1)» на глубине обрезается в «другие ход…» при минимуме колонки 180 (`w804.png`): короче — «другие (1)».
5. Пороги 804/803 и 720 работают как задумано (`w804.png` — рядом, `w803.png` — стопка; `low640.png` — доска по кнопке); диалоги при 640×480 помещаются.
### Что принимаю из отклонений разработчика
- «⤳» → «⇄» — да, яснее.
- Имя дебюта в дереве только когда меняется относительно родителя — да, с поправкой А5 (не показывать менее точное имя).
- «Первые ходы» семейства — его позиция по таблице — да.
- Строки ошибок в сводке нет в стопке — да (§6 так и задумано).
- Строка ошибок в сводке простым текстом — **нет**, см. А1: `counts_text` уже есть, это три строки правки.
- Отложены: вход с экрана партии, мини-доска в подсказке, «показать в дереве», сортировка таблицы дебютов — да; «Точнее…» только во вкладке «Ошибки», а не в строке переключателей — да, строка и так тесная.
- Автопереход на вкладку «Ошибки» при запуске движка (в дизайне не было) — да, полезно.
### Не проверено
Выбранная ошибка (стрелки сыгранного/лучшего хода, строка «… — лучше … · 0,0 → −1,2» под доской), «Остановлено → Продолжить», «нет партий цветом», «книга не открылась», партия, открытая из отчёта («⬅ К подготовке»). Для снимков нужна клавиатура во вкладке «Ошибки» (А6) или хук `CP_PREP_SELECT`.
## Изменения
- 2026-10-28: первая версия.
- 2026-10-28: §12 — ревью реализации f02f140 (замечания А/Б/В, принятые отклонения, что не проверено).