diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ba94f9..db49696 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +- Game analysis (Shift+A): background evaluation of the whole main line with its own engine process, + evaluation graph under the board, report tab with accuracy, inaccuracies, mistakes, blunders, + average centipawn loss and accuracy per game phase; engine marks and better lines in the notation; + "Write analysis to the game" (NAGs, comments, `[%eval]`, one undo step). Results are cached; + `[%eval]` comments of a PGN are used without an engine. + ## [0.1.0] — 2026-10-18 First public release. diff --git a/README.md b/README.md index 8711e6b..b60a631 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,9 @@ mouse and keyboard navigation. - **Engine analysis** — any UCI engine, up to 5 lines, best-move arrows, evaluation bar; search time, threads and memory are set right in the analysis panel. +- **Game analysis** — evaluate the whole game in the background: evaluation graph under the board, + accuracy, inaccuracies, mistakes and blunders per player and per game phase (Lichess method), + better moves in the notation; write it into the game as NAGs, comments and `[%eval]` (undoable). - **Engine lines on the board** — step through a line without touching the game, add it as a variation with one click (undoable). - **Editing** — enter moves and variations, promote or delete lines, undo/redo, @@ -69,7 +72,7 @@ cargo run --release -p chesspenguin -- examples/classics.pgn | Where | Keys | | --- | --- | | Library | ↑/↓ select · Enter open · Ctrl+O add PGN · Ctrl+N new game · Ctrl+F search | -| Game | ←/→ move · ↑/↓ switch variation · Home/End · F flip · L engine · Esc leave preview | +| Game | ←/→ move · ↑/↓ switch variation · Home/End · F flip · L engine · Shift+A game analysis · Esc leave preview | | Editing | Ctrl+Z / Ctrl+Y undo/redo · Ctrl+Shift+C copy PGN · Ctrl+S save as · Ctrl+W back to library | ## Project layout diff --git a/README.ru.md b/README.ru.md index cac95fd..c0bdc5e 100644 --- a/README.ru.md +++ b/README.ru.md @@ -16,6 +16,9 @@ навигация мышью и клавиатурой. - **Анализ движком** — любой UCI-движок, до 5 линий, стрелки лучших ходов, шкала оценки; время, потоки и память настраиваются прямо в панели анализа. +- **Анализ партии** — оценка всей партии в фоне: график под доской, точность, неточности, ошибки + и зевки каждого игрока и по стадиям партии (методика Lichess), лучшие ходы в нотации; + запись анализа в партию знаками, комментариями и `[%eval]` (с отменой). - **Линии движка на доске** — просмотр линии без изменения партии и вставка её вариантом (с отменой). - **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор, копирование PGN/FEN, сохранение партии в новый файл. diff --git a/apps/desktop/src/analysis.rs b/apps/desktop/src/analysis.rs index 0f7fcf9..a5a2dd3 100644 --- a/apps/desktop/src/analysis.rs +++ b/apps/desktop/src/analysis.rs @@ -251,16 +251,7 @@ impl Analysis { self.engine = None; self.current = None; self.lines.clear(); - self.status = Status::Failed(match reason { - TerminationReason::Hung { .. } => { - tr("The engine hung and was stopped").into() - } - TerminationReason::Exited { status } - | TerminationReason::Quit { status } => match status { - Some(s) => trf("The engine exited ({s})", &[("s", &s)]), - None => tr("The engine exited").into(), - }, - }); + self.status = Status::Failed(termination_message(&reason)); return; } _ => {} @@ -284,6 +275,17 @@ impl Drop for Analysis { } } +/// Human-readable reason of an engine process ending. +pub fn termination_message(reason: &TerminationReason) -> String { + match reason { + TerminationReason::Hung { .. } => tr("The engine hung and was stopped").into(), + TerminationReason::Exited { status } | TerminationReason::Quit { status } => match status { + Some(s) => trf("The engine exited ({s})", &[("s", s)]), + None => tr("The engine exited").into(), + }, + } +} + fn side(c: Color) -> Side { match c { Color::White => Side::White, diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 127570d..c9e5518 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -38,6 +38,8 @@ pub struct App { library: Library, game: Option, analysis: Analysis, + /// The live engine was stopped for a whole-game analysis and resumes after it. + live_paused: bool, settings_ui: SettingsWindow, toast: Option<(String, f64)>, tx: Sender, @@ -52,7 +54,8 @@ pub struct App { /// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md): /// `CP_OPEN=` opens a game from the first database, `CP_PLY=` steps -/// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings. +/// along the main line, `CP_ANALYZE=1` starts the engine, `CP_SETTINGS=1` opens settings, +/// `CP_REVIEW=1` starts the whole-game analysis (`=dialog` only opens its dialog). #[derive(Default)] struct DebugStartup { open: Option, @@ -113,6 +116,7 @@ impl App { library, game: None, analysis: Analysis::new(), + live_paused: false, settings_ui: SettingsWindow::new(), toast: None, tx, @@ -191,6 +195,10 @@ impl App { if std::env::var("CP_ENGINE_PANEL").is_ok() { g.debug_open_engine_settings(); } + // CP_REVIEW=dialog opens the game-analysis dialog, any other value starts the analysis. + if let Ok(v) = std::env::var("CP_REVIEW") { + g.debug_review(&self.settings, ctx, v != "dialog"); + } } if self.debug.analyze { self.toggle_engine(ctx); @@ -385,6 +393,7 @@ 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 Some(src) = g.source { @@ -397,6 +406,7 @@ impl App { } fn toggle_engine(&mut self, ctx: &egui::Context) { + self.live_paused = false; if self.analysis.is_on() { self.analysis.stop(); return; @@ -557,6 +567,19 @@ impl eframe::App for App { GameAction::Quit => ctx.send_viewport_cmd(egui::ViewportCommand::Close), GameAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open, GameAction::Toast(m) => self.toast(&ctx, m), + GameAction::PauseLive => { + if self.analysis.is_on() { + self.analysis.stop(); + self.live_paused = true; + } + } + GameAction::ResumeLive => { + if std::mem::take(&mut self.live_paused) + && let Some(cfg) = self.settings.active_engine().cloned() + { + self.analysis.start(&cfg, &ctx); + } + } } } } else { diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 5bd8821..31ad808 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -14,6 +14,7 @@ use crate::analysis::{self, Analysis, PvLine, Status}; use crate::assets::Sound; use crate::board::{self, Arrow, BoardState, BoardView}; use crate::notation::{Notation, NotationCommand}; +use crate::review::{DialogAction, ReportAction, Review}; use crate::settings::Settings; /// Where an opened game came from (to return to the same library row). @@ -53,6 +54,14 @@ pub struct GameView { scroll_to_cursor: bool, show_diagnostics: bool, engine_settings_open: bool, + review: Review, + side_tab: SideTab, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum SideTab { + Notation, + Report, } pub enum GameAction { @@ -69,11 +78,16 @@ pub enum GameAction { OpenSettings, Quit, Toast(String), + /// A whole-game analysis started: pause the live engine (they would share the CPU). + PauseLive, + /// The whole-game analysis ended: resume the live engine if it was paused. + ResumeLive, } impl GameView { pub fn new(game: Game, source: Option, diagnostics: Vec) -> Self { let flipped = false; + let review = Review::new(&game); Self { game, source, @@ -85,6 +99,8 @@ impl GameView { scroll_to_cursor: true, show_diagnostics: false, engine_settings_open: false, + review, + side_tab: SideTab::Notation, } } @@ -141,7 +157,19 @@ impl GameView { input_enabled: bool, ) -> Vec { let mut actions = Vec::new(); - if input_enabled { + if self.review.poll() { + actions.push(GameAction::ResumeLive); + if let Some(e) = &self.review.error { + actions.push(GameAction::Toast(e.clone())); + } + } + self.review.refresh(&self.game); + if analysis.status == Status::Running + && let Some(e) = settings.active_engine() + { + self.review.note_live_speed(analysis.nps, e.threads); + } + if input_enabled && !self.review.dialog_open { self.keyboard(ui, &mut actions); } @@ -163,6 +191,13 @@ impl GameView { }); self.sync_analysis(analysis); + match self.review.dialog(ui.ctx(), settings) { + Some(DialogAction::Start) => self.start_review(settings, true, ui.ctx(), &mut actions), + Some(DialogAction::EngineSwitch) => actions.push(GameAction::EngineSwitch), + Some(DialogAction::OpenEngines) => actions.push(GameAction::OpenEngineSettings), + None => {} + } + if self.show_diagnostics { let mut open = true; egui::Window::new(tr("PGN compatibility")) @@ -196,6 +231,64 @@ impl GameView { actions } + fn start_review( + &mut self, + settings: &Settings, + full: bool, + ctx: &egui::Context, + actions: &mut Vec, + ) { + let Some(engine) = settings.active_engine().cloned() else { + self.review.dialog_open = true; + return; + }; + if self + .review + .start(&self.game, &engine, &settings.review, full, ctx) + { + actions.push(GameAction::PauseLive); + self.side_tab = SideTab::Report; + } else if let Some(e) = &self.review.error { + actions.push(GameAction::Toast(e.clone())); + } else { + actions.push(GameAction::Toast( + tr("Every position is already evaluated").into(), + )); + } + } + + /// Header button: start, progress with cancel, or show/hide the report. + fn review_button(&mut self, ui: &mut Ui, actions: &mut Vec) { + if let Some((done, total)) = self.review.progress() { + if crate::widgets::small_close_button(ui) + .on_hover_text(tr("Stop the game analysis")) + .clicked() + { + self.review.cancel(); + actions.push(GameAction::ResumeLive); + } + ui.add( + egui::ProgressBar::new(done as f32 / total.max(1) as f32) + .desired_width(90.0) + .text(format!("{done}/{total}")), + ); + ui.label(tr("Game analysis")); + } else if self.review.has_data() { + ui.toggle_value(&mut self.review.visible, tr("📈 Report")) + .on_hover_text(tr( + "Show or hide the evaluation graph and the report (Shift+A)", + )); + } else if ui + .button(tr("📈 Analyse game")) + .on_hover_text(tr( + "Evaluate every move: accuracy, inaccuracies, mistakes, blunders (Shift+A)", + )) + .clicked() + { + self.review.dialog_open = true; + } + } + /// Keeps the engine bound to the game cursor (never to the preview). Cheap when unchanged. fn sync_analysis(&self, analysis: &mut Analysis) { if !analysis.is_on() { @@ -247,6 +340,7 @@ impl GameView { { actions.push(GameAction::OpenSettings); } + self.review_button(ui, actions); let warnings = self .diagnostics .iter() @@ -330,6 +424,20 @@ impl GameView { } } } + if self.review.visible + && let Some(sq) = self + .review + .best_move(self.cursor) + .as_ref() + .and_then(move_squares) + { + arrows.push(Arrow { + from: sq.0, + to: sq.1, + color: Color32::from_rgba_unmultiplied(0x2a, 0x8a, 0xd8, 170), + weight: 0.9, + }); + } if settings.show_best_arrow && analysis.best().is_some() { for (i, line) in analysis.lines.iter().take(3).enumerate() { if let Some(sq) = line.moves.first().and_then(move_squares) { @@ -350,7 +458,16 @@ impl GameView { let show_bar = analysis.is_on(); let bar_w = if show_bar { 18.0 } else { 0.0 }; let gap = if show_bar { 8.0 } else { 0.0 }; - let side = (area.width() - bar_w - gap).min(area.height()).max(120.0); + let show_graph = self.review.visible && (self.review.has_data() || self.review.running()); + let graph_h = if show_graph { + (area.height() * 0.14).clamp(80.0, 130.0) + } else { + 0.0 + }; + let graph_gap = if show_graph { 8.0 } else { 0.0 }; + let side = (area.width() - bar_w - gap) + .min(area.height() - graph_h - graph_gap) + .max(120.0); let total = bar_w + gap + side; let left = area.left() + ((area.width() - total) / 2.0).max(0.0).floor(); let group = egui::Rect::from_min_size(egui::pos2(left, area.top()), vec2(total, side)); @@ -427,6 +544,21 @@ impl GameView { } }); }); + if show_graph { + let graph_rect = egui::Rect::from_min_size( + egui::pos2(left, area.top() + side + graph_gap), + vec2(total, graph_h), + ); + let target = ui + .scope_builder(egui::UiBuilder::new().max_rect(graph_rect), |ui| { + self.review + .graph(ui, graph_rect.size(), self.cursor, &self.game) + }) + .inner; + if let Some(id) = target { + self.goto(id); + } + } } fn side_panel( @@ -439,7 +571,40 @@ impl GameView { 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 { + 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.selectable_value(&mut self.side_tab, SideTab::Report, tr("Report")); + }); + ui.separator(); + } + if self.side_tab == SideTab::Report { + let action = egui::ScrollArea::vertical() + .auto_shrink(false) + .show(ui, |ui| self.review.report_ui(ui, &self.game)) + .inner; + match action { + Some(ReportAction::Goto(id)) => self.goto(id), + Some(ReportAction::Write) => { + let n = self.review.write_to_game(&mut self.game); + actions.push(GameAction::Toast(trf( + "Analysis written to the game: {n} marked moves (Ctrl+Z to undo)", + &[("n", &n)], + ))); + } + Some(ReportAction::Update) => { + self.start_review(settings, false, ui.ctx(), actions) + } + Some(ReportAction::Reanalyse) => self.review.dialog_open = true, + None => {} + } + return; + } egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { @@ -447,11 +612,28 @@ impl GameView { game: &self.game, cursor: self.cursor, scroll_to_cursor: self.scroll_to_cursor, + marks: self.review.visible.then_some(&self.review.marks), } .show(ui); if let Some(id) = resp.clicked { self.goto(id); } + if let Some(id) = resp.best + && let Some(mark) = self.review.marks.get(&id) + && let Some(root) = self.game.position(mark.base) + && !mark.best.is_empty() + { + self.cursor = mark.base; + self.scroll_to_cursor = false; + self.board.clear(); + self.preview = Some(Preview { + base: mark.base, + root: root.clone(), + moves: mark.best.clone(), + san: mark.best_san.clone(), + shown: 1, + }); + } if let Some((id, cmd)) = resp.context { let result = match cmd { NotationCommand::Promote => { @@ -545,7 +727,15 @@ impl GameView { Status::Failed(e) => { ui.label(RichText::new(e).small().color(ui.visuals().error_fg_color)); } - Status::Off => {} + Status::Off => { + if self.review.running() { + ui.label( + RichText::new(tr("paused: the game is being analysed")) + .small() + .weak(), + ); + } + } } }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -760,6 +950,14 @@ impl GameView { self.engine_settings_open = true; } + pub fn debug_review(&mut self, settings: &Settings, ctx: &egui::Context, start: bool) { + if start { + self.start_review(settings, false, ctx, &mut Vec::new()); + } else { + self.review.dialog_open = true; + } + } + pub fn debug_advance(&mut self, plies: usize) { for _ in 0..plies { match self.game.main_child(self.cursor) { @@ -838,6 +1036,9 @@ impl GameView { if i.consume_shortcut(&ctrl(Key::W)) { cmds.push("back"); } + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) { + cmds.push("review"); + } if i.modifiers.is_none() { for (key, cmd) in [ (Key::ArrowLeft, "back1"), @@ -886,6 +1087,13 @@ impl GameView { } "flip" => self.flipped = !self.flipped, "engine" => actions.push(GameAction::ToggleEngine), + "review" => { + if self.review.has_data() || self.review.running() { + self.review.visible = !self.review.visible; + } else { + self.review.dialog_open = true; + } + } "esc" => { if self.preview.is_some() { self.preview = None; @@ -1007,11 +1215,7 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec= 1024 { - trf("{n} GB", &[("n", &(e.hash_mb / 1024))]) - } else { - trf("{n} MB", &[("n", &e.hash_mb)]) - }); + ui.label(format_mb(e.hash_mb)); ui.end_row(); }); if settled { @@ -1021,14 +1225,22 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec bool { +pub(crate) fn index_slider(ui: &mut Ui, idx: &mut usize, len: usize) -> bool { let before = *idx; let r = ui.add(egui::Slider::new(idx, 0..=len.saturating_sub(1)).show_value(false)); r.drag_stopped() || (*idx != before && !r.dragged()) } +pub(crate) fn format_mb(mb: u32) -> String { + if mb >= 1024 { + trf("{n} GB", &[("n", &(mb / 1024))]) + } else { + trf("{n} MB", &[("n", &mb)]) + } +} + /// Hash sizes from 16 MB up to half of physical memory (powers of two). -fn hash_steps() -> Vec { +pub(crate) fn hash_steps() -> Vec { let total_mb = std::fs::read_to_string("/proc/meminfo") .ok() .and_then(|s| { diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 5c97dab..02206b9 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1039,6 +1039,338 @@ const ROWS: &[[&str; 6]] = &[ "Material insuficiente", "Materiale insufficiente", ], + // Whole-game analysis + [ + "Every position is already evaluated", + "Все позиции уже оценены", + "Toutes les positions sont déjà évaluées", + "Alle Stellungen sind bereits bewertet", + "Todas las posiciones ya están evaluadas", + "Tutte le posizioni sono già valutate", + ], + [ + "Stop the game analysis", + "Остановить анализ партии", + "Arrêter l'analyse de la partie", + "Partieanalyse abbrechen", + "Detener el análisis de la partida", + "Interrompi l'analisi della partita", + ], + [ + "Game analysis", + "Анализ партии", + "Analyse de la partie", + "Partieanalyse", + "Análisis de la partida", + "Analisi della partita", + ], + [ + "📈 Report", + "📈 Отчёт", + "📈 Rapport", + "📈 Bericht", + "📈 Informe", + "📈 Resoconto", + ], + [ + "Show or hide the evaluation graph and the report (Shift+A)", + "Показать или скрыть график оценки и отчёт (Shift+A)", + "Afficher ou masquer le graphique d'évaluation et le rapport (Maj+A)", + "Bewertungsgrafik und Bericht ein- oder ausblenden (Umschalt+A)", + "Mostrar u ocultar el gráfico de evaluación y el informe (Mayús+A)", + "Mostra o nascondi il grafico di valutazione e il resoconto (Maiusc+A)", + ], + [ + "📈 Analyse game", + "📈 Анализ партии", + "📈 Analyser la partie", + "📈 Partie analysieren", + "📈 Analizar partida", + "📈 Analizza partita", + ], + [ + "Evaluate every move: accuracy, inaccuracies, mistakes, blunders (Shift+A)", + "Оценить каждый ход: точность, неточности, ошибки, зевки (Shift+A)", + "Évaluer chaque coup : précision, imprécisions, erreurs, gaffes (Maj+A)", + "Jeden Zug bewerten: Genauigkeit, Ungenauigkeiten, Fehler, grobe Fehler (Umschalt+A)", + "Evaluar cada jugada: precisión, imprecisiones, errores, errores graves (Mayús+A)", + "Valuta ogni mossa: precisione, imprecisioni, errori, svarioni (Maiusc+A)", + ], + [ + "Notation", + "Нотация", + "Notation", + "Notation", + "Notación", + "Notazione", + ], + [ + "Report", + "Отчёт", + "Rapport", + "Bericht", + "Informe", + "Resoconto", + ], + [ + "paused: the game is being analysed", + "пауза: идёт анализ партии", + "en pause : analyse de la partie en cours", + "pausiert: Partie wird analysiert", + "en pausa: se está analizando la partida", + "in pausa: analisi della partita in corso", + ], + [ + "Analysis written to the game: {n} marked moves (Ctrl+Z to undo)", + "Анализ записан в партию: отмечено ходов — {n} (Ctrl+Z — отменить)", + "Analyse écrite dans la partie : {n} coups marqués (Ctrl+Z pour annuler)", + "Analyse in die Partie geschrieben: {n} markierte Züge (Strg+Z zum Rückgängigmachen)", + "Análisis escrito en la partida: {n} jugadas marcadas (Ctrl+Z para deshacer)", + "Analisi scritta nella partita: {n} mosse segnate (Ctrl+Z per annullare)", + ], + [ + "Best:", + "Лучше:", + "Meilleur :", + "Besser:", + "Mejor:", + "Meglio:", + ], + [ + "Show this line on the board", + "Показать этот вариант на доске", + "Afficher cette ligne sur l'échiquier", + "Diese Variante auf dem Brett zeigen", + "Mostrar esta línea en el tablero", + "Mostra questa linea sulla scacchiera", + ], + [ + "Opening", + "Дебют", + "Ouverture", + "Eröffnung", + "Apertura", + "Apertura", + ], + [ + "Middlegame", + "Миттельшпиль", + "Milieu de partie", + "Mittelspiel", + "Medio juego", + "Mediogioco", + ], + [ + "Endgame", + "Эндшпиль", + "Finale", + "Endspiel", + "Final", + "Finale", + ], + [ + "Start position", + "Начальная позиция", + "Position de départ", + "Ausgangsstellung", + "Posición inicial", + "Posizione iniziale", + ], + [ + "Evaluations from the PGN ([%eval])", + "Оценки из PGN ([%eval])", + "Évaluations issues du PGN ([%eval])", + "Bewertungen aus der PGN ([%eval])", + "Evaluaciones del PGN ([%eval])", + "Valutazioni dal PGN ([%eval])", + ], + [ + "Update", + "Дополнить", + "Compléter", + "Ergänzen", + "Completar", + "Completa", + ], + [ + "Write analysis to the game", + "Записать анализ в партию", + "Écrire l'analyse dans la partie", + "Analyse in die Partie schreiben", + "Escribir el análisis en la partida", + "Scrivi l'analisi nella partita", + ], + [ + "Adds evaluations, ?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", + "Добавляет в партию оценки, знаки ?!/?/??, комментарии и лучшие варианты (Ctrl+Z — отменить)", + "Ajoute à la partie les évaluations, les signes ?!/?/??, des commentaires et les meilleures lignes (Ctrl+Z pour annuler)", + "Fügt der Partie Bewertungen, ?!/?/??-Zeichen, Kommentare und bessere Varianten hinzu (Strg+Z zum Rückgängigmachen)", + "Añade a la partida evaluaciones, signos ?!/?/??, comentarios y mejores líneas (Ctrl+Z para deshacer)", + "Aggiunge alla partita valutazioni, segni ?!/?/??, commenti e linee migliori (Ctrl+Z per annullare)", + ], + [ + "Analyse again…", + "Проанализировать заново…", + "Analyser de nouveau…", + "Erneut analysieren…", + "Analizar de nuevo…", + "Analizza di nuovo…", + ], + [ + "Go to the next one", + "Перейти к следующей", + "Aller au suivant", + "Zum nächsten", + "Ir al siguiente", + "Vai al successivo", + ], + [ + "Average centipawn loss", + "Средняя потеря сантипешек", + "Perte moyenne en centipions", + "Durchschnittlicher Centibauernverlust", + "Pérdida media de centipeones", + "Perdita media in centipedoni", + ], + [ + "Accuracy", + "Точность", + "Précision", + "Genauigkeit", + "Precisión", + "Precisione", + ], + [ + "The engine evaluates every position of the main line. The game itself is not changed.", + "Движок оценит каждую позицию основной линии. Сама партия не изменится.", + "Le moteur évalue chaque position de la ligne principale. La partie elle-même n'est pas modifiée.", + "Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.", + "El motor evalúa cada posición de la línea principal. La partida en sí no cambia.", + "Il motore valuta ogni posizione della linea principale. La partita non viene modificata.", + ], + [ + "Quality", + "Качество", + "Qualité", + "Qualität", + "Calidad", + "Qualità", + ], + [ + "Analyse", + "Анализировать", + "Analyser", + "Analysieren", + "Analizar", + "Analizza", + ], + [ + "Add an engine first", + "Сначала добавьте движок", + "Ajoutez d'abord un moteur", + "Zuerst eine Engine hinzufügen", + "Primero añade un motor", + "Aggiungi prima un motore", + ], + [ + "Inaccuracy", + "Неточность", + "Imprécision", + "Ungenauigkeit", + "Imprecisión", + "Imprecisione", + ], + ["Mistake", "Ошибка", "Erreur", "Fehler", "Error", "Errore"], + [ + "Blunder", + "Зевок", + "Gaffe", + "Grober Fehler", + "Error grave", + "Svarione", + ], + [ + "Inaccuracies", + "Неточности", + "Imprécisions", + "Ungenauigkeiten", + "Imprecisiones", + "Imprecisioni", + ], + [ + "Mistakes", + "Ошибки", + "Erreurs", + "Fehler", + "Errores", + "Errori", + ], + [ + "Blunders", + "Зевки", + "Gaffes", + "Grobe Fehler", + "Errores graves", + "Svarioni", + ], + [ + "{judgement}. {best} was best.", + "{judgement}. Лучше было {best}.", + "{judgement}. {best} était meilleur.", + "{judgement}. Besser war {best}.", + "{judgement}. Era mejor {best}.", + "{judgement}. Era meglio {best}.", + ], + [ + "{engine} · {nodes} nodes per move", + "{engine} · {nodes} узлов на ход", + "{engine} · {nodes} nœuds par coup", + "{engine} · {nodes} Knoten pro Zug", + "{engine} · {nodes} nodos por jugada", + "{engine} · {nodes} nodi per mossa", + ], + [ + "Positions without evaluation: {n}", + "Позиций без оценки: {n}", + "Positions sans évaluation : {n}", + "Stellungen ohne Bewertung: {n}", + "Posiciones sin evaluación: {n}", + "Posizioni senza valutazione: {n}", + ], + [ + "{quality} · {nodes} nodes", + "{quality} · {nodes} узлов", + "{quality} · {nodes} nœuds", + "{quality} · {nodes} Knoten", + "{quality} · {nodes} nodos", + "{quality} · {nodes} nodi", + ], + [ + "{n} positions, about {time}", + "Позиций: {n}, примерно {time}", + "{n} positions, environ {time}", + "{n} Stellungen, etwa {time}", + "{n} posiciones, unos {time}", + "{n} posizioni, circa {time}", + ], + [ + "{n} min", + "{n} мин", + "{n} min", + "{n} Min.", + "{n} min", + "{n} min", + ], + ["Fast", "Быстро", "Rapide", "Schnell", "Rápido", "Veloce"], + ["Normal", "Обычно", "Normal", "Normal", "Normal", "Normale"], + [ + "Deep", + "Глубоко", + "Approfondi", + "Gründlich", + "Profundo", + "Approfondito", + ], ]; #[cfg(test)] @@ -1055,6 +1387,8 @@ mod tests { include_str!("game_view.rs"), include_str!("library.rs"), include_str!("notation.rs"), + include_str!("review.rs"), + include_str!("settings.rs"), include_str!("settings_ui.rs"), include_str!("widgets.rs"), ]; diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index 8fab2be..cd4fdcc 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -9,6 +9,8 @@ mod game_view; mod i18n; mod library; mod notation; +mod report; +mod review; mod settings; mod settings_ui; mod sound; diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 1a3932d..ef148e3 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -1,7 +1,10 @@ //! Move list: main line as a two-column table (Lichess style), comments and variations //! as full-width blocks between rows; nested variations inline in parentheses. +use std::collections::HashMap; + use crate::i18n::tr; +use crate::review::{Mark, judgement_color, judgement_name, judgement_symbol}; use chess_core::shakmaty::Color; use chess_core::{CommentPart, Game, Nag, NodeId, parse_comment}; use egui::{Align2, Color32, FontId, RichText, Sense, Stroke, Ui, vec2}; @@ -10,6 +13,8 @@ pub struct Notation<'a> { pub game: &'a Game, pub cursor: NodeId, pub scroll_to_cursor: bool, + /// Engine assessments of main-line moves (whole-game analysis), shown apart from NAGs. + pub marks: Option<&'a HashMap>, } /// Result of a frame of the notation panel. @@ -17,6 +22,8 @@ pub struct Notation<'a> { pub struct NotationResponse { pub clicked: Option, pub context: Option<(NodeId, NotationCommand)>, + /// The better line of this marked move was clicked. + pub best: Option, } #[derive(Clone, Copy, Debug)] @@ -63,9 +70,14 @@ impl Notation<'_> { } let after = comment_text(n.comments_after()); let vars = game.variations(node); - let interrupted = !after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty(); + let mark = self.marks.and_then(|m| m.get(&child)); + let interrupted = + !after.is_empty() || !vars.is_empty() || !n.unparsed().is_empty() || mark.is_some(); if interrupted || color == Color::Black { row.flush(ui, &self, &mut out); + if let Some(mark) = mark { + mark_block(ui, child, mark, &mut out); + } if !after.is_empty() { comment_block(ui, &after); } @@ -126,6 +138,9 @@ impl Row { Some(id) => { let resp = ui.interact(cell, ui.id().with(("mv", id.index())), Sense::click()); paint_move_cell(ui, cell, n.game, id, id == n.cursor, resp.hovered()); + if let Some(mark) = n.marks.and_then(|m| m.get(&id)) { + paint_badge(ui, cell, mark); + } handle_move_response(ui, &resp, n, id, out); } None => { @@ -205,6 +220,72 @@ fn paint_move_cell( ); } +/// Engine verdict at the right edge of a move cell: a filled pill, unlike the author's NAGs. +fn paint_badge(ui: &Ui, cell: egui::Rect, mark: &Mark) { + let color = judgement_color(mark.judgement); + let font = FontId::proportional(12.0); + let galley = ui.painter().layout_no_wrap( + judgement_symbol(mark.judgement).to_string(), + font, + Color32::WHITE, + ); + let size = vec2(galley.size().x + 10.0, 16.0); + let rect = egui::Rect::from_min_size( + egui::pos2(cell.right() - size.x - 6.0, cell.center().y - size.y / 2.0), + size, + ); + ui.painter().rect_filled(rect, 8.0, color); + ui.painter() + .galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE); +} + +/// "Mistake. Best: 23…Nf6 24.Nd5 …" under a marked main-line move; the line opens as a preview. +fn mark_block(ui: &mut Ui, id: NodeId, mark: &Mark, out: &mut NotationResponse) { + let color = judgement_color(mark.judgement); + egui::Frame::new() + .fill(ui.visuals().extreme_bg_color) + .inner_margin(egui::Margin { + left: 10, + right: 10, + top: 3, + bottom: 3, + }) + .stroke(Stroke::new(1.0, color.gamma_multiply(0.6))) + .show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing.x = 5.0; + ui.label( + RichText::new(format!("{}.", judgement_name(mark.judgement))) + .color(color) + .strong(), + ); + let Some(first) = &mark.best_label else { + return; + }; + ui.label(RichText::new(tr("Best:")).weak()); + let mut line = first.clone(); + for san in mark.best_san.iter().skip(1).take(4) { + line.push(' '); + line.push_str(san); + } + if mark.best_san.len() > 5 { + line.push_str(" …"); + } + if ui + .add( + egui::Button::new(RichText::new(line).size(14.5)) + .frame_when_inactive(false), + ) + .on_hover_text(tr("Show this line on the board")) + .clicked() + { + out.best = Some(id); + } + }); + }); +} + /// Move-assessment glyph (`!`, `?`, …) with its color, plus position assessments. fn move_glyph(nags: &[Nag]) -> (String, Option) { let mut s = String::new(); diff --git a/apps/desktop/src/report.rs b/apps/desktop/src/report.rs new file mode 100644 index 0000000..ae3c180 --- /dev/null +++ b/apps/desktop/src/report.rs @@ -0,0 +1,569 @@ +//! Game review metrics: win percentage, move and game accuracy, inaccuracy/mistake/blunder +//! judgements, average centipawn loss and game phases. +//! +//! The method follows Lichess (lila `WinPercent`, `AccuracyPercent`, `Advice`, and the +//! scalachess `Divider`, see ); this is an independent +//! reimplementation of the published formulas. + +use chess_core::shakmaty::{Bitboard, Chess, Color, Position, Rank}; +use serde::{Deserialize, Serialize}; + +/// Engine evaluation from White's point of view. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub enum Eval { + Cp(i32), + /// Forced mate; `moves == 0` in a checkmate position. + Mate { + white: bool, + moves: u32, + }, +} + +/// Centipawn ceiling: larger advantages (and mates) count as this much. +const CP_CEILING: i32 = 1000; + +impl Eval { + pub fn from_white_eval(e: uci::WhiteEval) -> Eval { + match e { + uci::WhiteEval::Cp(cp) => Eval::Cp(cp), + uci::WhiteEval::Mate { winner, moves } => Eval::Mate { + white: winner == uci::Side::White, + moves, + }, + } + } + + /// Centipawns for `side`, mates folded into the ceiling. + fn cp_for(self, side: Color) -> i32 { + let white = match self { + Eval::Cp(cp) => cp.clamp(-CP_CEILING, CP_CEILING), + Eval::Mate { white: true, .. } => CP_CEILING, + Eval::Mate { white: false, .. } => -CP_CEILING, + }; + if side == Color::White { white } else { -white } + } + + /// `Some(true)` if `side` has a forced mate, `Some(false)` if it is being mated. + fn mate_for(self, side: Color) -> Option { + match self { + Eval::Cp(_) => None, + Eval::Mate { white, .. } => Some(white == (side == Color::White)), + } + } + + /// Chance of winning for `side`, 0..100. + pub fn win_percent(self, side: Color) -> f64 { + 50.0 + 50.0 * winning_chances(self.cp_for(side)) + } + + /// "+0.35", "−1.20", "#3", "#-2", "1-0". + pub fn format(self) -> String { + match self { + Eval::Cp(cp) => format!("{:+.2}", f64::from(cp) / 100.0), + Eval::Mate { white, moves: 0 } => if white { "1-0" } else { "0-1" }.into(), + Eval::Mate { white: true, moves } => format!("#{moves}"), + Eval::Mate { + white: false, + moves, + } => format!("#-{moves}"), + } + } + + /// Value for a PGN `[%eval …]` command (pawns or `#n`). + pub fn pgn(self) -> String { + match self { + Eval::Cp(cp) => format!("{:.2}", f64::from(cp) / 100.0), + Eval::Mate { white, moves } => { + format!("#{}{moves}", if white { "" } else { "-" }) + } + } + } + + /// Parses a PGN `[%eval …]` payload ("0.35", "-1.2", "#3", "#-2"). + pub fn parse_pgn(s: &str) -> Option { + let s = s.split([',', ' ']).next()?.trim(); + if let Some(m) = s.strip_prefix('#') { + let n: i32 = m.parse().ok()?; + return Some(Eval::Mate { + white: !m.starts_with('-'), + moves: n.unsigned_abs(), + }); + } + let pawns: f64 = s.parse().ok()?; + pawns + .is_finite() + .then(|| Eval::Cp((pawns * 100.0).round().clamp(-100_000.0, 100_000.0) as i32)) + } +} + +/// Lichess winning chances, −1..1. +fn winning_chances(cp: i32) -> f64 { + 2.0 / (1.0 + (-0.003_682_08 * f64::from(cp)).exp()) - 1.0 +} + +/// Accuracy of a move given the mover's win percentage before and after it, 0..100. +fn move_accuracy(before: f64, after: f64) -> f64 { + if after >= before { + return 100.0; + } + let raw = 103.166_810_071_164_9 * (-0.043_544_153_867_539_51 * (before - after)).exp() + - 3.166_924_740_191_411; + // +1: uncertainty bonus for imperfect analysis, as on Lichess. + (raw + 1.0).clamp(0.0, 100.0) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Judgement { + Inaccuracy, + Mistake, + Blunder, +} + +/// Judgement of a move from the evaluations before and after it. +fn judge(before: Eval, after: Eval, mover: Color) -> Option { + use Judgement::*; + let (mb, ma) = (before.mate_for(mover), after.mate_for(mover)); + if ma == Some(false) && mb != Some(false) { + // The move allows a forced mate. + let cp = before.cp_for(mover); + return Some(if cp < -999 { + Inaccuracy + } else if cp < -700 { + Mistake + } else { + Blunder + }); + } + if mb == Some(true) && ma != Some(true) { + // A forced mate was let go. + let cp = after.cp_for(mover); + return Some(if cp > 999 { + Inaccuracy + } else if cp > 700 { + Mistake + } else { + Blunder + }); + } + if mb.is_some() || ma.is_some() { + return None; + } + let delta = winning_chances(before.cp_for(mover)) - winning_chances(after.cp_for(mover)); + if delta >= 0.3 { + Some(Blunder) + } else if delta >= 0.2 { + Some(Mistake) + } else if delta >= 0.1 { + Some(Inaccuracy) + } else { + None + } +} + +/// Game phases as indices of the first position of each phase. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Phases { + pub middlegame: Option, + pub endgame: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Phase { + Opening, + Middlegame, + Endgame, +} + +impl Phases { + /// Splits a sequence of positions: the middlegame starts once few pieces are left or + /// a back rank is sparse; the endgame once at most six queens, rooks and minor pieces remain. + pub fn divide(positions: &[Chess]) -> Phases { + let majors_minors = |p: &Chess| { + let b = p.board(); + (b.knights() | b.bishops() | b.rooks() | b.queens()).count() + }; + let backrank_sparse = |p: &Chess| { + let b = p.board(); + (b.by_color(Color::White) & Bitboard::from_rank(Rank::First)).count() < 4 + || (b.by_color(Color::Black) & Bitboard::from_rank(Rank::Eighth)).count() < 4 + }; + let middlegame = positions + .iter() + .position(|p| majors_minors(p) <= 10 || backrank_sparse(p)); + let endgame = middlegame.and_then(|m| { + positions[m..] + .iter() + .position(|p| majors_minors(p) <= 6) + .map(|i| i + m) + }); + Phases { + middlegame, + endgame, + } + } + + pub fn of(self, position: usize) -> Phase { + if self.endgame.is_some_and(|e| position >= e) { + Phase::Endgame + } else if self.middlegame.is_some_and(|m| position >= m) { + Phase::Middlegame + } else { + Phase::Opening + } + } +} + +/// A move of the analysed line. +#[derive(Clone, Copy, Debug)] +pub struct Ply { + pub mover: Color, + /// Teaching null move `--`: not graded. + pub null: bool, + /// The move played equals the engine's best move (never judged as an error). + pub best: bool, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SideStats { + pub inaccuracies: u32, + pub mistakes: u32, + pub blunders: u32, + /// Average centipawn loss. + pub acpl: Option, + pub accuracy: Option, + /// Opening, middlegame, endgame. + pub phase_accuracy: [Option; 3], +} + +#[derive(Clone, Debug, Default)] +pub struct Report { + /// Per ply of the line. + pub judgements: Vec>, + pub white: SideStats, + pub black: SideStats, + pub phases: Phases, + /// All positions are evaluated. + pub complete: bool, +} + +impl Report { + pub fn side(&self, c: Color) -> &SideStats { + match c { + Color::White => &self.white, + Color::Black => &self.black, + } + } + + /// `evals[i]` belongs to the position before ply `i`; `evals.len() == plies.len() + 1`. + pub fn build(evals: &[Option], plies: &[Ply], phases: Phases) -> Report { + let n = plies.len().min(evals.len().saturating_sub(1)); + let mut report = Report { + judgements: vec![None; plies.len()], + phases, + complete: evals.iter().take(n + 1).all(Option::is_some), + ..Report::default() + }; + let mut losses: [Vec; 2] = [Vec::new(), Vec::new()]; + for i in 0..n { + let ply = plies[i]; + let (Some(before), Some(after)) = (evals[i], evals[i + 1]) else { + continue; + }; + if ply.null { + continue; + } + let j = if ply.best { + None + } else { + judge(before, after, ply.mover) + }; + report.judgements[i] = j; + let stats = match ply.mover { + Color::White => &mut report.white, + Color::Black => &mut report.black, + }; + match j { + Some(Judgement::Inaccuracy) => stats.inaccuracies += 1, + Some(Judgement::Mistake) => stats.mistakes += 1, + Some(Judgement::Blunder) => stats.blunders += 1, + None => {} + } + let loss = (before.cp_for(ply.mover) - after.cp_for(ply.mover)).max(0); + losses[ply.mover as usize].push(loss); + } + for color in [Color::White, Color::Black] { + let l = &losses[color as usize]; + if !l.is_empty() { + let avg = l.iter().map(|x| i64::from(*x)).sum::() as f64 / l.len() as f64; + let stats = match color { + Color::White => &mut report.white, + Color::Black => &mut report.black, + }; + stats.acpl = Some(avg.round() as u32); + } + } + if report.complete && n > 0 { + let wp: Vec = evals[..=n] + .iter() + .map(|e| e.map_or(50.0, |e| e.win_percent(Color::White))) + .collect(); + report.fill_accuracy(&wp, &plies[..n]); + } + report + } + + /// Lichess game accuracy: mean of the volatility-weighted mean and the harmonic mean + /// of move accuracies. + fn fill_accuracy(&mut self, wp: &[f64], plies: &[Ply]) { + let window = (wp.len() / 10).clamp(2, 8).min(wp.len()); + let mut windows: Vec<&[f64]> = vec![&wp[..window]; window.saturating_sub(2)]; + windows.extend(wp.windows(window)); + let weights: Vec = windows + .iter() + .map(|w| std_dev(w).clamp(0.5, 12.0)) + .collect(); + // (color, phase, accuracy, weight) + let mut moves = Vec::new(); + for (i, ply) in plies.iter().enumerate() { + if ply.null { + continue; + } + let (before, after) = (wp[i], wp[i + 1]); + let (before, after) = match ply.mover { + Color::White => (before, after), + Color::Black => (100.0 - before, 100.0 - after), + }; + let weight = weights.get(i).copied().unwrap_or(0.5); + moves.push(( + ply.mover, + self.phases.of(i), + move_accuracy(before, after), + weight, + )); + } + for color in [Color::White, Color::Black] { + let all: Vec<(f64, f64)> = moves + .iter() + .filter(|m| m.0 == color) + .map(|m| (m.2, m.3)) + .collect(); + let phase = |p: Phase| { + let v: Vec<(f64, f64)> = moves + .iter() + .filter(|m| m.0 == color && m.1 == p) + .map(|m| (m.2, m.3)) + .collect(); + // Too few moves in a phase say nothing about it. + if v.len() >= 3 { mixed_mean(&v) } else { None } + }; + let stats = match color { + Color::White => &mut self.white, + Color::Black => &mut self.black, + }; + stats.accuracy = mixed_mean(&all); + stats.phase_accuracy = [ + phase(Phase::Opening), + phase(Phase::Middlegame), + phase(Phase::Endgame), + ]; + } + } +} + +fn std_dev(xs: &[f64]) -> f64 { + if xs.is_empty() { + return 0.0; + } + let mean = xs.iter().sum::() / xs.len() as f64; + (xs.iter().map(|x| (x - mean).powi(2)).sum::() / xs.len() as f64).sqrt() +} + +/// Average of the weighted mean and the harmonic mean of `(accuracy, weight)`. +fn mixed_mean(v: &[(f64, f64)]) -> Option { + if v.is_empty() { + return None; + } + let wsum: f64 = v.iter().map(|x| x.1).sum(); + let weighted = v.iter().map(|x| x.0 * x.1).sum::() / wsum.max(f64::EPSILON); + let harmonic = v.len() as f64 / v.iter().map(|x| 1.0 / x.0.max(1.0)).sum::(); + Some((weighted + harmonic) / 2.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ply(mover: Color) -> Ply { + Ply { + mover, + null: false, + best: false, + } + } + + fn alternating(n: usize) -> Vec { + (0..n) + .map(|i| { + ply(if i % 2 == 0 { + Color::White + } else { + Color::Black + }) + }) + .collect() + } + + #[test] + fn win_percent_matches_lichess_curve() { + assert!((Eval::Cp(0).win_percent(Color::White) - 50.0).abs() < 1e-9); + let w = Eval::Cp(100).win_percent(Color::White); + assert!((w - 59.1).abs() < 0.1, "{w}"); + assert!((Eval::Cp(100).win_percent(Color::Black) - (100.0 - w)).abs() < 1e-9); + // Mates count as the centipawn ceiling. + let m = Eval::Mate { + white: true, + moves: 3, + }; + assert_eq!( + m.win_percent(Color::White), + Eval::Cp(5000).win_percent(Color::White) + ); + } + + #[test] + fn move_accuracy_bounds() { + assert_eq!(move_accuracy(50.0, 60.0), 100.0); + assert_eq!(move_accuracy(50.0, 50.0), 100.0); + let small = move_accuracy(60.0, 55.0); + let big = move_accuracy(60.0, 20.0); + assert!(small > 75.0 && small < 100.0, "{small}"); + assert!(big < 20.0, "{big}"); + assert_eq!(move_accuracy(100.0, 0.0), 0.0); + } + + #[test] + fn judgements_follow_win_chance_drop() { + let w = Color::White; + assert_eq!(judge(Eval::Cp(0), Eval::Cp(-30), w), None); + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(-60), w), + Some(Judgement::Inaccuracy) + ); + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(-150), w), + Some(Judgement::Mistake) + ); + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(-500), w), + Some(Judgement::Blunder) + ); + // Black's point of view: White's eval going up is Black's loss. + assert_eq!( + judge(Eval::Cp(0), Eval::Cp(500), Color::Black), + Some(Judgement::Blunder) + ); + // Already winning by a lot: losing a pawn changes nothing. + assert_eq!(judge(Eval::Cp(900), Eval::Cp(800), w), None); + let mated = Eval::Mate { + white: false, + moves: 4, + }; + let mating = Eval::Mate { + white: true, + moves: 4, + }; + assert_eq!(judge(Eval::Cp(0), mated, w), Some(Judgement::Blunder)); + assert_eq!( + judge(Eval::Cp(-1200), mated, w), + Some(Judgement::Inaccuracy) + ); + assert_eq!(judge(mating, Eval::Cp(300), w), Some(Judgement::Blunder)); + assert_eq!( + judge(mating, Eval::Cp(1500), w), + Some(Judgement::Inaccuracy) + ); + assert_eq!(judge(mating, mating, w), None); + assert_eq!(judge(mated, mated, w), None); + assert_eq!(judge(Eval::Cp(0), mating, w), None); + } + + #[test] + fn report_counts_and_accuracy() { + // White blunders on ply 2; everything else is quiet. + let cps = [20, 25, 20, -400, -390, -400, -395]; + let evals: Vec> = cps.iter().map(|c| Some(Eval::Cp(*c))).collect(); + let plies = alternating(cps.len() - 1); + let r = Report::build(&evals, &plies, Phases::default()); + assert!(r.complete); + assert_eq!(r.judgements[2], Some(Judgement::Blunder)); + assert_eq!(r.white.blunders, 1); + assert_eq!( + r.black.blunders + r.black.mistakes + r.black.inaccuracies, + 0 + ); + let (wa, ba) = (r.white.accuracy.expect("w"), r.black.accuracy.expect("b")); + assert!(wa < ba, "white {wa} black {ba}"); + assert!(ba > 90.0); + assert!(r.white.acpl.expect("acpl") > r.black.acpl.expect("acpl")); + } + + #[test] + fn partial_and_special_plies() { + let evals = vec![Some(Eval::Cp(0)), Some(Eval::Cp(-500)), None, None]; + let mut plies = alternating(3); + let r = Report::build(&evals, &plies, Phases::default()); + assert!(!r.complete); + assert_eq!(r.white.blunders, 1); + assert_eq!(r.white.accuracy, None); + // The engine's own best move is never an error; null moves are not graded. + plies[0].best = true; + let r = Report::build(&evals, &plies, Phases::default()); + assert_eq!(r.white.blunders, 0); + plies[0].best = false; + plies[0].null = true; + let r = Report::build(&evals, &plies, Phases::default()); + assert_eq!(r.white.blunders, 0); + assert_eq!(r.white.acpl, None); + } + + #[test] + fn pgn_eval_roundtrip() { + for e in [ + Eval::Cp(35), + Eval::Cp(-120), + Eval::Mate { + white: true, + moves: 3, + }, + Eval::Mate { + white: false, + moves: 2, + }, + ] { + assert_eq!(Eval::parse_pgn(&e.pgn()), Some(e)); + } + assert_eq!(Eval::parse_pgn("0.17,22"), Some(Eval::Cp(17))); + assert_eq!(Eval::parse_pgn("abc"), None); + } + + #[test] + fn phases_of_a_real_game() { + // The Opera Game: queens and rooks stay until the very end, so no endgame. + let game = chess_core::parse_str( + "1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 7. Qb3 Qe7 \ + 8. Nc3 c6 9. Bg5 b5 10. Nxb5 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 13. Rxd7 Rxd7 \ + 14. Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+ Nxb8 17. Rd8# 1-0", + ) + .game; + let positions: Vec = std::iter::once(chess_core::NodeId::ROOT) + .chain(game.mainline()) + .filter_map(|n| game.position(n).cloned()) + .collect(); + assert_eq!(positions.len(), 34); + let p = Phases::divide(&positions); + let mid = p.middlegame.expect("middlegame"); + assert!(mid > 4 && mid < 25, "{mid}"); + assert_eq!(p.of(0), Phase::Opening); + assert_eq!(p.of(mid), Phase::Middlegame); + } +} diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs new file mode 100644 index 0000000..89bea9c --- /dev/null +++ b/apps/desktop/src/review.rs @@ -0,0 +1,1349 @@ +//! Whole-game analysis: a background engine job over the main line, cached results, +//! the evaluation graph under the board, the report tab and the launch dialog. +//! +//! The job uses its own engine process and never touches the game; writing the results +//! into the game is a separate, undoable action ([`Review::write_to_game`]). + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::{Duration, Instant}; + +use chess_core::shakmaty::san::SanPlus; +use chess_core::shakmaty::uci::UciMove; +use chess_core::shakmaty::{Chess, Color, Move, Position}; +use chess_core::{Annotation, CommentPart, Game, Nag, NodeId, parse_comment}; +use egui::{Color32, RichText, Sense, Stroke, Ui, pos2, vec2}; +use serde::{Deserialize, Serialize}; +use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; + +use crate::i18n::{tr, trf}; +use crate::report::{Eval, Judgement, Phases, Ply, Report}; +use crate::settings::{EngineConfig, REVIEW_QUALITY, ReviewSettings, Settings}; + +/// Engine result for one position of the main line. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct PosEval { + pub eval: Eval, + /// Principal variation in UCI; the first move is the engine's best move. + #[serde(default)] + pub pv: Vec, + #[serde(default)] + pub depth: u32, +} + +/// Where the evaluations came from. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +pub struct ReviewMeta { + pub engine: String, + /// Nodes per position; 0 = read from `[%eval]` comments of the PGN. + pub nodes: u64, +} + +#[derive(Serialize, Deserialize)] +struct CacheFile { + version: u32, + meta: ReviewMeta, + evals: Vec<(String, PosEval)>, +} + +const CACHE_VERSION: u32 = 1; +/// A node-limited search should never take this long; stop it if it does. +const SEARCH_GUARD: Duration = Duration::from_secs(300); + +/// An engine assessment of a main-line move, shown over the notation. +#[derive(Clone, Debug)] +pub struct Mark { + pub judgement: Judgement, + /// Node before the move (where the better line starts). + pub base: NodeId, + pub best: Vec, + pub best_san: Vec, + /// "23…Nf6". + pub best_label: Option, +} + +pub enum ReportAction { + Goto(NodeId), + Write, + Update, + Reanalyse, +} + +pub enum DialogAction { + Start, + EngineSwitch, + OpenEngines, +} + +struct Target { + key: String, + pos: EnginePosition, + turn: Side, +} + +enum JobMsg { + Engine(String), + Eval { + key: String, + eval: PosEval, + nps: u64, + }, + Done, + Failed(String), +} + +struct Job { + rx: Receiver, + cancel: Arc, + total: usize, + done: usize, + threads: u32, +} + +impl Drop for Job { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Relaxed); + } +} + +pub struct Review { + evals: HashMap, + pub meta: Option, + job: Option, + pub error: Option, + /// Graph and report tab are shown. + pub visible: bool, + pub dialog_open: bool, + /// Measured engine speed per thread, for time estimates. + nps_per_thread: Option, + built_rev: Option, + dirty: bool, + /// Root and main-line nodes: the analysed positions. + line: Vec, + keys: Vec, + /// Side making each move of the line. + movers: Vec, + /// Evaluation per position (engine result or a terminal position). + values: Vec>, + pub report: Report, + pub marks: HashMap, + /// Report tab: index of the last visited error per side and kind. + cycle: HashMap<(Color, Judgement), usize>, +} + +impl Review { + pub fn new(game: &Game) -> Self { + let mut r = Review { + evals: HashMap::new(), + meta: None, + job: None, + error: None, + visible: false, + dialog_open: false, + nps_per_thread: None, + built_rev: None, + dirty: false, + line: Vec::new(), + keys: Vec::new(), + movers: Vec::new(), + values: Vec::new(), + report: Report::default(), + marks: HashMap::new(), + cycle: HashMap::new(), + }; + r.rebuild(game); + if r.load_cache() || r.load_pgn_evals(game) { + r.rebuild(game); + r.visible = true; + } + r + } + + pub fn has_data(&self) -> bool { + !self.evals.is_empty() + } + + pub fn running(&self) -> bool { + self.job.is_some() + } + + pub fn progress(&self) -> Option<(usize, usize)> { + self.job.as_ref().map(|j| (j.done, j.total)) + } + + /// Positions of the current main line without an evaluation. + pub fn missing(&self) -> usize { + self.values.iter().filter(|v| v.is_none()).count() + } + + /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. + pub fn refresh(&mut self, game: &Game) { + if self.dirty || self.built_rev != Some(game.revision()) { + self.rebuild(game); + } + } + + fn rebuild(&mut self, game: &Game) { + self.line = std::iter::once(NodeId::ROOT) + .chain(game.mainline()) + .collect(); + let positions: Vec = self + .line + .iter() + .filter_map(|id| game.position(*id).cloned()) + .collect(); + self.keys = self + .line + .iter() + .map(|id| position_key(game, *id).map(|k| k.0).unwrap_or_default()) + .collect(); + self.values = (0..self.line.len()) + .map(|i| { + self.evals + .get(&self.keys[i]) + .map(|e| e.eval) + .or_else(|| positions.get(i).and_then(terminal_eval)) + }) + .collect(); + let mut plies = Vec::with_capacity(self.line.len().saturating_sub(1)); + for i in 1..self.line.len() { + let mv = game.game_move(self.line[i]); + let best = self.evals.get(&self.keys[i - 1]).and_then(|e| e.pv.first()); + plies.push(Ply { + mover: positions.get(i - 1).map_or(Color::White, |p| p.turn()), + null: mv.is_none_or(|m| m.is_null()), + best: best.is_some() && mv.and_then(|m| m.uci()).as_ref() == best, + }); + } + self.movers = plies.iter().map(|p| p.mover).collect(); + self.report = Report::build(&self.values, &plies, Phases::divide(&positions)); + self.marks.clear(); + for (i, j) in self.report.judgements.iter().enumerate() { + let Some(judgement) = *j else { continue }; + let (base, node) = (self.line[i], self.line[i + 1]); + let (best, best_san) = match (self.evals.get(&self.keys[i]), positions.get(i)) { + (Some(e), Some(root)) => parse_pv(root, &e.pv), + _ => (Vec::new(), Vec::new()), + }; + let best_label = best_san.first().and_then(|san| { + let (num, color) = game.move_number(node)?; + Some(match color { + Color::White => format!("{num}.{san}"), + Color::Black => format!("{num}…{san}"), + }) + }); + self.marks.insert( + node, + Mark { + judgement, + base, + best, + best_san, + best_label, + }, + ); + } + self.built_rev = Some(game.revision()); + self.dirty = false; + } + + /// Starts the engine job. `full` discards earlier results; otherwise only positions + /// without an evaluation are analysed. Returns false if there is nothing to do. + pub fn start( + &mut self, + game: &Game, + engine: &EngineConfig, + rs: &ReviewSettings, + full: bool, + ctx: &egui::Context, + ) -> bool { + self.job = None; + self.error = None; + if full { + self.evals.clear(); + self.dirty = true; + } + self.meta = Some(ReviewMeta { + engine: engine.name.clone(), + nodes: rs.nodes(), + }); + self.rebuild(game); + let targets: Vec = (0..self.line.len()) + .filter(|i| self.values[*i].is_none()) + .filter_map(|i| { + let (key, pos) = position_key(game, self.line[i])?; + let turn = match game.position(self.line[i])?.turn() { + Color::White => Side::White, + Color::Black => Side::Black, + }; + Some(Target { key, pos, turn }) + }) + .collect(); + if targets.is_empty() { + return false; + } + let (tx, rx) = channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let total = targets.len(); + let (path, threads, hash, nodes) = ( + engine.path.clone(), + rs.threads.max(1), + rs.hash_mb, + rs.nodes(), + ); + let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone()); + let spawned = std::thread::Builder::new() + .name("game-review".into()) + .spawn(move || { + let msg = match run_job(path, threads, hash, nodes, targets, &tx, &cancel_w, &ctx_w) + { + Ok(()) => JobMsg::Done, + Err(e) => JobMsg::Failed(e), + }; + let _ = tx.send(msg); + ctx_w.request_repaint(); + }); + if let Err(e) = spawned { + self.error = Some(e.to_string()); + return false; + } + self.job = Some(Job { + rx, + cancel, + total, + done: 0, + threads, + }); + self.visible = true; + true + } + + pub fn cancel(&mut self) { + if self.job.take().is_some() { + self.save_cache(); + } + } + + /// Collects job results; returns true when the job has just ended. + pub fn poll(&mut self) -> bool { + let Some(job) = &mut self.job else { + return false; + }; + let mut ended = false; + while let Ok(msg) = job.rx.try_recv() { + match msg { + JobMsg::Engine(name) => { + if let Some(m) = &mut self.meta { + m.engine = name; + } + } + JobMsg::Eval { key, eval, nps } => { + job.done += 1; + if nps > 0 { + self.nps_per_thread = Some(nps as f64 / f64::from(job.threads)); + } + self.evals.insert(key, eval); + self.dirty = true; + } + JobMsg::Done => ended = true, + JobMsg::Failed(e) => { + self.error = Some(e); + ended = true; + } + } + } + if ended { + self.job = None; + self.save_cache(); + } + ended + } + + /// Engine speed per thread for estimates: measured here, else from the live engine. + pub fn note_live_speed(&mut self, nps: u64, threads: u32) { + if self.nps_per_thread.is_none() && nps > 0 { + self.nps_per_thread = Some(nps as f64 / f64::from(threads.max(1))); + } + } + + /// The engine's better move for a marked node (an arrow on the board). + pub fn best_move(&self, node: NodeId) -> Option { + self.marks.get(&node).and_then(|m| m.best.first().copied()) + } + + // ----- cache ----------------------------------------------------------------- + + fn cache_path(&self) -> Option { + let mut h: u64 = 0xcbf2_9ce4_8422_2325; + for k in &self.keys { + for b in k.bytes().chain(std::iter::once(b'\n')) { + h ^= u64::from(b); + h = h.wrapping_mul(0x0100_0000_01b3); + } + } + Some( + Settings::cache_dir()? + .join("analysis") + .join(format!("{h:016x}.json")), + ) + } + + fn save_cache(&self) { + let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else { + return; + }; + if self.evals.is_empty() { + return; + } + let Some(path) = self.cache_path() else { + return; + }; + let file = CacheFile { + version: CACHE_VERSION, + meta, + evals: self + .evals + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect(), + }; + match serde_json::to_vec(&file) { + Ok(bytes) => { + if let Err(e) = crate::settings::write_atomic(&path, &bytes) { + eprintln!("review cache: {}: {e}", path.display()); + } + } + Err(e) => eprintln!("review cache: {e}"), + } + } + + fn load_cache(&mut self) -> bool { + let Some(bytes) = self.cache_path().and_then(|p| std::fs::read(p).ok()) else { + return false; + }; + let Ok(file) = serde_json::from_slice::(&bytes) else { + return false; + }; + if file.version != CACHE_VERSION || file.evals.is_empty() { + return false; + } + self.meta = Some(file.meta); + self.evals = file.evals.into_iter().collect(); + true + } + + /// Uses `[%eval]` comments (Lichess exports, or our own written analysis) when every + /// main-line move has one. + fn load_pgn_evals(&mut self, game: &Game) -> bool { + let mut found = Vec::new(); + for (i, id) in self.line.iter().enumerate().skip(1) { + let Some(node) = game.node(*id) else { + return false; + }; + let e = node + .comments_after() + .iter() + .flat_map(|c| parse_comment(c)) + .find_map(|p| match p { + CommentPart::Annotation(Annotation::Other { name, payload }) + if name == "eval" => + { + Eval::parse_pgn(&payload) + } + _ => None, + }); + match e { + Some(e) => found.push((i, e)), + None if self.values[i].is_some() => {} + None => return false, + } + } + let Some(&(_, first)) = found.first() else { + return false; + }; + // The start position carries no comment: Lichess assumes +0.15 for the initial one. + let root = if game.start().is_standard() { + Eval::Cp(15) + } else { + first + }; + found.insert(0, (0, root)); + for (i, eval) in found { + self.evals.insert( + self.keys[i].clone(), + PosEval { + eval, + pv: Vec::new(), + depth: 0, + }, + ); + } + self.meta = Some(ReviewMeta { + engine: "PGN".into(), + nodes: 0, + }); + true + } + + // ----- writing into the game ------------------------------------------------- + + /// Adds `[%eval]` to every main-line move and, for errors, a move-assessment NAG + /// (unless the author gave one), a comment and the better line as a variation. + /// One undo step. Returns the number of annotated errors. + pub fn write_to_game(&self, game: &mut Game) -> usize { + game.edit_group(|g| { + let mut errors = 0; + for i in 1..self.line.len() { + let id = self.line[i]; + let Some(node) = g.node(id) else { continue }; + let mut nags = node.nags().to_vec(); + let mut comments: Vec = node + .comments_after() + .iter() + .map(|c| strip_eval(c)) + .filter(|c| !c.trim().is_empty()) + .collect(); + if let Some(e) = self.values[i] + && !matches!(e, Eval::Mate { moves: 0, .. }) + { + comments.insert(0, format!("[%eval {}]", e.pgn())); + } + if let Some(mark) = self.marks.get(&id) { + errors += 1; + if !nags.iter().any(|n| n.is_move_assessment()) { + nags.push(match mark.judgement { + Judgement::Inaccuracy => Nag::DUBIOUS_MOVE, + Judgement::Mistake => Nag::MISTAKE, + Judgement::Blunder => Nag::BLUNDER, + }); + } + let name = judgement_name(mark.judgement); + let text = match &mark.best_label { + Some(best) => trf( + "{judgement}. {best} was best.", + &[("judgement", &name), ("best", best)], + ), + None => format!("{name}."), + }; + if !comments.contains(&text) { + comments.push(text); + } + if !mark.best.is_empty() { + let _ = g.add_line(mark.base, &mark.best[..mark.best.len().min(8)]); + } + } + let _ = g.annotate(id, nags, comments); + } + errors + }) + } + + // ----- UI -------------------------------------------------------------------- + + /// Evaluation graph; returns a main-line node to go to (click or drag). + pub fn graph( + &self, + ui: &mut Ui, + size: egui::Vec2, + cursor: NodeId, + game: &Game, + ) -> Option { + let (rect, resp) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let painter = ui.painter_at(rect); + let visuals = ui.visuals(); + painter.rect_filled(rect, 4.0, visuals.extreme_bg_color); + let n = self.values.len(); + if n < 2 { + return None; + } + let inner = rect.shrink2(vec2(6.0, 6.0)); + let x_of = |i: usize| inner.left() + inner.width() * i as f32 / (n - 1) as f32; + let y_of = |wp: f64| inner.bottom() - inner.height() * (wp / 100.0) as f32; + let mid = y_of(50.0); + let wp: Vec> = self + .values + .iter() + .map(|v| v.map(|e| e.win_percent(Color::White))) + .collect(); + let (white_fill, black_fill) = if visuals.dark_mode { + (Color32::from_gray(150), Color32::from_gray(8)) + } else { + (Color32::from_gray(255), Color32::from_gray(70)) + }; + + // Phase boundaries. + let phase_line = Stroke::new(1.0, visuals.weak_text_color().gamma_multiply(0.6)); + let font = egui::FontId::proportional(11.0); + // Labels go right of their boundary, or left of it when they would not fit. + let label = |x: f32, text: &str| { + let galley = + painter.layout_no_wrap(text.to_string(), font.clone(), visuals.weak_text_color()); + let w = galley.size().x; + let left = if x + 4.0 + w > rect.right() - 4.0 { + x - 4.0 - w + } else { + x + 4.0 + }; + painter.galley( + pos2(left, rect.top() + 3.0), + galley, + visuals.weak_text_color(), + ); + }; + if self.report.phases.middlegame.is_some_and(|m| m > 0) { + label(inner.left(), tr("Opening")); + } + for (idx, name) in [ + (self.report.phases.middlegame, tr("Middlegame")), + (self.report.phases.endgame, tr("Endgame")), + ] { + if let Some(i) = idx { + let x = x_of(i); + if i > 0 { + painter.vline(x, rect.y_range(), phase_line); + } + label(x, name); + } + } + + // Advantage areas between the curve and the middle line. + for i in 0..n - 1 { + let (Some(a), Some(b)) = (wp[i], wp[i + 1]) else { + continue; + }; + let (x0, x1, y0, y1) = (x_of(i), x_of(i + 1), y_of(a), y_of(b)); + let fill = |pts: Vec, above: bool| { + painter.add(egui::Shape::convex_polygon( + pts, + if above { white_fill } else { black_fill }, + Stroke::NONE, + )); + }; + if (a >= 50.0) == (b >= 50.0) { + fill( + vec![pos2(x0, mid), pos2(x0, y0), pos2(x1, y1), pos2(x1, mid)], + a >= 50.0, + ); + } else { + let t = ((50.0 - a) / (b - a)) as f32; + let xc = x0 + (x1 - x0) * t; + fill(vec![pos2(x0, mid), pos2(x0, y0), pos2(xc, mid)], a >= 50.0); + fill(vec![pos2(xc, mid), pos2(x1, y1), pos2(x1, mid)], b >= 50.0); + } + } + painter.hline( + inner.x_range(), + mid, + Stroke::new(1.0, visuals.weak_text_color().gamma_multiply(0.5)), + ); + + // The curve, broken where positions are not evaluated yet. + let curve = Stroke::new(1.6, Color32::from_rgb(0xe0, 0x7b, 0x1f)); + let mut run: Vec = Vec::new(); + for (i, v) in wp.iter().enumerate() { + match v { + Some(w) => run.push(pos2(x_of(i), y_of(*w))), + None => { + if run.len() > 1 { + painter.add(egui::Shape::line(std::mem::take(&mut run), curve)); + } + run.clear(); + } + } + } + if run.len() > 1 { + painter.add(egui::Shape::line(run, curve)); + } + for (i, j) in self.report.judgements.iter().enumerate() { + if let (Some(j), Some(w)) = (j, wp[i + 1]) { + painter.circle_filled(pos2(x_of(i + 1), y_of(w)), 3.5, judgement_color(*j)); + } + } + + // Current move. + if let Some(ci) = self.line_index(cursor, game) { + painter.vline(x_of(ci), rect.y_range(), Stroke::new(1.5, curve.color)); + } + if let Some((done, total)) = self.progress() { + painter.text( + rect.right_top() + vec2(-6.0, 3.0), + egui::Align2::RIGHT_TOP, + format!("{done}/{total}"), + egui::FontId::proportional(11.0), + visuals.text_color(), + ); + } + + let index_at = |x: f32| { + let t = ((x - inner.left()) / inner.width()).clamp(0.0, 1.0); + (t * (n - 1) as f32).round() as usize + }; + if let Some(p) = resp.hover_pos() { + let i = index_at(p.x); + painter.vline( + x_of(i), + rect.y_range(), + Stroke::new(1.0, visuals.weak_text_color()), + ); + let label = if i == 0 { + tr("Start position").to_string() + } else { + game.move_label(self.line[i]).unwrap_or_default() + }; + let eval = self.values[i] + .map(Eval::format) + .unwrap_or_else(|| "…".into()); + let mark = self + .report + .judgements + .get(i.wrapping_sub(1)) + .copied() + .flatten(); + resp.clone().on_hover_ui_at_pointer(|ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(label).strong()); + ui.label(eval); + if let Some(j) = mark { + ui.label(RichText::new(judgement_name(j)).color(judgement_color(j))); + } + }); + }); + } + if (resp.clicked() || resp.dragged()) + && let Some(p) = resp.interact_pointer_pos() + { + let target = self.line[index_at(p.x)]; + if target != cursor { + return Some(target); + } + } + None + } + + /// Index in the main line of `cursor`, or of the main-line move a variation leaves from. + fn line_index(&self, cursor: NodeId, game: &Game) -> Option { + let mut id = cursor; + loop { + if let Some(i) = self.line.iter().position(|n| *n == id) { + return Some(i); + } + id = game.parent(id)?; + } + } + + /// Report tab: per-player statistics in the Lichess layout. + pub fn report_ui(&mut self, ui: &mut Ui, game: &Game) -> Option { + let mut action = None; + ui.add_space(6.0); + for color in [Color::White, Color::Black] { + if let Some(a) = self.side_block(ui, game, color) { + action = Some(a); + } + ui.add_space(10.0); + } + ui.separator(); + if let Some(meta) = &self.meta { + let source = if meta.nodes == 0 { + tr("Evaluations from the PGN ([%eval])").to_string() + } else { + trf( + "{engine} · {nodes} nodes per move", + &[ + ("engine", &meta.engine), + ("nodes", &format_count(meta.nodes)), + ], + ) + }; + ui.label(RichText::new(source).small().weak()); + } + if let Some(e) = &self.error { + ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); + } + let missing = self.missing(); + if missing > 0 && !self.running() { + ui.horizontal_wrapped(|ui| { + ui.label( + RichText::new(trf("Positions without evaluation: {n}", &[("n", &missing)])) + .color(ui.visuals().warn_fg_color), + ); + let can_update = self.meta.as_ref().is_some_and(|m| m.nodes > 0); + if can_update && ui.button(tr("Update")).clicked() { + action = Some(ReportAction::Update); + } + }); + } + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + if ui + .add_enabled( + !self.running() && self.has_data(), + egui::Button::new(tr("Write analysis to the game")), + ) + .on_hover_text(tr( + "Adds evaluations, ?!/?/?? marks, comments and better lines to the game (Ctrl+Z to undo)", + )) + .clicked() + { + action = Some(ReportAction::Write); + } + if ui + .add_enabled(!self.running(), egui::Button::new(tr("Analyse again…"))) + .clicked() + { + action = Some(ReportAction::Reanalyse); + } + }); + action + } + + fn side_block(&mut self, ui: &mut Ui, game: &Game, color: Color) -> Option { + let mut action = None; + let name = game + .tag(if color == Color::White { + "White" + } else { + "Black" + }) + .filter(|s| !s.is_empty() && *s != "?") + .unwrap_or(if color == Color::White { + tr("White") + } else { + tr("Black") + }) + .to_string(); + ui.horizontal(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); + let stroke = Stroke::new(1.5, ui.visuals().text_color()); + if color == Color::White { + ui.painter() + .circle(r.center(), 6.0, Color32::from_gray(235), stroke); + } else { + ui.painter() + .circle(r.center(), 6.0, Color32::TRANSPARENT, stroke); + } + ui.label(RichText::new(name).strong().size(16.0)); + }); + let s = self.report.side(color).clone(); + egui::Grid::new(("review_side", color as u8)) + .num_columns(2) + .spacing(vec2(10.0, 3.0)) + .show(ui, |ui| { + for (j, count) in [ + (Judgement::Inaccuracy, s.inaccuracies), + (Judgement::Mistake, s.mistakes), + (Judgement::Blunder, s.blunders), + ] { + let c = judgement_color(j); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label( + RichText::new(count.to_string()) + .strong() + .size(15.0) + .color(c), + ); + }); + let text = RichText::new(judgement_plural(j)).size(15.0).color(c); + if count > 0 { + let resp = ui + .add(egui::Button::new(text).frame_when_inactive(false)) + .on_hover_text(tr("Go to the next one")); + if resp.clicked() + && let Some(id) = self.next_error(color, j) + { + action = Some(ReportAction::Goto(id)); + } + } else { + ui.label(text); + } + ui.end_row(); + } + let value_row = + |ui: &mut Ui, value: String, label: &str, color: Option| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let mut t = RichText::new(value).strong().size(15.0); + if let Some(c) = color { + t = t.color(c); + } + ui.label(t); + }); + let mut t = RichText::new(label).size(15.0); + if let Some(c) = color { + t = t.color(c); + } + ui.label(t); + ui.end_row(); + }; + let dash = || "—".to_string(); + value_row( + ui, + s.acpl.map_or_else(dash, |v| v.to_string()), + tr("Average centipawn loss"), + None, + ); + value_row( + ui, + s.accuracy.map_or_else(dash, percent), + tr("Accuracy"), + None, + ); + for (i, label) in [tr("Opening"), tr("Middlegame"), tr("Endgame")] + .into_iter() + .enumerate() + { + if let Some(a) = s.phase_accuracy[i] { + value_row(ui, percent(a), label, Some(accuracy_color(a))); + } + } + }); + action + } + + /// Next main-line move of `color` with judgement `j` (cycles). + fn next_error(&mut self, color: Color, j: Judgement) -> Option { + let hits: Vec = self + .report + .judgements + .iter() + .enumerate() + .filter(|(i, x)| **x == Some(j) && self.movers.get(*i) == Some(&color)) + .map(|(i, _)| self.line[i + 1]) + .collect(); + if hits.is_empty() { + return None; + } + let k = self.cycle.entry((color, j)).or_insert(usize::MAX); + *k = k.wrapping_add(1) % hits.len(); + Some(hits[*k]) + } + + /// Launch dialog (engine, quality, threads, memory, time estimate). + pub fn dialog(&mut self, ctx: &egui::Context, settings: &mut Settings) -> Option { + if !self.dialog_open { + return None; + } + let mut action = None; + let modal = egui::Modal::new(egui::Id::new("review_dialog")).show(ctx, |ui| { + ui.set_width(440.0); + ui.heading(tr("Game analysis")); + ui.label( + RichText::new(tr( + "The engine evaluates every position of the main line. The game itself is not changed.", + )) + .weak(), + ); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(tr("Engine")); + let current = settings + .active_engine() + .map(|e| e.name.clone()) + .unwrap_or_else(|| tr("not selected").into()); + egui::ComboBox::from_id_salt("review_engine") + .selected_text(current) + .width(ui.available_width() - 8.0) + .show_ui(ui, |ui| { + for i in 0..settings.engines.len() { + let selected = settings.active_engine == Some(i); + if ui + .selectable_label(selected, &settings.engines[i].name) + .clicked() + && !selected + { + settings.active_engine = Some(i); + action = Some(DialogAction::EngineSwitch); + } + } + ui.separator(); + if ui.button(tr("Add or edit engines…")).clicked() { + action = Some(DialogAction::OpenEngines); + } + }); + }); + ui.add_space(4.0); + let rs = &mut settings.review; + let cores = std::thread::available_parallelism() + .map(|n| n.get() as u32) + .unwrap_or(1); + let hash_steps = crate::game_view::hash_steps(); + ui.spacing_mut().slider_width = 200.0; + egui::Grid::new("review_grid") + .num_columns(3) + .spacing(vec2(12.0, 8.0)) + .show(ui, |ui| { + ui.label(tr("Quality")); + let mut q = rs.quality.min(REVIEW_QUALITY.len() - 1); + crate::game_view::index_slider(ui, &mut q, REVIEW_QUALITY.len()); + rs.quality = q; + ui.label(trf( + "{quality} · {nodes} nodes", + &[ + ("quality", &tr(REVIEW_QUALITY[q].0)), + ("nodes", &format_count(REVIEW_QUALITY[q].1)), + ], + )); + ui.end_row(); + + ui.label(tr("Threads")); + let mut th = rs.threads.clamp(1, cores) as usize - 1; + crate::game_view::index_slider(ui, &mut th, cores as usize); + rs.threads = th as u32 + 1; + ui.label(format!("{} / {cores}", rs.threads)); + ui.end_row(); + + ui.label(tr("Memory")); + let mut h = hash_steps + .iter() + .position(|m| *m >= rs.hash_mb) + .unwrap_or(hash_steps.len() - 1); + crate::game_view::index_slider(ui, &mut h, hash_steps.len()); + rs.hash_mb = hash_steps[h]; + ui.label(crate::game_view::format_mb(rs.hash_mb)); + ui.end_row(); + }); + ui.add_space(6.0); + let positions = self + .values + .iter() + .filter(|v| !matches!(v, Some(Eval::Mate { moves: 0, .. }))) + .count(); + let per_thread = self.nps_per_thread.unwrap_or(700_000.0); + let secs = positions as f64 * rs.nodes() as f64 / (per_thread * f64::from(rs.threads)); + ui.label(trf( + "{n} positions, about {time}", + &[("n", &positions), ("time", &format_duration(secs))], + )); + ui.add_space(10.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let ready = settings.active_engine().is_some(); + if ui + .add_enabled( + ready, + egui::Button::new(RichText::new(tr("Analyse")).strong().size(16.0)), + ) + .clicked() + { + action = Some(DialogAction::Start); + } + if ui.button(tr("Cancel")).clicked() { + self.dialog_open = false; + } + if !ready { + ui.label( + RichText::new(tr("Add an engine first")) + .color(ui.visuals().warn_fg_color), + ); + } + }); + }); + }); + if modal.should_close() { + self.dialog_open = false; + } + if matches!( + action, + Some(DialogAction::Start | DialogAction::OpenEngines) + ) { + self.dialog_open = false; + } + action + } +} + +impl Drop for Review { + fn drop(&mut self) { + // Leaving the game mid-analysis keeps what was computed. + self.cancel(); + } +} + +#[allow(clippy::too_many_arguments)] +fn run_job( + path: PathBuf, + threads: u32, + hash_mb: u32, + nodes: u64, + targets: Vec, + tx: &Sender, + cancel: &AtomicBool, + ctx: &egui::Context, +) -> Result<(), String> { + let handle = uci::Engine::spawn_with(uci::EngineConfig::new(&path), Box::new(|| {})) + .map_err(|e| e.to_string())?; + if let Some(name) = &handle.info().name { + let _ = tx.send(JobMsg::Engine(name.clone())); + } + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = handle.set_threads(threads); + let _ = handle.set_hash_mb(hash_mb); + let _ = handle.set_multipv(1); + let _ = handle.new_game(); + for (i, t) in targets.into_iter().enumerate() { + let id = SearchId(i as u64 + 1); + handle + .search(t.pos.clone(), id, SearchLimits::Nodes(nodes)) + .map_err(|e| e.to_string())?; + let started = Instant::now(); + let mut stopping = false; + let mut last: Option = None; + loop { + if cancel.load(Ordering::Relaxed) { + handle.quit(); + return Ok(()); + } + if !stopping && started.elapsed() > SEARCH_GUARD { + let _ = handle.stop(); + stopping = true; + } + match handle.recv_timeout(Duration::from_millis(100)) { + Some(EngineEvent::Info { search_id, info }) if search_id == id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || last.is_none() { + last = Some(info); + } + } + } + Some(EngineEvent::BestMove { + search_id, best, .. + }) if search_id == id => { + if let Some(info) = last.take() + && let Some(score) = info.score + { + let eval = Eval::from_white_eval(score.to_white(t.turn).eval); + let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); + if let Some(b) = best + && pv.first() != Some(&b) + { + pv = vec![b]; + } + let _ = tx.send(JobMsg::Eval { + key: t.key, + eval: PosEval { + eval, + pv, + depth: info.depth.unwrap_or(0), + }, + nps: info.nps.unwrap_or(0), + }); + ctx.request_repaint(); + } + break; + } + Some(EngineEvent::Terminated(reason)) => { + return Err(crate::analysis::termination_message(&reason)); + } + _ => {} + } + } + } + handle.quit(); + Ok(()) +} + +/// Cache key and UCI position of a node (full history, see [`Game::engine_history`]). +fn position_key(game: &Game, id: NodeId) -> Option<(String, EnginePosition)> { + let h = game.engine_history(id)?; + let key = format!( + "{}|{}", + h.start_fen.as_deref().unwrap_or("startpos"), + h.moves.join(" ") + ); + let pos = match h.start_fen { + None => EnginePosition::startpos(h.moves), + Some(fen) => EnginePosition::fen(fen, h.moves), + }; + Some((key, pos)) +} + +/// Evaluation of a position without legal moves. +fn terminal_eval(pos: &Chess) -> Option { + if pos.is_checkmate() { + Some(Eval::Mate { + white: pos.turn() == Color::Black, + moves: 0, + }) + } else if pos.is_stalemate() { + Some(Eval::Cp(0)) + } else { + None + } +} + +fn parse_pv(root: &Chess, pv: &[String]) -> (Vec, Vec) { + let mut pos = root.clone(); + let (mut moves, mut san) = (Vec::new(), Vec::new()); + for u in pv { + let Some(m) = u + .parse::() + .ok() + .and_then(|um| um.to_move(&pos).ok()) + else { + break; + }; + san.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); + moves.push(m); + } + (moves, san) +} + +/// Removes `[%eval …]` commands from a comment. +fn strip_eval(c: &str) -> String { + let mut out = String::new(); + let mut rest = c; + while let Some(i) = rest.find("[%eval") { + out.push_str(&rest[..i]); + match rest[i..].find(']') { + Some(j) => rest = &rest[i + j + 1..], + None => { + rest = ""; + } + } + } + out.push_str(rest); + out.trim().to_string() +} + +pub fn judgement_color(j: Judgement) -> Color32 { + match j { + Judgement::Inaccuracy => Color32::from_rgb(0x56, 0xb4, 0xe9), + Judgement::Mistake => Color32::from_rgb(0xe6, 0x8f, 0x00), + Judgement::Blunder => Color32::from_rgb(0xdf, 0x53, 0x53), + } +} + +pub fn judgement_symbol(j: Judgement) -> &'static str { + match j { + Judgement::Inaccuracy => "?!", + Judgement::Mistake => "?", + Judgement::Blunder => "??", + } +} + +pub fn judgement_name(j: Judgement) -> &'static str { + match j { + Judgement::Inaccuracy => tr("Inaccuracy"), + Judgement::Mistake => tr("Mistake"), + Judgement::Blunder => tr("Blunder"), + } +} + +fn judgement_plural(j: Judgement) -> &'static str { + match j { + Judgement::Inaccuracy => tr("Inaccuracies"), + Judgement::Mistake => tr("Mistakes"), + Judgement::Blunder => tr("Blunders"), + } +} + +fn accuracy_color(a: f64) -> Color32 { + if a >= 85.0 { + Color32::from_rgb(0x62, 0x9c, 0x2e) + } else if a >= 70.0 { + Color32::from_rgb(0x56, 0xb4, 0xe9) + } else if a >= 50.0 { + Color32::from_rgb(0xe6, 0x8f, 0x00) + } else { + Color32::from_rgb(0xdf, 0x53, 0x53) + } +} + +fn percent(a: f64) -> String { + format!("{}%", a.round() as i64) +} + +/// 250 000 → "250k", 1 000 000 → "1M". +fn format_count(n: u64) -> String { + if n >= 1_000_000 && n.is_multiple_of(100_000) { + let m = n as f64 / 1e6; + if n.is_multiple_of(1_000_000) { + format!("{m:.0}M") + } else { + format!("{m:.1}M") + } + } else if n >= 1000 { + format!("{}k", n / 1000) + } else { + n.to_string() + } +} + +fn format_duration(secs: f64) -> String { + let s = secs.ceil().max(1.0) as u64; + if s < 60 { + trf("{n} s", &[("n", &s)]) + } else { + trf("{n} min", &[("n", &s.div_ceil(60))]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strip_eval_keeps_other_text() { + assert_eq!(strip_eval("[%eval 0.35] Good move"), "Good move"); + assert_eq!( + strip_eval("A [%eval #-3] B [%clk 0:01:00]"), + "A B [%clk 0:01:00]" + ); + assert_eq!(strip_eval("[%eval 1.0"), ""); + } + + #[test] + fn counts_are_compact() { + assert_eq!(format_count(250_000), "250k"); + assert_eq!(format_count(1_000_000), "1M"); + assert_eq!(format_count(1_500_000), "1.5M"); + } + + #[test] + fn pgn_evals_and_written_analysis_roundtrip() { + let mut game = chess_core::parse_str( + "1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} 2. Qh5 {[%eval -0.2]} Ke7 {[%eval 6.5]} \ + 3. Qxe5# 1-0", + ) + .game; + let mut r = Review::new(&game); + assert!(r.has_data() && r.visible); + assert_eq!(r.missing(), 0); + assert!(r.report.complete); + // 2…Ke7 throws the game away; 3.Qxe5# is a terminal position. + let ke7 = game.mainline()[3]; + assert_eq!( + r.marks.get(&ke7).map(|m| m.judgement), + Some(Judgement::Blunder) + ); + assert_eq!(r.report.black.blunders, 1); + + let errors = r.write_to_game(&mut game); + assert_eq!(errors, r.marks.len()); + let node = game.node(ke7).expect("node"); + assert!(node.nags().contains(&Nag::BLUNDER)); + assert!(node.comments_after()[0].starts_with("[%eval 6.50]")); + r.refresh(&game); + // Writing again replaces evaluations instead of duplicating them. + r.write_to_game(&mut game); + let n = game.node(ke7).expect("node"); + assert_eq!( + n.comments_after() + .iter() + .filter(|c| c.contains("[%eval")) + .count(), + 1 + ); + assert_eq!( + n.nags().iter().filter(|x| x.is_move_assessment()).count(), + 1 + ); + // Both writes are single undo steps. + game.undo(); + game.undo(); + assert!(!game.is_modified()); + r.cancel(); + } +} diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index 6d54e81..e9d5790 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -63,6 +63,41 @@ pub struct Settings { pub show_best_arrow: bool, /// Recently opened PGN files, most recent first. pub databases: Vec, + /// Whole-game analysis options. + pub review: ReviewSettings, +} + +/// Options of the whole-game analysis (the engine is the active one). +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default)] +pub struct ReviewSettings { + /// Index into [`REVIEW_QUALITY`]. + pub quality: usize, + pub threads: u32, + pub hash_mb: u32, +} + +impl Default for ReviewSettings { + fn default() -> Self { + Self { + quality: 1, + threads: default_threads(), + hash_mb: default_hash(), + } + } +} + +/// Search effort per position: (label, nodes). +pub const REVIEW_QUALITY: [(&str, u64); 3] = [ + ("Fast", 250_000), + ("Normal", 1_000_000), + ("Deep", 3_000_000), +]; + +impl ReviewSettings { + pub fn nodes(&self) -> u64 { + REVIEW_QUALITY[self.quality.min(REVIEW_QUALITY.len() - 1)].1 + } } impl Default for Settings { @@ -80,6 +115,7 @@ impl Default for Settings { active_engine: None, show_best_arrow: true, databases: Vec::new(), + review: ReviewSettings::default(), } } } @@ -90,6 +126,12 @@ impl Settings { .map(|d| d.config_dir().to_path_buf()) } + /// `~/.cache/chesspenguin` (derived data that can be deleted at any time). + pub fn cache_dir() -> Option { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.cache_dir().to_path_buf()) + } + fn file() -> Option { Self::config_dir().map(|d| d.join("settings.json")) } diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 1b84c91..c8bad5b 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -5,7 +5,16 @@ use egui::{Color32, Sense, Stroke, Ui, vec2}; /// Window close button (the app runs undecorated under tiling compositors). pub fn close_button(ui: &mut Ui) -> egui::Response { - let (rect, resp) = ui.allocate_exact_size(vec2(32.0, 28.0), Sense::click()); + x_button(ui, vec2(32.0, 28.0), 6.0).on_hover_text(tr("Close the application")) +} + +/// Compact ✕ (e.g. to cancel a running task); the caller adds the tooltip. +pub fn small_close_button(ui: &mut Ui) -> egui::Response { + x_button(ui, vec2(22.0, 20.0), 4.5) +} + +fn x_button(ui: &mut Ui, size: egui::Vec2, d: f32) -> egui::Response { + let (rect, resp) = ui.allocate_exact_size(size, Sense::click()); if resp.hovered() { ui.painter() .rect_filled(rect, 4.0, Color32::from_rgb(0xc4, 0x2b, 0x1c)); @@ -16,11 +25,10 @@ pub fn close_button(ui: &mut Ui) -> egui::Response { ui.visuals().text_color() }; let c = rect.center(); - let d = 6.0; let stroke = Stroke::new(1.6, color); ui.painter() .line_segment([c + vec2(-d, -d), c + vec2(d, d)], stroke); ui.painter() .line_segment([c + vec2(-d, d), c + vec2(d, -d)], stroke); - resp.on_hover_text(tr("Close the application")) + resp } diff --git a/crates/chess-core/src/edit.rs b/crates/chess-core/src/edit.rs index e3049a9..ad67607 100644 --- a/crates/chess-core/src/edit.rs +++ b/crates/chess-core/src/edit.rs @@ -7,6 +7,14 @@ use shakmaty::{CastlingMode, Move, Position, san::SanPlus, uci::UciMove}; use crate::game::{Game, GameMove, MoveKind, NodeId}; +use crate::nag::Nag; + +/// NAGs and trailing comments of a node (what annotation edits change). +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct Annotations { + nags: Vec, + comments_after: Vec, +} #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Command { @@ -25,12 +33,19 @@ pub(crate) enum Command { from: usize, to: usize, }, + Annotate { + node: NodeId, + old: Annotations, + new: Annotations, + }, + /// Several commands undone and redone as one step. + Group(Vec), } impl Command { fn inverse(&self) -> Command { - match *self { - Command::Attach { + match self { + &Command::Attach { parent, child, index, @@ -39,7 +54,7 @@ impl Command { child, index, }, - Command::Detach { + &Command::Detach { parent, child, index, @@ -48,22 +63,32 @@ impl Command { child, index, }, - Command::Reorder { parent, from, to } => Command::Reorder { + &Command::Reorder { parent, from, to } => Command::Reorder { parent, from: to, to: from, }, + Command::Annotate { node, old, new } => Command::Annotate { + node: *node, + old: new.clone(), + new: old.clone(), + }, + Command::Group(cmds) => { + Command::Group(cmds.iter().rev().map(Command::inverse).collect()) + } } } /// Node the UI should select after this command has been applied. fn cursor(&self, game: &Game) -> NodeId { - match *self { - Command::Attach { child, .. } => child, - Command::Detach { parent, .. } => parent, - Command::Reorder { parent, to, .. } => { + match self { + &Command::Attach { child, .. } => child, + &Command::Detach { parent, .. } => parent, + &Command::Reorder { parent, to, .. } => { game.children(parent).get(to).copied().unwrap_or(parent) } + Command::Annotate { node, .. } => *node, + Command::Group(cmds) => cmds.first().map_or(NodeId::ROOT, |c| c.cursor(game)), } } } @@ -227,6 +252,43 @@ impl Game { Ok(()) } + /// Replaces the NAGs and trailing comments of `id`. Undoable; no-op if unchanged. + pub fn annotate( + &mut self, + id: NodeId, + nags: Vec, + comments_after: Vec, + ) -> Result<(), EditError> { + self.check_attached(id)?; + let node = self.node(id).ok_or(EditError::UnknownNode)?; + let old = Annotations { + nags: node.nags.clone(), + comments_after: node.comments_after.clone(), + }; + let new = Annotations { + nags, + comments_after, + }; + if old != new { + self.record(Command::Annotate { node: id, old, new }); + } + Ok(()) + } + + /// Runs `f` so that all its edits form a single undo step. + pub fn edit_group(&mut self, f: impl FnOnce(&mut Game) -> R) -> R { + let outer = self.group.replace(Vec::new()); + let result = f(self); + let cmds = std::mem::replace(&mut self.group, outer).unwrap_or_default(); + if !cmds.is_empty() { + match &mut self.group { + Some(parent) => parent.push(Command::Group(cmds)), + None => self.push_undo(Command::Group(cmds)), + } + } + result + } + pub fn can_undo(&self) -> bool { !self.undo_stack.is_empty() } @@ -260,6 +322,15 @@ impl Game { if !matches!(cmd, Command::Attach { .. }) { self.apply(&cmd); } + if let Some(group) = &mut self.group { + group.push(cmd); + self.touch(); + return; + } + self.push_undo(cmd); + } + + fn push_undo(&mut self, cmd: Command) { if self.saved_depth.is_some_and(|d| d > self.undo_stack.len()) { // The saved state lived in the redo stack, which is discarded now. self.saved_depth = None; @@ -270,6 +341,22 @@ impl Game { } fn apply(&mut self, cmd: &Command) { + match cmd { + Command::Annotate { node, new, .. } => { + if let Some(n) = self.node_mut(*node) { + n.nags.clone_from(&new.nags); + n.comments_after.clone_from(&new.comments_after); + } + return; + } + Command::Group(cmds) => { + for c in cmds { + self.apply(c); + } + return; + } + _ => {} + } match *cmd { Command::Attach { parent, @@ -299,6 +386,7 @@ impl Game { p.children.insert(to, c); } } + Command::Annotate { .. } | Command::Group(_) => {} } } @@ -426,4 +514,60 @@ mod tests { Err(EditError::RootNotRemovable) ); } + + #[test] + fn annotate_is_undoable() { + let mut g = Game::new(); + let e4 = g.add_uci_line(g.root(), &["e2e4"]).expect("e4"); + g.mark_saved(); + g.annotate(e4, vec![Nag::GOOD_MOVE], vec!["[%eval 0.3]".into()]) + .expect("annotate"); + assert_eq!( + g.node(e4).map(|n| n.nags().to_vec()), + Some(vec![Nag::GOOD_MOVE]) + ); + assert!(g.is_modified()); + // Unchanged annotations do not create an undo step. + let depth = g.undo_stack.len(); + g.annotate(e4, vec![Nag::GOOD_MOVE], vec!["[%eval 0.3]".into()]) + .expect("same"); + assert_eq!(g.undo_stack.len(), depth); + assert_eq!(g.undo().map(|o| o.cursor), Some(e4)); + assert!( + g.node(e4) + .is_some_and(|n| n.nags().is_empty() && n.comments_after().is_empty()) + ); + assert!(!g.is_modified()); + g.redo(); + assert_eq!(g.node(e4).map(|n| n.comments_after().len()), Some(1)); + } + + #[test] + fn edit_group_is_one_undo_step() { + let mut g = Game::new(); + let end = g + .add_uci_line(g.root(), &["e2e4", "e7e5", "g1f3"]) + .expect("line"); + let e4 = g.main_child(g.root()).expect("e4"); + let e5 = g.main_child(e4).expect("e5"); + let before = g.canonical_tree(); + let steps = g.undo_stack.len(); + g.edit_group(|g| { + g.annotate(e5, vec![Nag::MISTAKE], vec!["better c5".into()]) + .expect("annotate"); + g.add_uci_line(e4, &["c7c5", "g1f3"]).expect("variation"); + g.edit_group(|g| g.annotate(end, vec![Nag::DUBIOUS_MOVE], Vec::new())) + .expect("nested"); + }); + assert_eq!(g.undo_stack.len(), steps + 1); + assert_eq!(g.children(e4).len(), 2); + let after = g.canonical_tree(); + g.undo(); + assert_eq!(g.canonical_tree(), before); + g.redo(); + assert_eq!(g.canonical_tree(), after); + // An empty group records nothing. + g.edit_group(|_| ()); + assert_eq!(g.undo_stack.len(), steps + 1); + } } diff --git a/crates/chess-core/src/game.rs b/crates/chess-core/src/game.rs index 98ca3f6..c8f7e73 100644 --- a/crates/chess-core/src/game.rs +++ b/crates/chess-core/src/game.rs @@ -191,6 +191,8 @@ pub struct Game { pub(crate) saved_depth: Option, /// Changes outside the undo history (tags, result) since the last save. pub(crate) unsaved_meta: bool, + /// Commands collected by an open [`Game::edit_group`]. + pub(crate) group: Option>, } impl Default for Game { @@ -254,6 +256,7 @@ impl Game { revision: 0, saved_depth: Some(0), unsaved_meta: false, + group: None, } } diff --git a/docs/decisions.md b/docs/decisions.md index ed3f6a3..4f6dd99 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -14,6 +14,15 @@ 7. **Название — ChessPenguin** (2026-10-18). Бинарник и пакеты `chesspenguin`, app id `io.github.vrubelroman.chessPenguin`, настройки в `~/.config/chesspenguin` (старые переносятся автоматически). 8. **Публикация** — https://github.com/vrubelroman/chessPenguin, чистая история без `designExample/` (чужие скриншоты остаются только локально). Версии по SemVer, первая — `0.1.0`, тег `v0.1.0`; релизы собирает GitHub Actions по тегу `v*`: deb, rpm, AppImage, Flatpak, Windows zip. +9. **Анализ партии (версия 0.2)** — 2026-10-18, по схеме, предложенной оркестратором и принятой пользователем: + - живой движок (оценка текущей позиции, `L`) и анализ партии целиком — разные процессы и разные кнопки; на время анализа партии живой движок ставится на паузу и затем возобновляется; + - кнопка «📈 Анализ партии» в шапке экрана партии (действие над партией, не над позицией), `Shift+A`; во время работы — прогресс и отмена, после — «📈 Отчёт» скрывает/показывает результаты; + - график оценки — полосой под доской (шкала — шанс на победу, как на Lichess), клик/протяжка переходит к ходу, отмечены стадии партии и ошибки; + - статистика — вкладкой «Отчёт» рядом с нотацией: неточности/ошибки/зевки (клик — к следующей), средняя потеря сантипешек, точность и точность по стадиям; кнопки «разобрать свои ошибки» нет — смотрим чужие партии; + - отметки движка в нотации — отдельным слоем (цветной значок), партия не меняется; «Записать анализ в партию» — отдельное действие с одним шагом отмены (NAG, комментарий, лучший вариант, `[%eval]`); + - анализируется только основная линия; результаты кэшируются в `~/.cache/chesspenguin/analysis/`; при правке основной линии дооцениваются только новые позиции; оценки `[%eval]` из PGN используются без движка; + - методика — опубликованные формулы Lichess (lichess.org/page/accuracy), реализованы заново. + ## Следует из исходного ТЗ - Linux desktop; предпочтение стека Artcraft, подлежащего проверке по исходникам. diff --git a/docs/dev/desktop.md b/docs/dev/desktop.md index 58bcc50..33c4c67 100644 --- a/docs/dev/desktop.md +++ b/docs/dev/desktop.md @@ -12,6 +12,8 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i | `notation.rs` | Нотация: основная линия таблицей в две колонки, комментарии/варианты блоками, вложенные варианты в скобках | | `board.rs` | Виджет доски: клик/drag, превращение, рокировка кликом на поле короля или ладью, стрелки, круги | | `analysis.rs` | Контроллер анализа поверх `uci`: запуск в фоне, привязка результатов к истории позиции, MultiPV | +| `report.rs` | Метрики анализа партии без UI: шанс на победу, точность хода и партии, неточность/ошибка/зевок, средняя потеря сантипешек, стадии партии (формулы Lichess) | +| `review.rs` | Анализ партии целиком: фоновый поток с собственным процессом движка (`go nodes N`), кэш, `[%eval]` из PGN, график, вкладка «Отчёт», окно запуска, запись анализа в партию | | `assets.rs`, `sound.rs` | Встроенные SVG-фигуры, темы доски, звуки (rodio в отдельном потоке) | | `settings.rs`, `settings_ui.rs` | JSON в `$XDG_CONFIG_HOME/chesspenguin/settings.json` (атомарная запись), окно настроек | @@ -20,11 +22,12 @@ egui/eframe 0.36 (wgpu, Wayland/X11). Бинарник `chesspenguin`, app id `i - Анализ привязан к курсору партии, не к предпросмотру. Ключ — стартовая позиция + история ходов UCI; события с чужим `SearchId` отбрасываются. - Предпросмотр PV — снимок линии; документ меняется только кнопкой «Добавить как вариант» (один шаг Undo). - Исходный PGN не перезаписывается: только «Сохранить партию как…» в отдельный файл. +- Анализ партии не меняет документ. Ключ оценки — та же история позиции, что у живого анализа; кэш — `$XDG_CACHE_HOME/chesspenguin/analysis/.json`. «Записать анализ в партию» — `Game::edit_group`, один шаг Undo; повторная запись заменяет `[%eval]`, а не дублирует. ## Клавиатура Библиотека: ↑/↓ — строка, Enter — открыть, Ctrl+O — добавить PGN, Ctrl+N — новая партия, Ctrl+F — поиск. -Партия: ←/→ — ход, ↑/↓ — соседний вариант, Home/End, F — перевернуть, L — движок, Esc — выйти из предпросмотра, +Партия: ←/→ — ход, ↑/↓ — соседний вариант, Home/End, F — перевернуть, L — движок, Shift+A — анализ партии / отчёт, Esc — выйти из предпросмотра, Ctrl+Z / Ctrl+Y — отмена/повтор, Ctrl+Shift+C — копировать PGN, Ctrl+S — сохранить как, Ctrl+W — в библиотеку, Ctrl+, — настройки. ## Dev-хуки запуска (ручная проверка и скриншоты) @@ -34,7 +37,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` — открыть настройки, `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. +`CP_ANALYZE` — запустить активный движок, `CP_SETTINGS` — открыть настройки, `CP_ENGINE_PANEL` — раскрыть панель настроек движка, `CP_VAR` — перейти в первый вариант после `CP_PLY`, `CP_REVIEW=1` — запустить анализ партии (`=dialog` — только открыть окно), `CP_SCREENSHOT=file.png` (+ `CP_SCREENSHOT_DELAY=сек`) — полноэкранный снимок окна и выход; так сделаны `docs/screenshots/`. ## Языки