feat: add opening repertoire training

This commit is contained in:
vrubelroman 2026-11-03 00:03:51 +03:00
parent 4eb0822ec6
commit f49aab68fa
36 changed files with 13389 additions and 90 deletions

View file

@ -295,6 +295,10 @@ pub struct App {
prep_quit_ask: bool,
prep_quit_ok: bool,
allow_quit: bool,
#[cfg(not(web))]
repertoire: Option<crate::repertoire_ui::RepertoireUi>,
#[cfg(not(web))]
toast_repertoire: Option<(trainer::repertoire::RepertoireId, String)>,
applied_dark: Option<bool>,
debug: DebugStartup,
}
@ -428,6 +432,18 @@ impl DebugStartup {
impl App {
pub fn new(ctx: &egui::Context) -> Self {
let mut settings = Settings::load();
let repertoire_migrated = settings.migrate_repertoire_flow();
#[cfg(not(web))]
{
if let Ok(language) = std::env::var("CP_LANG")
&& let Some(language) = crate::i18n::Lang::from_locale(&language)
{
settings.language = language;
}
if let Ok(dark) = std::env::var("CP_DARK") {
settings.dark_mode = dark != "0";
}
}
// Before the samples, which are named in this language.
crate::i18n::set_lang(settings.language);
crate::engine_download::clean_leftovers();
@ -482,7 +498,7 @@ impl App {
}
let mut app = Self {
settings,
settings_dirty: false,
settings_dirty: repertoire_migrated,
sound: SoundPlayer::new(),
library,
game: None,
@ -527,6 +543,10 @@ impl App {
desktop,
translation: Default::default(),
allow_quit: false,
#[cfg(not(web))]
repertoire: None,
#[cfg(not(web))]
toast_repertoire: None,
applied_dark: None,
debug: DebugStartup::from_env(),
}
@ -718,7 +738,15 @@ impl App {
};
let now = ctx.input(|i| i.time);
if !self.debug.screenshot_requested {
if ctx.cumulative_frame_nr() == 1 {
let size = std::env::var("CP_SCREENSHOT_SIZE").ok().and_then(|size| {
let (width, height) = size.split_once('x')?;
Some(egui::vec2(width.parse().ok()?, height.parse().ok()?))
});
if let Some(size) = size {
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false));
ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(false));
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size));
} else if ctx.cumulative_frame_nr() == 1 {
ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(true));
}
if now >= self.debug.screenshot_delay {
@ -748,6 +776,84 @@ impl App {
}
fn debug_step(&mut self, ctx: &egui::Context) {
#[cfg(not(web))]
if let Ok(what) = std::env::var("CP_REPERTOIRE") {
static OPEN: std::sync::Once = std::sync::Once::new();
OPEN.call_once(|| {
self.repertoire = Some(crate::repertoire_ui::RepertoireUi::new());
if let Some(screen) = self.repertoire.as_mut() {
screen.debug_open(&what, &mut self.settings);
}
});
}
#[cfg(not(web))]
if let Ok(path) = std::env::var("CP_REPERTOIRE_IMPORT_FILE") {
static IMPORT: std::sync::Once = std::sync::Once::new();
IMPORT.call_once(|| {
if let Some(screen) = self.repertoire.as_mut() {
screen.debug_import(PathBuf::from(path));
}
});
}
#[cfg(not(web))]
if std::env::var_os("CP_REPERTOIRE_EXPORT").is_some() {
static EXPORT: std::sync::Once = std::sync::Once::new();
EXPORT.call_once(|| {
if let Some(screen) = self.repertoire.as_mut() {
screen.debug_export();
}
});
}
#[cfg(not(web))]
if std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some()
&& let Some(screen) = self.repertoire.as_mut()
{
screen.debug_confirm_import(&self.settings);
}
#[cfg(not(web))]
if let Ok(name) = std::env::var("CP_REPERTOIRE_RENAME") {
static RENAME: std::sync::Once = std::sync::Once::new();
if !RENAME.is_completed() {
let mut done = false;
if let Some(screen) = self.repertoire.as_mut() {
done = screen.debug_rename(name, &self.settings);
}
if done {
RENAME.call_once(|| {});
}
}
}
#[cfg(not(web))]
if std::env::var_os("CP_REPERTOIRE_DELETE").is_some() {
static DELETE: std::sync::Once = std::sync::Once::new();
if !DELETE.is_completed() {
let mut done = false;
if let Some(screen) = self.repertoire.as_mut() {
done = screen.debug_delete(&self.settings);
}
if done {
DELETE.call_once(|| {});
}
}
}
#[cfg(not(web))]
if let Ok(moves) = std::env::var("CP_REPERTOIRE_MOVES") {
static MOVES: std::sync::Once = std::sync::Once::new();
MOVES.call_once(|| {
if let Some(screen) = self.repertoire.as_mut() {
screen.debug_moves(&moves);
}
});
}
#[cfg(not(web))]
if std::env::var_os("CP_REPERTOIRE_HINT").is_some() {
static HINT: std::sync::Once = std::sync::Once::new();
HINT.call_once(|| {
if let Some(screen) = self.repertoire.as_mut() {
screen.debug_hint();
}
});
}
if self.debug.prep.is_some()
&& let Some(path) = self.settings.databases.first().cloned()
&& self.library.database(&path).is_some()
@ -841,6 +947,26 @@ impl App {
g.debug_review(ctx, &v);
}
}
#[cfg(not(web))]
{
static ADD_REPERTOIRE: std::sync::Once = std::sync::Once::new();
if let Ok(name) = std::env::var("CP_ADD_REPERTOIRE")
&& !ADD_REPERTOIRE.is_completed()
&& let Some((game, at)) =
self.game.as_ref().and_then(|g| g.debug_repertoire_source())
{
ADD_REPERTOIRE.call_once(|| {});
let title = self.game.as_ref().map(GameView::title).unwrap_or_default();
if let Some(game_view) = self.game.as_mut() {
game_view.suspend();
}
self.analysis.stop();
self.repertoire = Some(crate::repertoire_ui::RepertoireUi::new());
if let Some(screen) = self.repertoire.as_mut() {
screen.debug_add_from_game(game, at, title, name);
}
}
}
if let Some(start) = self.debug.play_from.take() {
self.start_play(ctx, start);
}
@ -1110,6 +1236,10 @@ impl App {
/// A message said once and seldom (a database made for the player): longer in view.
fn toast_for(&mut self, ctx: &egui::Context, msg: impl Into<String>, secs: f64) {
#[cfg(not(web))]
{
self.toast_repertoire = None;
}
self.toast = Some(Toast {
text: msg.into(),
until: ctx.input(|i| i.time) + secs,
@ -2135,6 +2265,87 @@ impl App {
self.game = Some(view);
}
#[cfg(not(web))]
fn open_repertoire(&mut self, ctx: &egui::Context) {
if self.analysis.is_on() {
self.analysis.stop();
self.live_paused = true;
}
if let Some(game) = self.game.as_mut() {
game.suspend();
}
self.repertoire
.get_or_insert_with(crate::repertoire_ui::RepertoireUi::new)
.open_library();
ctx.request_repaint();
}
#[cfg(not(web))]
fn open_repertoire_add(&mut self, ctx: &egui::Context, source: Game, at: chess_core::NodeId) {
self.open_repertoire(ctx);
if let Some(screen) = self.repertoire.as_mut() {
let title = self.game.as_ref().map(GameView::title).unwrap_or_default();
screen.open_add_from_game(source, at, title);
}
}
#[cfg(not(web))]
fn close_repertoire(&mut self, ctx: &egui::Context) {
self.repertoire = None;
if self.game.is_some()
&& std::mem::take(&mut self.live_paused)
&& let Some(config) = self.settings.active_engine().cloned()
{
self.analysis.start(&config, ctx);
}
}
#[cfg(not(web))]
fn show_repertoire(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
self.library.poll();
let Some(mut screen) = self.repertoire.take() else {
return;
};
let actions = screen.show(ui, &mut self.settings);
self.repertoire = Some(screen);
for action in actions {
match action {
crate::repertoire_ui::RepertoireAction::Close => self.close_repertoire(ctx),
crate::repertoire_ui::RepertoireAction::OpenSettings => {
self.settings_ui.open = true
}
crate::repertoire_ui::RepertoireAction::Sound(sound) => self.play(sound),
crate::repertoire_ui::RepertoireAction::Toast(message) => self.toast(ctx, message),
crate::repertoire_ui::RepertoireAction::SettingsChanged => {
self.settings_dirty = true
}
crate::repertoire_ui::RepertoireAction::Added { id, name, report } => {
let title = self.game.as_ref().map(GameView::title).unwrap_or_default();
let text = if report.added_nodes == 0 && report.annotation_changes == 0 {
tr("Already in the repertoire — no changes").to_owned()
} else if report.added_nodes == 0 {
trf(
"The path was already in the repertoire; annotations added: {n}",
&[("n", &report.annotation_changes)],
)
} else {
trf(
"Added to “{name}”: new moves: {added} · matched: {matched}",
&[
("name", &name),
("added", &report.added_nodes),
("matched", &report.merged_nodes.saturating_sub(1)),
],
)
};
self.toast_for(ctx, text, 8.0);
self.toast_repertoire = Some((id, title));
self.close_repertoire(ctx);
}
}
}
}
/// Learning the opening of the current game: the training opens over it.
fn open_training(&mut self, start: crate::train::TrainStart) {
let g = match start
@ -3585,6 +3796,19 @@ impl eframe::App for App {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.prep_quit_ask = true;
}
#[cfg(not(web))]
if ctx.input(|i| i.viewport().close_requested())
&& !self.allow_quit
&& self
.repertoire
.as_ref()
.is_some_and(|screen| screen.has_unsaved())
{
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
if let Some(screen) = self.repertoire.as_mut() {
screen.resolve_unsaved();
}
}
let quitting = !self.prep_quit_ask;
// Quitting: a comment being written goes into the game first, so the question
// about unsaved changes counts it.
@ -3660,7 +3884,11 @@ impl eframe::App for App {
self.analysis.poll();
let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k);
if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) {
#[cfg(not(web))]
let repertoire_visible = self.repertoire.is_some();
#[cfg(web)]
let repertoire_visible = false;
if !repertoire_visible && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) {
self.pick_databases(&ctx);
}
if ctx.input_mut(|i| {
@ -3669,6 +3897,7 @@ impl eframe::App for App {
Key::N,
))
}) && self.game.is_none()
&& !repertoire_visible
&& crate::platform::CAPS.own_databases
{
self.own.then_close = None;
@ -3677,6 +3906,7 @@ impl eframe::App for App {
// In the library a game from the start; on a game's screen the game plays on
// from its position (the game view takes Ctrl+G there).
if self.game.is_none()
&& !repertoire_visible
&& crate::platform::CAPS.play
&& ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G)))
{
@ -3685,10 +3915,12 @@ impl eframe::App for App {
// A browser keeps Ctrl+N for its window: N in the library there (design §4).
let new_game_key = cfg!(web)
&& self.game.is_none()
&& !repertoire_visible
&& !ctx.egui_wants_keyboard_input()
&& ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::N));
if (new_game_key || ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))))
&& self.game.is_none()
&& !repertoire_visible
{
self.new_game();
}
@ -3700,7 +3932,10 @@ impl eframe::App for App {
// dropped before the game is drawn (its header names the target).
let _ = self.current_target();
let shelf = self.shelf_dbs();
if let Some(game) = &mut self.game {
if repertoire_visible {
#[cfg(not(web))]
self.show_repertoire(ui, &ctx);
} else if let Some(game) = &mut self.game {
let input_enabled = self.confirm_close.is_none();
// A database opened for the reference tab arrives here (the library is
// not drawn while a game is shown).
@ -3838,7 +4073,10 @@ impl eframe::App for App {
self.play_next = Some(PlayNext::Dialog(from));
self.request_close(&ctx, intent);
}
GameAction::Train(start) => self.open_training(*start),
#[cfg(not(web))]
GameAction::AddToRepertoire(game, at) => {
self.open_repertoire_add(&ctx, *game, at)
}
GameAction::PlayFrom(from) => self.play_new(&ctx, PlayNext::Dialog(Some(from))),
GameAction::PutAside(intent) => {
let intent = intent.unwrap_or(
@ -4032,6 +4270,8 @@ impl eframe::App for App {
LibraryAction::Preparations => {
self.prep_list = Some(crate::prep_ui::PrepList::new());
}
#[cfg(not(web))]
LibraryAction::OpeningTraining => self.open_repertoire(&ctx),
}
}
}
@ -4159,13 +4399,25 @@ impl eframe::App for App {
}
let mut undo_clicked = false;
#[cfg(not(web))]
let mut open_repertoire = None;
if let Some(t) = &self.toast {
let now = ctx.input(|i| i.time);
if now > t.until {
self.toast = None;
self.own.undo = None;
#[cfg(not(web))]
{
self.toast_repertoire = None;
}
} else {
let (msg, undo) = (t.text.clone(), t.undo && self.own.undo.is_some());
#[cfg(not(web))]
let repertoire_link = self.toast_repertoire.clone();
#[cfg(not(web))]
let has_action = undo || repertoire_link.is_some();
#[cfg(web)]
let has_action = undo;
let area = egui::Area::new(egui::Id::new(TOAST))
.anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0))
.order(egui::Order::Foreground)
@ -4180,11 +4432,15 @@ impl eframe::App for App {
if undo && ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() {
undo_clicked = true;
}
#[cfg(not(web))]
if repertoire_link.is_some() && ui.button(tr("Open")).clicked() {
open_repertoire = repertoire_link.clone();
}
});
});
});
// Under the mouse the toast waits (the button is being reached for).
if undo
if has_action
&& area.response.contains_pointer()
&& let Some(t) = self.toast.as_mut()
{
@ -4197,6 +4453,15 @@ impl eframe::App for App {
self.toast = None;
self.undo_delete(&ctx);
}
#[cfg(not(web))]
if let Some((id, title)) = open_repertoire {
self.toast = None;
self.toast_repertoire = None;
self.open_repertoire(&ctx);
if let Some(screen) = self.repertoire.as_mut() {
screen.open_from_toast(id, title, &self.settings);
}
}
if self.settings_dirty && !ctx.input(|i| i.pointer.any_down()) {
self.settings_dirty = false;

View file

@ -23,6 +23,12 @@ const SAMPLES: [(&str, &str); 2] = [
("Alekhine", include_str!("../../../examples/alekhine.pgn")),
];
#[cfg(test)]
const OPENING_SAMPLES: [(&str, &str); 2] = [
("najdorf", include_str!("../../../examples/najdorf.pgn")),
("spanish", include_str!("../../../examples/spanish.pgn")),
];
fn dir() -> Option<PathBuf> {
crate::platform::examples_dir()
}
@ -116,6 +122,61 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn opening_samples_have_three_legal_records_and_the_requested_branches() {
for (name, text) in OPENING_SAMPLES {
let db = chess_core::PgnDatabase::from_bytes(
text.as_bytes().to_vec(),
None,
&mut |_| {},
&std::sync::atomic::AtomicBool::new(false),
)
.unwrap();
assert_eq!(db.len(), 3, "{name}");
let mut branches = Vec::new();
for index in 0..db.len() {
let parsed = db.load_game(index).unwrap();
assert!(parsed.diagnostics.is_empty(), "{name} #{}", index + 1);
let game = parsed.game;
for tag in ["Event", "Site", "Date", "Round", "White", "Black", "Result"] {
assert!(game.tag(tag).is_some(), "{name} #{index}: {tag}");
}
assert_eq!(game.result().as_str(), "*");
let san: Vec<String> = game
.mainline()
.iter()
.filter_map(|id| game.game_move(*id).map(|mv| mv.san.clone()))
.collect();
let common: &[&str] = if name == "najdorf" {
&[
"e4", "c5", "Nf3", "d6", "d4", "cxd4", "Nxd4", "Nf6", "Nc3", "a6",
]
} else {
&["e4", "e5", "Nf3", "Nc6", "Bb5"]
};
assert!(san.len() >= common.len(), "{name} #{index}: {san:?}");
assert!(
common
.iter()
.zip(&san)
.all(|(expected, actual)| *expected == actual),
"{name} #{index}: {san:?}"
);
branches.push(san);
}
if name == "najdorf" {
assert_eq!(branches[0][10], "Be3");
assert_eq!(branches[1][10], "Bg5");
assert_eq!(branches[2][10], "Be2");
} else {
assert_eq!(branches[0][5], "Nf6");
assert_eq!(branches[1][5], "a6");
assert_eq!(branches[2][5], "a6");
assert_eq!(branches[2][9], "Nxe4");
}
}
}
#[test]
fn the_first_start_writes_the_samples_and_shelves_them() {
let dir = folder("first");

View file

@ -130,8 +130,8 @@ pub enum GameAction {
OpenDatabase(PathBuf),
/// «Play on from here»: the play dialog for this position.
PlayFrom(Box<crate::play::StartFrom>),
/// «Learn the opening up to this move»: the training over this game.
Train(Box<crate::train::TrainStart>),
#[cfg(not(web))]
AddToRepertoire(Box<Game>, NodeId),
Sound(Sound),
CopyText(String, &'static str),
/// Ctrl+S: into the game's own database, else "Add to database…".
@ -1635,7 +1635,10 @@ impl GameView {
} else if let Some((id, NotationCommand::PlayFrom)) = resp.context {
self.play_from(id, actions);
} else if let Some((id, NotationCommand::Train)) = resp.context {
self.train_from(id, actions);
#[cfg(not(web))]
self.add_repertoire_from(id, actions);
#[cfg(web)]
let _ = id;
} else if let Some((id, cmd)) = resp.context {
let result = match cmd {
NotationCommand::Paste
@ -2061,21 +2064,24 @@ impl GameView {
self.play_from(at, actions);
ui.close();
}
}
#[cfg(not(web))]
if self.play.is_none() && crate::platform::CAPS.training {
if !crate::platform::CAPS.play {
ui.separator();
}
let line = crate::train::TrainStart::from_game(&self.game, self.cursor);
if ui
.add_enabled(
line.is_some(),
egui::Button::new(tr("Learn the opening up to this move")),
)
.add_enabled(line.is_some(), egui::Button::new(tr("Add to repertoire…")))
.on_disabled_hover_text(if self.cursor == NodeId::ROOT {
tr("Select the move to learn up to")
tr("Select the move up to which to add")
} else {
tr("The line has a null move (--): it cannot be played on the board")
})
.clicked()
{
let at = self.cursor;
self.train_from(at, actions);
self.add_repertoire_from(at, actions);
ui.close();
}
}
@ -3905,16 +3911,10 @@ impl GameView {
// ----- learning an opening (docs/design/opening-trainer.md) ----------------------
/// «Learn the opening up to this move»: the training opens over this game.
fn train_from(&mut self, at: NodeId, actions: &mut Vec<GameAction>) {
if self.play.is_some() {
return;
}
self.commit_editor();
self.preview = None;
if let Some(mut t) = crate::train::TrainStart::from_game(&self.game, at) {
t.flipped = self.flipped;
actions.push(GameAction::Train(Box::new(t)));
#[cfg(not(web))]
fn add_repertoire_from(&self, at: NodeId, actions: &mut Vec<GameAction>) {
if self.play.is_none() && crate::train::TrainStart::from_game(&self.game, at).is_some() {
actions.push(GameAction::AddToRepertoire(Box::new(self.game.clone()), at));
}
}
@ -4470,6 +4470,12 @@ impl GameView {
Some(t)
}
#[cfg(not(web))]
pub fn debug_repertoire_source(&self) -> Option<(Game, NodeId)> {
crate::train::TrainStart::from_game(&self.game, self.cursor)
.map(|_| (self.game.clone(), self.cursor))
}
/// Dev hook (`CP_TRAIN_MOVES`): moves of the training made as on the board (UCI;
/// a wrong one is a mistake).
pub fn debug_train_moves(&mut self, uci: &str) {

File diff suppressed because it is too large Load diff

View file

@ -45,6 +45,10 @@ mod player_games;
mod prep_saved;
mod prep_ui;
mod reference;
#[cfg(not(web))]
mod repertoire_training;
#[cfg(not(web))]
mod repertoire_ui;
mod review;
mod review_engine;
mod rodent4_download;
@ -147,17 +151,30 @@ pub fn run_native() -> eframe::Result {
graphics::install_panic_hook();
graphics::init_library_log();
let mode = graphics::choose();
let mut viewport = egui::ViewportBuilder::default()
.with_app_id("io.github.vrubelroman.chessPenguin")
.with_title("ChessPenguin")
.with_inner_size([1400.0, 900.0])
.with_min_inner_size([640.0, 480.0])
// X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id.
.with_icon(
eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png"))
.unwrap_or_default(),
);
if let Some((width, height)) = std::env::var("CP_SCREENSHOT_SIZE").ok().and_then(|size| {
let (width, height) = size.split_once('x')?;
Some((width.parse::<f32>().ok()?, height.parse::<f32>().ok()?))
}) {
viewport = viewport
.with_inner_size([width, height])
.with_min_inner_size([width, height])
.with_max_inner_size([width, height])
.with_resizable(false)
.with_fullscreen(false)
.with_maximized(false);
}
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_app_id("io.github.vrubelroman.chessPenguin")
.with_title("ChessPenguin")
.with_inner_size([1400.0, 900.0])
.with_min_inner_size([640.0, 480.0])
// X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id.
.with_icon(
eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png"))
.unwrap_or_default(),
),
viewport,
wgpu_options: graphics::options(mode),
..Default::default()
};

View file

@ -89,6 +89,8 @@ pub enum LibraryAction {
},
/// «🗐 Preparations»: the saved preparations against opponents.
Preparations,
#[cfg(not(web))]
OpeningTraining,
/// «Prepare against…» for a player of this database (opponent-prep.md §2).
PrepareAgainst {
path: PathBuf,
@ -151,7 +153,8 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 {
};
let play = crate::platform::CAPS.play;
let prep = crate::platform::CAPS.prep;
let groups = 1.0 + f32::from(u8::from(play)) + f32::from(u8::from(prep));
let training = crate::platform::CAPS.training;
let groups = 1.0 + f32::from(u8::from(play)) + f32::from(u8::from(prep || training));
texts[..if play { 4 } else { 3 }]
.iter()
.map(|t| button_w(ui, t))
@ -168,6 +171,11 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 {
} else {
0.0
}
+ if training {
button_w(ui, tr("Opening training"))
} else {
0.0
}
+ update.map_or(0.0, |v| button_w(ui, v))
+ groups * GROUP_GAP
}
@ -826,6 +834,15 @@ impl Library {
actions.push(LibraryAction::Preparations);
}
}
#[cfg(not(web))]
if crate::platform::CAPS.training {
if !crate::platform::CAPS.prep {
ui.separator();
}
if ui.button(tr("Opening training")).clicked() {
actions.push(LibraryAction::OpeningTraining);
}
}
}
/// "♞ Play": a game against Maia, a group of its own.

View file

@ -58,7 +58,7 @@ pub enum NotationCommand {
Paste,
/// A game against Maia from this position (docs/design/play-from-position.md).
PlayFrom,
/// Learn the opening up to this move (docs/design/opening-trainer.md).
/// Add the exact path through this move to an opening repertoire.
Train,
}
@ -445,60 +445,57 @@ fn handle_move_response(
out.context = Some((id, NotationCommand::Delete));
ui.close();
}
// Games against the computer and the trainer: not in every version.
if !crate::platform::CAPS.play {
if !crate::platform::CAPS.play && !crate::platform::CAPS.training {
return;
}
ui.separator();
// A finished position has nothing to play.
let over = n.game.position(id).and_then(|p| {
if p.is_checkmate() {
Some(tr("checkmate"))
} else if p.is_stalemate() {
Some(tr("stalemate"))
} else if p.is_insufficient_material() {
Some(tr("neither side can checkmate"))
} else {
None
if crate::platform::CAPS.play {
let over = n.game.position(id).and_then(|p| {
if p.is_checkmate() {
Some(tr("checkmate"))
} else if p.is_stalemate() {
Some(tr("stalemate"))
} else if p.is_insufficient_material() {
Some(tr("neither side can checkmate"))
} else {
None
}
});
let play = ui
.add_enabled(
over.is_none(),
egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"),
)
.on_hover_text(tr("A game against the computer from this position"));
let play = match over {
Some(why) => play.on_disabled_hover_text(crate::i18n::trf(
"The game is over here: {why}",
&[("why", &why)],
)),
None => play,
};
if play.clicked() {
out.context = Some((id, NotationCommand::PlayFrom));
ui.close();
}
});
let play = ui
.add_enabled(
over.is_none(),
egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"),
)
.on_hover_text(tr("A game against the computer from this position"));
let play = match over {
Some(why) => play.on_disabled_hover_text(crate::i18n::trf(
"The game is over here: {why}",
&[("why", &why)],
)),
None => play,
};
if play.clicked() {
out.context = Some((id, NotationCommand::PlayFrom));
ui.close();
}
// Learning the opening: the runs of this line so far on the right.
let runs = crate::train::runs_to(n.game, id);
let label = runs
.filter(|&r| r > 0)
.map(|r| crate::i18n::trf("runs: {n}", &[("n", &r)]))
.unwrap_or_default();
let learn = ui
.add_enabled(
runs.is_some(),
egui::Button::new(tr("Learn the opening up to this move")).shortcut_text(label),
)
.on_hover_text(tr(
"Replay from memory the moves of both sides from the start of the game up to this move",
))
.on_disabled_hover_text(tr(
"The line has a null move (--): it cannot be played on the board",
));
if learn.clicked() {
out.context = Some((id, NotationCommand::Train));
ui.close();
if crate::platform::CAPS.training {
let line = crate::train::TrainStart::from_game(n.game, id);
let add = ui
.add_enabled(
line.is_some(),
egui::Button::new(tr("Add to repertoire…")),
)
.on_hover_text(tr("Add only the path from the start through this move, with its comments and NAGs"))
.on_disabled_hover_text(if id == NodeId::ROOT {
tr("Select the move up to which to add")
} else {
tr("The line has a null move (--): it cannot be played on the board")
});
if add.clicked() {
out.context = Some((id, NotationCommand::Train));
ui.close();
}
}
});
let _ = ui;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,331 @@
use super::*;
use std::sync::atomic::AtomicU64;
use std::time::Duration;
static NEXT_TEST: AtomicU64 = AtomicU64::new(0);
struct Fixture {
ui: RepertoireUi,
settings: Settings,
dir: PathBuf,
id: RepertoireId,
}
impl Fixture {
fn new() -> Self {
let dir = std::env::temp_dir().join(format!(
"cp-repertoire-ui-{}-{}",
std::process::id(),
NEXT_TEST.fetch_add(1, Ordering::Relaxed)
));
let library_store = LibraryStore::new(dir.join("library.json"));
let mut library = Library::default();
let id = library
.create("Async opening", &chess_core::parse_str("1. e4 e5 *").game)
.unwrap();
library_store.save(&mut library).unwrap();
let mut ui =
RepertoireUi::with_stores(library_store, StatsStore::new(dir.join("stats.json")));
let event = ui.rx.recv_timeout(Duration::from_secs(5)).unwrap();
ui.tx.send(event).unwrap();
let mut settings = Settings::default();
ui.poll(&mut settings);
assert!(!ui.indexing);
ui.select(id.clone(), &settings);
Self {
ui,
settings,
dir,
id,
}
}
fn completed_job(&self) -> Event {
self.ui.rx.recv_timeout(Duration::from_secs(5)).unwrap()
}
fn deliver(&mut self, event: Event) {
self.ui.tx.send(event).unwrap();
self.ui.poll(&mut self.settings);
}
fn start(&mut self) {
self.ui.mode = TrainingMode::Both;
self.ui.queue = QueueMode::ReviewInOrder;
self.ui.start(&mut self.settings);
assert!(self.ui.preparing);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
#[test]
fn stale_index_cannot_replace_a_newer_rebuild() {
let mut f = Fixture::new();
f.ui.rebuild_tree();
let old = f.completed_job();
f.ui.rebuild_tree();
let current = f.completed_job();
f.deliver(old);
assert!(f.ui.indexing);
assert!(f.ui.tree.is_none());
assert!(f.ui.trees.is_empty());
f.deliver(current);
assert!(!f.ui.indexing);
assert!(f.ui.tree.is_some());
assert!(f.ui.trees.contains_key(&f.id));
}
#[test]
fn completed_training_start_is_ignored_after_leaving_the_detail_screen() {
let mut f = Fixture::new();
f.start();
let ready = f.completed_job();
f.ui.open_library();
f.deliver(ready);
assert!(!f.ui.preparing);
assert!(!f.ui.detail);
assert!(!f.ui.training_visible);
assert!(f.ui.training.is_none());
assert!(f.ui.error.is_none());
}
#[test]
fn stale_training_start_cannot_cancel_or_replace_a_new_generation() {
let mut f = Fixture::new();
f.start();
let old = f.completed_job();
let old_generation = f.ui.training_generation;
f.ui.open_library();
f.ui.select(f.id.clone(), &f.settings);
f.start();
let current = f.completed_job();
assert!(f.ui.training_generation > old_generation);
f.deliver(old);
f.deliver(Event::TrainingReady(
old_generation,
Err("stale failure".into()),
));
assert!(f.ui.preparing);
assert!(f.ui.training.is_none());
assert!(f.ui.error.is_none());
f.deliver(current);
assert!(!f.ui.preparing);
assert!(f.ui.training_visible);
assert!(f.ui.training.is_some());
}
#[test]
fn async_start_can_finish_a_real_opening_and_persist_its_statistics() {
let mut f = Fixture::new();
f.start();
let ready = f.completed_job();
f.deliver(ready);
assert!(f.ui.training_visible);
f.ui.debug_moves("e2e4 e7e5");
let training = f.ui.training.as_ref().unwrap();
assert!(!training.target_available());
assert!(!training.has_unsaved());
let saved = f.ui.stats_store.load().unwrap();
assert_eq!(
saved.runs(&f.id, TrainingMode::Both).unwrap().completions,
1
);
assert_eq!(saved.move_stats.iter().map(|s| s.correct).sum::<u32>(), 2);
assert!(f.ui.error.is_none());
}
#[test]
fn due_count_reuses_pending_work_across_minutes_and_discards_evicted_results() {
let mut f = Fixture::new();
let key = CountKey {
id: f.id.clone(),
mode: TrainingMode::White,
queue: QueueMode::SpacedRepetition,
policy: SrsPolicy::Due,
scope: TrainingScope::whole(),
library_revision: f.ui.library.revision,
stats_revision: f.ui.stats.revision,
minute: now() / 60 - 2,
};
f.ui.counts.insert(key.clone(), None);
assert_eq!(
f.ui.task_count(&f.id, key.mode, key.queue, key.policy, &key.scope),
None
);
assert_eq!(f.ui.counts.len(), 1);
assert_eq!(f.ui.counts.get(&key), Some(&None));
assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty)));
f.deliver(Event::Counted(key.clone(), 0));
assert_eq!(f.ui.counts.get(&key), Some(&Some(0)));
f.ui.counts.clear();
f.deliver(Event::Counted(key, 99));
assert!(f.ui.counts.is_empty());
}
#[test]
fn both_and_review_counts_have_no_minute_expiry_and_complete_asynchronously() {
let mut f = Fixture::new();
for (mode, queue, expected) in [
(TrainingMode::Both, QueueMode::LeastRecent, 1),
(TrainingMode::White, QueueMode::ReviewInOrder, 1),
] {
let scope = TrainingScope::whole();
assert_eq!(
f.ui.task_count(&f.id, mode, queue, SrsPolicy::Due, &scope),
None
);
assert!(
f.ui.counts
.keys()
.filter(|k| k.mode == mode)
.all(|k| k.minute == 0)
);
let event = f.completed_job();
f.deliver(event);
assert_eq!(
f.ui.task_count(&f.id, mode, queue, SrsPolicy::Due, &scope),
Some(expected)
);
assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty)));
}
}
#[test]
#[ignore = "manual corpus import and indexing measurement"]
fn corpus_import_preserves_source_and_reports_real_outcome() {
for filename in ["The Ruy Lopez - Move by Move.pgn", "Alekhin.pgn"] {
println!("File: {filename}");
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../pgnFilesforExample")
.join(filename);
let before = std::fs::read(&path).unwrap();
let cancelled = AtomicBool::new(false);
let started = std::time::Instant::now();
let imported = read_import(&path, None, Library::default(), &cancelled);
let import_elapsed = started.elapsed();
assert_eq!(
std::fs::read(&path).unwrap(),
before,
"import changed source bytes"
);
// Count the source independently, including records after any rejected one.
let db = PgnDatabase::from_bytes(before.clone(), None, &mut |_| {}, &cancelled).unwrap();
let source_nodes: usize = (0..db.len())
.map(|index| {
db.load_game(index)
.unwrap()
.game
.attached_nodes()
.len()
.saturating_sub(1)
})
.sum();
println!(
"Corpus: {} bytes; {} records; {} parsed source move nodes",
before.len(),
db.len(),
source_nodes
);
match imported {
Ok(preview) => {
let repertoire = preview.library.repertoire(&preview.id).unwrap();
let started = std::time::Instant::now();
let tree = RepertoireTree::new(repertoire);
let index_elapsed = started.elapsed();
let nodes = tree.game().attached_nodes().len().saturating_sub(1);
assert_eq!(preview.records, db.len());
assert!(nodes > 0);
println!(
"IMPORTED: {} records; {} merged move nodes; import {:?}; index {:?}; combined {:?}",
preview.records,
nodes,
import_elapsed,
index_elapsed,
import_elapsed + index_elapsed
);
}
Err(reason) => {
assert!(!reason.is_empty());
println!(
"REJECTED (no repertoire imported, indexing not run): {reason}; read_import elapsed {import_elapsed:?}"
);
}
}
if filename == "Alekhin.pgn" {
let fixture = Fixture::new();
let subset_path = fixture.dir.join("Alekhin-first-200.pgn");
let subset = (0..200)
.map(|index| db.raw_text(index).expect("source record exists"))
.collect::<Vec<_>>()
.join("\n\n");
std::fs::write(&subset_path, subset.as_bytes()).unwrap();
let started = std::time::Instant::now();
let mut preview = read_import(&subset_path, None, Library::default(), &cancelled)
.expect("the first 200 complete source records must import successfully");
let subset_import_elapsed = started.elapsed();
assert_eq!(preview.records, 200);
let repertoire = preview.library.repertoire(&preview.id).unwrap();
let started = std::time::Instant::now();
let tree = RepertoireTree::new(repertoire);
let index_elapsed = started.elapsed();
let nodes = tree.game().attached_nodes().len().saturating_sub(1);
let canonical = tree.game().canonical_tree();
let started = std::time::Instant::now();
let store = LibraryStore::new(fixture.dir.join("corpus-library.json"));
store.save(&mut preview.library).unwrap();
let loaded = store.load().unwrap();
assert_eq!(
loaded
.repertoire(&preview.id)
.unwrap()
.game()
.canonical_tree(),
canonical
);
let roundtrip_elapsed = started.elapsed();
assert_eq!(std::fs::read(&subset_path).unwrap(), subset.as_bytes());
assert!(nodes > 0);
println!(
"IMPORTED TEMP FIRST 200: {} bytes; {} merged move nodes; import {:?}; index {:?}; import+index {:?}; save/reload+canonical verification {:?}",
subset.len(),
nodes,
subset_import_elapsed,
index_elapsed,
subset_import_elapsed + index_elapsed,
roundtrip_elapsed
);
}
assert_eq!(
std::fs::read(&path).unwrap(),
before,
"corpus check changed source bytes"
);
}
}
#[test]
fn expanding_and_collapsing_variations_only_changes_visible_rows() {
let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Bc4 *").game;
let before = game.canonical_tree();
let e4 = game.children(NodeId::ROOT)[0];
let e5 = game.children(e4)[0];
let c5 = game.children(e4)[1];
let bc4 = game.children(e5)[0];
let nf3 = game.children(c5)[0];
let mut expanded = HashSet::new();
let collapsed = tree_rows(&game, &expanded);
assert_eq!(collapsed, vec![(e4, 0), (e5, 0), (bc4, 0)]);
expanded.insert(e4);
let visible = tree_rows(&game, &expanded);
assert_eq!(visible, vec![(e4, 0), (e5, 0), (bc4, 0), (c5, 1), (nf3, 1)]);
assert_eq!(game.canonical_tree(), before);
expanded.remove(&e4);
assert_eq!(tree_rows(&game, &expanded), collapsed);
assert_eq!(game.canonical_tree(), before);
}

View file

@ -159,6 +159,15 @@ pub struct Settings {
pub players: Vec<crate::player_games::Player>,
/// Preparing against an opponent (docs/design/opponent-prep.md).
pub prep: PrepSettings,
pub repertoire_flow_version: u8,
/// Last training mode and queue of each opening repertoire.
pub repertoire_modes: std::collections::HashMap<
String,
(
trainer::repertoire::TrainingMode,
trainer::repertoire::QueueMode,
),
>,
}
/// Options of the opponent preparation; its engine search is the game analysis's.
@ -226,11 +235,23 @@ impl Default for Settings {
rating: None,
play: Default::default(),
prep: PrepSettings::default(),
repertoire_modes: Default::default(),
repertoire_flow_version: 0,
}
}
}
impl Settings {
pub fn migrate_repertoire_flow(&mut self) -> bool {
if self.repertoire_flow_version >= 1 {
return false;
}
for (_, queue) in self.repertoire_modes.values_mut() {
*queue = trainer::repertoire::QueueMode::Practice;
}
self.repertoire_flow_version = 1;
true
}
pub fn config_dir() -> Option<PathBuf> {
crate::platform::config_dir()
}
@ -364,3 +385,28 @@ mod tests {
assert!(json.contains("\"book\":\"/db/book.pgn\""));
}
}
#[cfg(test)]
mod repertoire_flow_tests {
use super::*;
use trainer::repertoire::{QueueMode, TrainingMode};
#[test]
fn old_training_preferences_migrate_once_without_resetting_color_or_custom_settings() {
let mut settings = Settings::default();
settings.repertoire_modes.insert(
"old".into(),
(TrainingMode::Black, QueueMode::SpacedRepetition),
);
assert!(settings.migrate_repertoire_flow());
assert_eq!(
settings.repertoire_modes["old"],
(TrainingMode::Black, QueueMode::Practice)
);
settings.repertoire_modes.get_mut("old").unwrap().1 = QueueMode::SpacedRepetition;
assert!(!settings.migrate_repertoire_flow());
assert_eq!(
settings.repertoire_modes["old"].1,
QueueMode::SpacedRepetition
);
}
}