Game screen: result in the header, move badges, refutation arrows, viewed games
Some checks are pending
CI / check (push) Waiting to run
CI / windows-build (push) Waiting to run

- Header shows the result (1-0, 0-1, ½-½) next to the players.
- Lichess-style badge on the moved piece: engine judgement (??, ?, ?!) when the
  game analysis is shown, otherwise the author's !/?/!!/!?/?! symbol.
- On a marked move the board shows the engine's refutation (opponent's best
  reply) and the best answer to it instead of the better move.
- Engine arrows are all blue and deduplicated; with the live engine on only its
  arrows are drawn.
- Library marks games opened before with a check (remembered by content in
  viewed.json); context menu to mark/unmark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubel 2026-10-18 14:00:19 +03:00
parent bb7d3b3fa6
commit f25826664a
9 changed files with 362 additions and 39 deletions

View file

@ -391,6 +391,7 @@ impl App {
}),
parsed.diagnostics,
));
self.library.mark_viewed(&path, index);
self.settings.touch_database(&path);
self.settings_dirty = true;
}

View file

@ -14,6 +14,14 @@ pub struct Arrow {
pub weight: f32,
}
/// A round label in the top right corner of a square, as on Lichess.
#[derive(Clone, Copy, Debug)]
pub struct Badge {
pub square: Square,
pub text: &'static str,
pub color: Color32,
}
/// Interaction state that lives across frames (per board instance).
#[derive(Default)]
pub struct BoardState {
@ -35,6 +43,8 @@ pub struct BoardView<'a> {
pub arrows: &'a [Arrow],
/// Circled squares (from `[%csl]` comment annotations).
pub circles: &'a [(Square, Color32)],
/// Move assessment shown on the destination square of the last move ("??" in red, …).
pub badge: Option<Badge>,
pub interactive: bool,
pub show_coords: bool,
pub theme: BoardTheme,
@ -170,6 +180,33 @@ impl BoardView<'_> {
for a in self.arrows {
draw_arrow(&painter, &geo, a);
}
if let Some(b) = self.badge {
let r = geo.square_rect(b.square);
let radius = sq_size * 0.19;
// Over the corner of the square, kept inside the board.
let c = egui::pos2(
(r.right() - radius * 0.35).min(rect.right() - radius - 1.0),
(r.top() + radius * 0.35).max(rect.top() + radius + 1.0),
);
painter.circle_filled(
c + vec2(0.0, sq_size * 0.015),
radius,
Color32::from_black_alpha(90),
);
painter.circle(
c,
radius,
b.color,
Stroke::new(sq_size * 0.02, Color32::WHITE),
);
painter.text(
c,
egui::Align2::CENTER_CENTER,
b.text,
egui::FontId::proportional(radius * 1.05),
Color32::WHITE,
);
}
// dragged piece follows the cursor
if let (Some(from), true) = (state.drag, response.dragged())

View file

@ -5,7 +5,7 @@ use std::path::PathBuf;
use chess_core::shakmaty::{Chess, Color, Move, Position, Square};
use chess_core::{
Annotation, CommentPart, Diagnostic, Game, MoveKind, NodeId, Severity, ShapeColor,
Annotation, CommentPart, Diagnostic, Game, GameResult, MoveKind, NodeId, Severity, ShapeColor,
parse_comment,
};
use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2};
@ -138,6 +138,37 @@ impl GameView {
self.preview = None;
}
/// Assessment of the move that led to the current position, for the board: the
/// engine's judgement when the game analysis is shown, otherwise the author's
/// `!`/`?` symbol.
fn badge(&self) -> Option<board::Badge> {
let square = match self.game.game_move(self.cursor)?.kind {
MoveKind::Normal(m) => move_squares(&m)?.1,
MoveKind::Null => return None,
};
if self.review.visible
&& let Some(mark) = self.review.marks.get(&self.cursor)
{
return Some(board::Badge {
square,
text: crate::review::judgement_symbol(mark.judgement),
color: crate::review::judgement_color(mark.judgement),
});
}
let nag = self
.game
.node(self.cursor)?
.nags()
.iter()
.copied()
.find(|n| n.is_move_assessment())?;
Some(board::Badge {
square,
text: nag.symbol()?,
color: crate::notation::assessment_color(nag)?,
})
}
fn sound_for(&self, id: NodeId) -> Option<Sound> {
let mv = self.game.game_move(id)?;
let pos = self.game.position(id)?;
@ -324,11 +355,22 @@ impl GameView {
ui.separator();
ui.vertical(|ui| {
let modified = if self.game.is_modified() { " •" } else { "" };
ui.label(
RichText::new(format!("{}{modified}", self.title()))
.strong()
.size(16.0),
);
ui.horizontal(|ui| {
ui.label(
RichText::new(format!("{}{modified}", self.title()))
.strong()
.size(16.0),
);
if let Some(result) = result_label(self.game.result()) {
ui.label(
RichText::new(format!(" {result} "))
.strong()
.size(15.0)
.background_color(ui.visuals().widgets.inactive.weak_bg_fill),
)
.on_hover_text(result_hint(self.game.result()));
}
});
let sub = self.subtitle();
if !sub.is_empty() {
ui.label(RichText::new(sub).weak());
@ -428,30 +470,27 @@ 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,
});
// With the live engine on, only its arrows are drawn: two sources of engine
// arrows on one board would overlap and compete.
if self.review.visible && !analysis.is_on() {
// The opponent's best reply to a marked move (strong) and the best answer to it.
let line = self.review.refutation(self.cursor, &self.game);
for (k, m) in line.iter().enumerate() {
if let Some(sq) = move_squares(m) {
engine_arrow(
&mut arrows,
sq,
if k == 0 { 200 } else { 100 },
if k == 0 { 1.0 } else { 0.75 },
);
}
}
}
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) {
let alpha = if i == 0 { 170 } else { 90 };
arrows.push(Arrow {
from: sq.0,
to: sq.1,
color: Color32::from_rgba_unmultiplied(21, 120, 27, alpha),
weight: if i == 0 { 1.0 } else { 0.7 },
});
let alpha = if i == 0 { 200 } else { 100 };
engine_arrow(&mut arrows, sq, alpha, if i == 0 { 1.0 } else { 0.7 });
}
}
}
@ -529,6 +568,11 @@ impl GameView {
last_move,
arrows: &arrows,
circles: &circles,
badge: if self.preview.is_none() {
self.badge()
} else {
None
},
interactive: self.preview.is_none(),
show_coords: settings.show_coords,
theme: settings.board_theme.theme(),
@ -1333,6 +1377,43 @@ fn game_over(pos: &Chess) -> Option<GameOver> {
}
}
/// Engine arrows (live analysis and game analysis) are all blue; a move both suggest
/// is drawn once, with the stronger of the two looks.
fn engine_arrow(arrows: &mut Vec<Arrow>, (from, to): (Square, Square), alpha: u8, weight: f32) {
let color = Color32::from_rgba_unmultiplied(0, 48, 136, alpha);
if let Some(a) = arrows.iter_mut().find(|a| a.from == from && a.to == to) {
if a.color.a() < color.a() {
a.color = color;
}
a.weight = a.weight.max(weight);
return;
}
arrows.push(Arrow {
from,
to,
color,
weight,
});
}
/// "1-0", "0-1", "½-½"; `None` for an unfinished game.
fn result_label(r: GameResult) -> Option<&'static str> {
match r {
GameResult::WhiteWins => Some("1-0"),
GameResult::BlackWins => Some("0-1"),
GameResult::Draw => Some("½-½"),
GameResult::Unknown => None,
}
}
fn result_hint(r: GameResult) -> &'static str {
match r {
GameResult::WhiteWins => tr("White won"),
GameResult::BlackWins => tr("Black won"),
_ => tr("Draw"),
}
}
fn move_squares(m: &Move) -> Option<(Square, Square)> {
Some((m.from()?, board::ui_target(m)))
}

View file

@ -1477,6 +1477,41 @@ const ROWS: &[[&str; 6]] = &[
"· {n} partidas · {format}, solo lectura",
"· {n} partite · {format}, sola lettura",
],
// Game result
[
"White won",
"Победили белые",
"Les Blancs ont gagné",
"Weiß hat gewonnen",
"Ganaron las blancas",
"Hanno vinto i bianchi",
],
[
"Black won",
"Победили чёрные",
"Les Noirs ont gagné",
"Schwarz hat gewonnen",
"Ganaron las negras",
"Hanno vinto i neri",
],
["Draw", "Ничья", "Nulle", "Remis", "Tablas", "Patta"],
// Viewed games
[
"Mark as viewed",
"Отметить как просмотренную",
"Marquer comme vue",
"Als angesehen markieren",
"Marcar como vista",
"Segna come vista",
],
[
"Mark as not viewed",
"Снять отметку «просмотрена»",
"Marquer comme non vue",
"Als nicht angesehen markieren",
"Marcar como no vista",
"Segna come non vista",
],
];
#[cfg(test)]

View file

@ -10,7 +10,9 @@ use std::sync::{Arc, Mutex};
use chess_core::{GameEntry, PgnDatabase, ScanProgress};
use chess_import::{Format, ImportError, Opened, Unsupported};
use egui::{Color32, RichText, Sense, Ui, vec2};
use egui::{Color32, RichText, Sense, Stroke, Ui, vec2};
use crate::viewed::{self, Viewed};
use egui_extras::{Column, TableBuilder};
enum Slot {
@ -55,6 +57,9 @@ struct ImportInfo {
pub struct Library {
slots: HashMap<PathBuf, Slot>,
/// Games the user has opened (by content), and the content key of each game per database.
viewed: Viewed,
keys: HashMap<PathBuf, Vec<u64>>,
info: HashMap<PathBuf, ImportInfo>,
/// Database whose import notes are shown.
notes_open: Option<PathBuf>,
@ -72,6 +77,8 @@ impl Library {
pub fn new() -> Self {
Self {
slots: HashMap::new(),
viewed: Viewed::load(),
keys: HashMap::new(),
info: HashMap::new(),
notes_open: None,
selected_db: None,
@ -152,6 +159,7 @@ impl Library {
pub fn forget(&mut self, path: &Path) {
self.info.remove(path);
self.keys.remove(path);
if let Some(Slot::Loading { cancel, .. }) = self.slots.remove(path) {
cancel.store(true, Ordering::Relaxed);
}
@ -161,6 +169,13 @@ impl Library {
}
}
/// Remembers that a game was opened (shown with a check mark in the table).
pub fn mark_viewed(&mut self, path: &Path, index: usize) {
if let Some(&k) = self.keys.get(path).and_then(|k| k.get(index)) {
self.viewed.set(k, true);
}
}
pub fn database(&self, path: &Path) -> Option<Arc<PgnDatabase>> {
match self.slots.get(path) {
Some(Slot::Ready(db)) => Some(db.clone()),
@ -175,6 +190,10 @@ impl Library {
{
*slot = match res {
Ok(o) => {
let keys = (0..o.db.len())
.map(|i| viewed::key(o.db.raw_bytes(i).unwrap_or_default()))
.collect();
self.keys.insert(path.clone(), keys);
self.info.insert(
path.clone(),
ImportInfo {
@ -567,6 +586,9 @@ impl Library {
}
let view = &self.view;
let entries = db.entries();
let keys = self.keys.get(&path);
let viewed = &self.viewed;
let mut toggle_viewed = None;
let mut clicked = None;
let mut opened = None;
let mut sort_click = None;
@ -599,6 +621,8 @@ impl Library {
return;
};
row.set_selected(self.selected_row == Some(e.index));
let key = keys.and_then(|k| k.get(e.index)).copied();
let seen = key.is_some_and(|k| viewed.contains(k));
let cells: [String; 10] = [
(e.index + 1).to_string(),
e.white().unwrap_or("").to_string(),
@ -615,6 +639,22 @@ impl Library {
];
for (i, text) in cells.into_iter().enumerate() {
row.col(|ui| {
if i == 0 && seen {
// A check mark before the number: the game was opened before.
let c = ui.max_rect().left_center() + vec2(7.0, 0.0);
let stroke = Stroke::new(2.0, Color32::from_rgb(0x62, 0x9c, 0x2e));
ui.painter().line_segment(
[c + vec2(-4.0, 0.0), c + vec2(-1.0, 3.5)],
stroke,
);
ui.painter().line_segment(
[c + vec2(-1.0, 3.5), c + vec2(5.0, -4.0)],
stroke,
);
}
if i == 0 {
ui.add_space(14.0);
}
let mut t = RichText::new(text);
if i == 0 {
t = t.weak();
@ -630,6 +670,19 @@ impl Library {
});
}
let resp = row.response();
if let Some(k) = key {
resp.context_menu(|ui| {
let label = if seen {
tr("Mark as not viewed")
} else {
tr("Mark as viewed")
};
if ui.button(label).clicked() {
toggle_viewed = Some((k, !seen));
ui.close();
}
});
}
if resp.clicked() {
clicked = Some(e.index);
}
@ -638,6 +691,9 @@ impl Library {
}
});
});
if let Some((k, v)) = toggle_viewed {
self.viewed.set(k, v);
}
if let Some(k) = sort_click {
self.sort = if self.sort.0 == k {
(k, !self.sort.1)

View file

@ -15,6 +15,7 @@ mod review;
mod settings;
mod settings_ui;
mod sound;
mod viewed;
mod widgets;
fn main() -> eframe::Result {

View file

@ -321,6 +321,19 @@ fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut Nota
});
}
/// Colour of a move-assessment NAG ($1-$6), the Lichess palette.
pub fn assessment_color(nag: Nag) -> Option<Color32> {
Some(match nag.0 {
1 => Color32::from_rgb(0x62, 0x9c, 0x2e),
2 => Color32::from_rgb(0xe6, 0x8f, 0x00),
3 => Color32::from_rgb(0x22, 0xac, 0x9a),
4 => Color32::from_rgb(0xdf, 0x53, 0x53),
5 => Color32::from_rgb(0xea, 0x45, 0xd8),
6 => Color32::from_rgb(0x56, 0xb4, 0xe9),
_ => return None,
})
}
/// Move-assessment glyph (`!`, `?`, …) with its color, plus position assessments.
fn move_glyph(nags: &[Nag]) -> (String, Option<Color32>) {
let mut s = String::new();
@ -331,15 +344,10 @@ fn move_glyph(nags: &[Nag]) -> (String, Option<Color32>) {
continue;
};
if nag.is_move_assessment() {
color = Some(match nag.0 {
1 => Color32::from_rgb(0x62, 0x9c, 0x2e),
2 => Color32::from_rgb(0xe6, 0x8f, 0x00),
3 => Color32::from_rgb(0x22, 0xac, 0x9a),
4 => Color32::from_rgb(0xdf, 0x53, 0x53),
5 => Color32::from_rgb(0xea, 0x45, 0xd8),
6 => Color32::from_rgb(0x56, 0xb4, 0xe9),
_ => continue,
});
let Some(c) = assessment_color(*nag) else {
continue;
};
color = Some(c);
s.push_str(sym);
} else {
s.push(' ');

View file

@ -368,9 +368,25 @@ impl Review {
}
}
/// The engine's better move for a marked node (an arrow on the board).
pub fn best_move(&self, node: NodeId) -> Option<Move> {
self.marks.get(&node).and_then(|m| m.best.first().copied())
/// After an inaccuracy, mistake or blunder: how the opponent punishes it and how
/// the player best answers, the first two moves of the engine line from the position
/// after the move (shown as arrows, as on Lichess).
pub fn refutation(&self, node: NodeId, game: &Game) -> Vec<Move> {
if !self.marks.contains_key(&node) {
return Vec::new();
}
let (Some(i), Some(pos)) = (
self.line.iter().position(|n| *n == node),
game.position(node),
) else {
return Vec::new();
};
let Some(e) = self.keys.get(i).and_then(|k| self.evals.get(k)) else {
return Vec::new();
};
let (mut moves, _) = parse_pv(pos, &e.pv);
moves.truncate(2);
moves
}
// ----- cache -----------------------------------------------------------------

View file

@ -0,0 +1,88 @@
//! Games the user has opened, remembered by their content (so a mark follows the game
//! when a file is re-sorted or other games are added) in
//! `$XDG_DATA_HOME/chesspenguin/viewed.json`.
use std::collections::HashSet;
use std::path::PathBuf;
#[derive(Default)]
pub struct Viewed {
games: HashSet<u64>,
}
impl Viewed {
fn file() -> Option<PathBuf> {
directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin")
.map(|d| d.data_dir().join("viewed.json"))
}
pub fn load() -> Viewed {
let games = Self::file()
.and_then(|p| std::fs::read(p).ok())
.and_then(|b| serde_json::from_slice::<Vec<u64>>(&b).ok())
.unwrap_or_default();
Viewed {
games: games.into_iter().collect(),
}
}
fn save(&self) {
let Some(path) = Self::file() else { return };
let mut list: Vec<u64> = self.games.iter().copied().collect();
list.sort_unstable();
match serde_json::to_vec(&list) {
Ok(bytes) => {
if let Err(e) = crate::settings::write_atomic(&path, &bytes) {
eprintln!("viewed games: {}: {e}", path.display());
}
}
Err(e) => eprintln!("viewed games: {e}"),
}
}
pub fn contains(&self, key: u64) -> bool {
self.games.contains(&key)
}
pub fn set(&mut self, key: u64, viewed: bool) {
let changed = if viewed {
self.games.insert(key)
} else {
self.games.remove(&key)
};
if changed {
self.save();
}
}
}
/// Identity of a game: FNV-1a 64 of its PGN text without surrounding whitespace.
pub fn key(raw: &[u8]) -> u64 {
let start = raw
.iter()
.position(|b| !b.is_ascii_whitespace())
.unwrap_or(raw.len());
let end = raw
.iter()
.rposition(|b| !b.is_ascii_whitespace())
.map_or(start, |i| i + 1);
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in &raw[start..end.max(start)] {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0100_0000_01b3);
}
h
}
#[cfg(test)]
mod tests {
#[test]
fn key_ignores_surrounding_whitespace() {
assert_eq!(
super::key(b"\n[Event \"x\"]\n1. e4 *\n\n"),
super::key(b"[Event \"x\"]\n1. e4 *")
);
assert_ne!(super::key(b"1. e4 *"), super::key(b"1. d4 *"));
assert_eq!(super::key(b" "), super::key(b""));
}
}