feat: simplify opening variation training
This commit is contained in:
parent
f49aab68fa
commit
71ca5ad9e6
14 changed files with 1571 additions and 637 deletions
|
|
@ -16266,6 +16266,17 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Ikkala tomon",
|
||||
"Екі тарап",
|
||||
],
|
||||
[
|
||||
"Variants",
|
||||
"Варианты",
|
||||
"Variantes",
|
||||
"Varianten",
|
||||
"Variantes",
|
||||
"Varianti",
|
||||
"Variantes",
|
||||
"Variantlar",
|
||||
"Варианттар",
|
||||
],
|
||||
[
|
||||
"No targets in this mode",
|
||||
"В этом режиме нет целей",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::time::Duration;
|
||||
use std::{sync::mpsc, time::Duration};
|
||||
|
||||
use chess_core::shakmaty::{Chess, Color, Move, Position, Square, uci::UciMove};
|
||||
use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2};
|
||||
|
|
@ -28,10 +28,17 @@ struct Flash {
|
|||
wrong: bool,
|
||||
}
|
||||
|
||||
struct NextPathJob {
|
||||
generation: u64,
|
||||
rx: mpsc::Receiver<(u64, Result<TrainingSession, String>)>,
|
||||
}
|
||||
|
||||
pub struct TrainingUi {
|
||||
repertoire: Repertoire,
|
||||
saved_stats: StatsData,
|
||||
discard_requested: bool,
|
||||
next_job: Option<NextPathJob>,
|
||||
next_generation: u64,
|
||||
mode: TrainingMode,
|
||||
queue_mode: QueueMode,
|
||||
policy: SrsPolicy,
|
||||
|
|
@ -71,7 +78,55 @@ impl TrainingUi {
|
|||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new_random(
|
||||
repertoire: &Repertoire,
|
||||
mode: TrainingMode,
|
||||
stats: StatsData,
|
||||
store: StatsStore,
|
||||
flipped: bool,
|
||||
) -> Result<Self, SessionError> {
|
||||
let session = TrainingSession::new_random(repertoire, mode, stats, now())?;
|
||||
let task_origin = if session.scope().include_context {
|
||||
repertoire.game().start().position().clone()
|
||||
} else {
|
||||
session.scope_start_position().clone()
|
||||
};
|
||||
let mut training = Self {
|
||||
repertoire: repertoire.clone(),
|
||||
saved_stats: session.stats().clone(),
|
||||
discard_requested: false,
|
||||
next_job: None,
|
||||
next_generation: 0,
|
||||
mode,
|
||||
queue_mode: QueueMode::Practice,
|
||||
policy: SrsPolicy::Due,
|
||||
session,
|
||||
store,
|
||||
board: BoardState::default(),
|
||||
flipped: match mode {
|
||||
TrainingMode::White => false,
|
||||
TrainingMode::Black => true,
|
||||
TrainingMode::Both => flipped,
|
||||
},
|
||||
positions: Vec::new(),
|
||||
position_path_len: usize::MAX,
|
||||
position_task_start: usize::MAX,
|
||||
task_start: 0,
|
||||
task_origin,
|
||||
view_ply: 0,
|
||||
flash: None,
|
||||
hint: None,
|
||||
message: None,
|
||||
save_error: None,
|
||||
confirm_discard: false,
|
||||
completed_targets: 0,
|
||||
target_limit: usize::MAX,
|
||||
};
|
||||
training.save();
|
||||
Ok(training)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments, dead_code)]
|
||||
pub fn new_with_policy(
|
||||
repertoire: &Repertoire,
|
||||
scope: TrainingScope,
|
||||
|
|
@ -98,6 +153,8 @@ impl TrainingUi {
|
|||
repertoire: repertoire.clone(),
|
||||
saved_stats,
|
||||
discard_requested: false,
|
||||
next_job: None,
|
||||
next_generation: 0,
|
||||
mode,
|
||||
queue_mode,
|
||||
policy,
|
||||
|
|
@ -200,7 +257,11 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn play(&mut self, mv: Move) {
|
||||
if self.is_finished() || self.flash.is_some() || self.save_error.is_some() {
|
||||
if self.is_finished()
|
||||
|| self.flash.is_some()
|
||||
|| self.save_error.is_some()
|
||||
|| self.next_job.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let mut after = self.session.position().clone();
|
||||
|
|
@ -247,7 +308,7 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn restart(&mut self) {
|
||||
if self.save_error.is_some() {
|
||||
if self.save_error.is_some() || self.next_job.is_some() {
|
||||
return;
|
||||
}
|
||||
match self.session.restart(now()) {
|
||||
|
|
@ -257,15 +318,81 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn next_path(&mut self) {
|
||||
if self.save_error.is_some() || !self.is_path_practice() {
|
||||
if self.save_error.is_some() || self.next_job.is_some() || !self.is_path_practice() {
|
||||
return;
|
||||
}
|
||||
match self.session.next_path(now()) {
|
||||
Ok(()) => self.after_run_reset(),
|
||||
let prepared = match self.session.prepare_next_path() {
|
||||
Ok(prepared) => prepared,
|
||||
Err(error) => {
|
||||
self.message = Some(error.to_string());
|
||||
return;
|
||||
}
|
||||
};
|
||||
let repertoire = self.repertoire.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.next_generation = self.next_generation.wrapping_add(1);
|
||||
let generation = self.next_generation;
|
||||
self.next_job = Some(NextPathJob { generation, rx });
|
||||
if let Err(error) = crate::platform::spawn("repertoire-training-next", move || {
|
||||
let result = prepared
|
||||
.run(&repertoire, now())
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = tx.send((generation, result));
|
||||
}) {
|
||||
self.next_job = None;
|
||||
self.message = Some(error.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_next(&mut self) {
|
||||
let (generation, result) = {
|
||||
let Some(job) = &self.next_job else {
|
||||
return;
|
||||
};
|
||||
match job.rx.try_recv() {
|
||||
Ok(result) => result,
|
||||
Err(mpsc::TryRecvError::Empty) => return,
|
||||
Err(mpsc::TryRecvError::Disconnected) => (
|
||||
job.generation,
|
||||
Err("next-path worker stopped without a result".to_owned()),
|
||||
),
|
||||
}
|
||||
};
|
||||
self.apply_next(generation, result);
|
||||
}
|
||||
|
||||
fn apply_next(&mut self, generation: u64, result: Result<TrainingSession, String>) {
|
||||
if generation != self.next_generation
|
||||
|| self
|
||||
.next_job
|
||||
.as_ref()
|
||||
.is_none_or(|job| job.generation != generation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.next_job = None;
|
||||
match result {
|
||||
Ok(session) => {
|
||||
self.session = session;
|
||||
self.after_run_reset();
|
||||
self.save();
|
||||
}
|
||||
Err(error) => self.message = Some(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn deliver_next(&mut self) {
|
||||
let (generation, result) = self
|
||||
.next_job
|
||||
.as_ref()
|
||||
.expect("a pending next-path job")
|
||||
.rx
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.expect("next-path worker result");
|
||||
self.apply_next(generation, result);
|
||||
}
|
||||
|
||||
fn after_run_reset(&mut self) {
|
||||
self.completed_targets = 0;
|
||||
self.target_limit = target_count(
|
||||
|
|
@ -314,7 +441,7 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn keyboard(&mut self, ui: &Ui, actions: &mut Vec<TrainingAction>) {
|
||||
if ui.ctx().egui_wants_keyboard_input() {
|
||||
if ui.ctx().egui_wants_keyboard_input() || self.next_job.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut command = None;
|
||||
|
|
@ -423,6 +550,7 @@ impl TrainingUi {
|
|||
interactive: !self.is_finished()
|
||||
&& self.flash.is_none()
|
||||
&& self.save_error.is_none()
|
||||
&& self.next_job.is_none()
|
||||
&& self.view_ply + 1 == self.positions.len(),
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
|
|
@ -523,6 +651,15 @@ impl TrainingUi {
|
|||
});
|
||||
}
|
||||
|
||||
fn preparing(&self, ui: &mut Ui) {
|
||||
card(ui, false).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spinner();
|
||||
ui.label(tr("Preparing the tree…"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn result(&mut self, ui: &mut Ui, actions: &mut Vec<TrainingAction>) {
|
||||
card(ui, false).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
|
|
@ -535,6 +672,9 @@ impl TrainingUi {
|
|||
.strong()
|
||||
.size(17.0),
|
||||
);
|
||||
if let Some(message) = &self.message {
|
||||
ui.label(message);
|
||||
}
|
||||
if self.is_path_practice() {
|
||||
let played = self
|
||||
.session
|
||||
|
|
@ -591,94 +731,6 @@ impl TrainingUi {
|
|||
});
|
||||
}
|
||||
|
||||
fn notation(&mut self, ui: &mut Ui) {
|
||||
let mut clicked = None;
|
||||
let mut marks: std::collections::HashMap<(String, String), (u32, bool)> =
|
||||
std::collections::HashMap::new();
|
||||
for attempt in self.session.attempts() {
|
||||
let mark = marks
|
||||
.entry((
|
||||
attempt.position_fen4.clone(),
|
||||
if self.mode == TrainingMode::Both {
|
||||
String::new()
|
||||
} else {
|
||||
attempt.expected_uci.clone()
|
||||
},
|
||||
))
|
||||
.or_default();
|
||||
mark.0 += u32::from(!attempt.correct);
|
||||
mark.1 |= attempt.hinted;
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink(false)
|
||||
.show(ui, |ui| {
|
||||
let path = &self.session.path()[self.task_start..];
|
||||
let mut index = 0;
|
||||
while index < path.len() {
|
||||
let white = self
|
||||
.positions
|
||||
.get(index)
|
||||
.is_some_and(|p| p.turn() == Color::White);
|
||||
let number = self.positions.get(index).map_or(1, |p| p.fullmoves().get());
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.add_sized(
|
||||
[36.0, 24.0],
|
||||
egui::Label::new(
|
||||
RichText::new(if white {
|
||||
format!("{number}.")
|
||||
} else {
|
||||
format!("{number}…")
|
||||
})
|
||||
.weak(),
|
||||
),
|
||||
);
|
||||
for color in [Color::White, Color::Black] {
|
||||
if index >= path.len() {
|
||||
break;
|
||||
}
|
||||
let is_white = self
|
||||
.positions
|
||||
.get(index)
|
||||
.is_some_and(|p| p.turn() == Color::White);
|
||||
if is_white != (color == Color::White) {
|
||||
continue;
|
||||
}
|
||||
let played = &path[index];
|
||||
let global = self.task_start + index;
|
||||
let mut text = played.san.clone();
|
||||
if let Some((mistakes, hinted)) = marks.get(&(
|
||||
played.position_before.clone(),
|
||||
if self.mode == TrainingMode::Both {
|
||||
String::new()
|
||||
} else {
|
||||
played.uci.clone()
|
||||
},
|
||||
)) {
|
||||
if *mistakes > 0 {
|
||||
text.push_str(&format!(" ×{mistakes}"));
|
||||
}
|
||||
if *hinted {
|
||||
text.push_str(" *");
|
||||
}
|
||||
}
|
||||
let response = ui.selectable_label(self.view_ply == global + 1, text);
|
||||
let was_clicked = response.clicked();
|
||||
if played.automatic {
|
||||
response.on_hover_text(tr("Automatic move/context"));
|
||||
}
|
||||
if was_clicked {
|
||||
clicked = Some(global + 1 - self.task_start);
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
if let Some(ply) = clicked {
|
||||
self.view_ply = ply;
|
||||
}
|
||||
}
|
||||
|
||||
fn save_strip(&mut self, ui: &mut Ui) {
|
||||
let Some(error) = self.save_error.clone() else {
|
||||
return;
|
||||
|
|
@ -716,7 +768,11 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, settings: &Settings, name: &str) -> Vec<TrainingAction> {
|
||||
self.poll_next();
|
||||
let mut actions = Vec::new();
|
||||
if self.next_job.is_some() {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(50));
|
||||
}
|
||||
if let Some(flash) = &self.flash {
|
||||
let left = flash
|
||||
.until
|
||||
|
|
@ -731,7 +787,10 @@ impl TrainingUi {
|
|||
egui::Panel::top("repertoire_training_header").show(ui, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.button(format!("← {}", tr("Back to repertoire")))
|
||||
.add_enabled(
|
||||
self.next_job.is_none(),
|
||||
egui::Button::new(format!("← {}", tr("Back to repertoire"))),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
if self.save_error.is_some() {
|
||||
|
|
@ -765,6 +824,10 @@ impl TrainingUi {
|
|||
};
|
||||
crate::widgets::check_panel("repertoire_training_side", &side.response);
|
||||
egui::CentralPanel::default().show(ui, |ui| self.board(ui, settings, &mut actions));
|
||||
if self.next_job.is_some() {
|
||||
self.discard_requested = false;
|
||||
actions.retain(|action| !matches!(action, TrainingAction::Back));
|
||||
}
|
||||
if self.save_error.is_some() && !self.discard_requested {
|
||||
if actions
|
||||
.iter()
|
||||
|
|
@ -781,63 +844,66 @@ impl TrainingUi {
|
|||
}
|
||||
|
||||
fn side(&mut self, ui: &mut Ui, actions: &mut Vec<TrainingAction>) {
|
||||
let notation_height = (ui.available_height() - 230.0).max(120.0);
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_training_controls")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 8.0;
|
||||
self.save_strip(ui);
|
||||
if self.is_finished() {
|
||||
if self.next_job.is_some() {
|
||||
self.preparing(ui);
|
||||
} else if self.is_finished() {
|
||||
self.result(ui, actions);
|
||||
} else {
|
||||
self.task_card(ui);
|
||||
self.user_card(ui);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
for (label, ply) in [
|
||||
("⏮", 0),
|
||||
("◀", self.view_ply.saturating_sub(1)),
|
||||
(
|
||||
"▶",
|
||||
(self.view_ply + 1).min(self.positions.len().saturating_sub(1)),
|
||||
),
|
||||
("⏭", self.positions.len().saturating_sub(1)),
|
||||
] {
|
||||
if self.next_job.is_none() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
for (label, ply) in [
|
||||
("⏮", 0),
|
||||
("◀", self.view_ply.saturating_sub(1)),
|
||||
(
|
||||
"▶",
|
||||
(self.view_ply + 1).min(self.positions.len().saturating_sub(1)),
|
||||
),
|
||||
("⏭", self.positions.len().saturating_sub(1)),
|
||||
] {
|
||||
if ui
|
||||
.add_sized([30.0, 26.0], egui::Button::new(label))
|
||||
.clicked()
|
||||
{
|
||||
self.view_ply = ply;
|
||||
}
|
||||
}
|
||||
if ui
|
||||
.add_sized([30.0, 26.0], egui::Button::new(label))
|
||||
.add_sized([30.0, 26.0], egui::Button::new("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.view_ply = ply;
|
||||
self.flipped = !self.flipped;
|
||||
}
|
||||
}
|
||||
if ui
|
||||
.add_sized([30.0, 26.0], egui::Button::new("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.flipped = !self.flipped;
|
||||
}
|
||||
if !self.is_finished() && ui.button(tr("↻ Restart")).clicked() {
|
||||
self.restart();
|
||||
}
|
||||
});
|
||||
if self.view_ply + 1 < self.positions.len()
|
||||
if !self.is_finished() && ui.button(tr("↻ Restart")).clicked() {
|
||||
self.restart();
|
||||
}
|
||||
});
|
||||
}
|
||||
if self.next_job.is_none()
|
||||
&& self.view_ply + 1 < self.positions.len()
|
||||
&& ui
|
||||
.link(tr("Viewing an earlier position · back to training — End"))
|
||||
.clicked()
|
||||
{
|
||||
self.go_end();
|
||||
}
|
||||
ui.separator();
|
||||
ui.allocate_ui(vec2(ui.available_width(), notation_height), |ui| {
|
||||
self.notation(ui);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn debug_hint(&mut self) {
|
||||
if self.next_job.is_some() {
|
||||
return;
|
||||
}
|
||||
if let Some(candidate) = self.session.hint(now()) {
|
||||
self.hint = move_squares(&candidate);
|
||||
self.save();
|
||||
|
|
@ -848,7 +914,13 @@ impl TrainingUi {
|
|||
for text in moves.split_whitespace() {
|
||||
match text {
|
||||
"hint" => self.debug_hint(),
|
||||
"next" => self.next_path(),
|
||||
"next" => {
|
||||
self.next_path();
|
||||
#[cfg(test)]
|
||||
if self.next_job.is_some() {
|
||||
self.deliver_next();
|
||||
}
|
||||
}
|
||||
"repeat" => self.restart(),
|
||||
_ => {}
|
||||
}
|
||||
|
|
@ -1176,6 +1248,164 @@ mod tests {
|
|||
assert_board_matches_session(&training);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_next_saves_its_cursor_without_a_move_and_repeat_does_not_advance_it() {
|
||||
let fixture = training(
|
||||
"1. e4 e5 (1... c5) 2. Nf3 (2. c4) *",
|
||||
TrainingMode::Both,
|
||||
"random-cursor-save",
|
||||
);
|
||||
let mut random = TrainingUi::new_random(
|
||||
&fixture.repertoire,
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
fixture.store.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(random.save_error.is_none());
|
||||
assert_eq!(random.session.queue_mode(), QueueMode::Practice);
|
||||
let initial = serde_json::to_value(random.session.stats()).unwrap();
|
||||
assert_eq!(initial["random_practice_cursors"][0]["position"], 1);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.store.load().unwrap()).unwrap(),
|
||||
initial
|
||||
);
|
||||
|
||||
random.debug_moves("next");
|
||||
assert!(random.save_error.is_none());
|
||||
assert!(random.session.attempts().is_empty());
|
||||
assert_board_matches_session(&random);
|
||||
let next = serde_json::to_value(random.session.stats()).unwrap();
|
||||
assert_eq!(next["random_practice_cursors"][0]["position"], 2);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.store.load().unwrap()).unwrap(),
|
||||
next
|
||||
);
|
||||
|
||||
random.debug_moves("repeat");
|
||||
assert_eq!(serde_json::to_value(random.session.stats()).unwrap(), next);
|
||||
assert_board_matches_session(&random);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_next_blocks_duplicate_work_and_applies_delivery_exactly_once() {
|
||||
let fixture = training(
|
||||
"1. e4 e5 (1... c5) 2. Nf3 (2. c4) *",
|
||||
TrainingMode::Both,
|
||||
"async-next-delivery",
|
||||
);
|
||||
let mut random = TrainingUi::new_random(
|
||||
&fixture.repertoire,
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
fixture.store.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
random.debug_moves("");
|
||||
let old_path = random.session.path().to_vec();
|
||||
let old_scope = random.session.scope().clone();
|
||||
let old_positions = random.positions.clone();
|
||||
let old_stats = serde_json::to_vec(random.session.stats()).unwrap();
|
||||
let generation = random.next_generation;
|
||||
|
||||
random.next_path();
|
||||
assert!(random.next_job.is_some());
|
||||
assert_eq!(random.next_generation, generation.wrapping_add(1));
|
||||
assert_eq!(random.session.path(), old_path);
|
||||
assert_eq!(random.positions, old_positions);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(random.session.stats()).unwrap(),
|
||||
old_stats
|
||||
);
|
||||
random.next_path();
|
||||
assert_eq!(random.next_generation, generation.wrapping_add(1));
|
||||
random.restart();
|
||||
assert_eq!(random.session.scope(), &old_scope);
|
||||
assert_eq!(random.session.path(), old_path);
|
||||
|
||||
random.deliver_next();
|
||||
assert!(random.next_job.is_none());
|
||||
assert!(random.session.attempts().is_empty());
|
||||
assert_board_matches_session(&random);
|
||||
let delivered_stats = serde_json::to_value(random.session.stats()).unwrap();
|
||||
assert_eq!(delivered_stats["random_practice_cursors"][0]["position"], 2);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.store.load().unwrap()).unwrap(),
|
||||
delivered_stats
|
||||
);
|
||||
let delivered_path = random.session.path().to_vec();
|
||||
random.poll_next();
|
||||
assert_eq!(random.session.path(), delivered_path);
|
||||
assert_eq!(
|
||||
serde_json::to_value(random.session.stats()).unwrap(),
|
||||
delivered_stats
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_next_computation_error_preserves_the_current_session() {
|
||||
let mut training = training_queue(
|
||||
"1. e4 e5 *",
|
||||
TrainingMode::Both,
|
||||
"async-next-error",
|
||||
QueueMode::Practice,
|
||||
TrainingScope::from_prefix(vec!["e2e4".into()]),
|
||||
);
|
||||
training.debug_moves("");
|
||||
let old_path = training.session.path().to_vec();
|
||||
let old_scope = training.session.scope().clone();
|
||||
let old_positions = training.positions.clone();
|
||||
let old_stats = serde_json::to_vec(training.session.stats()).unwrap();
|
||||
training.repertoire.pgn = parse_str("1. d4 d5 *").game.to_pgn();
|
||||
|
||||
training.next_path();
|
||||
training.deliver_next();
|
||||
assert!(training.next_job.is_none());
|
||||
assert!(
|
||||
training
|
||||
.message
|
||||
.as_ref()
|
||||
.is_some_and(|message| message.contains("invalid training scope"))
|
||||
);
|
||||
assert_eq!(training.session.path(), old_path);
|
||||
assert_eq!(training.session.scope(), &old_scope);
|
||||
assert_eq!(training.positions, old_positions);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(training.session.stats()).unwrap(),
|
||||
old_stats
|
||||
);
|
||||
assert_board_matches_session(&training);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_next_save_error_remains_visible_after_successful_computation() {
|
||||
let fixture = training(
|
||||
"1. e4 e5 (1... c5) 2. Nf3 *",
|
||||
TrainingMode::Both,
|
||||
"async-next-save-error",
|
||||
);
|
||||
let mut random = TrainingUi::new_random(
|
||||
&fixture.repertoire,
|
||||
TrainingMode::Both,
|
||||
StatsData::default(),
|
||||
fixture.store.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let mut external = random.store.load().unwrap();
|
||||
random.store.save(&mut external).unwrap();
|
||||
|
||||
random.next_path();
|
||||
random.deliver_next();
|
||||
assert!(random.next_job.is_none());
|
||||
assert!(random.save_error.is_some());
|
||||
assert!(random.has_unsaved());
|
||||
assert_eq!(random.session.stats().revision, 1);
|
||||
assert_board_matches_session(&random);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_mainline_scope_end_is_accepted() {
|
||||
let game =
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
|
|
@ -10,8 +10,8 @@ use chess_core::shakmaty::Color;
|
|||
use chess_core::{Game, NodeId, PgnDatabase, Severity};
|
||||
use egui::{Key, Modifiers, RichText, Ui};
|
||||
use trainer::repertoire::{
|
||||
Library, LibraryStore, MergeReport, MoveKey, QueueMode, Repertoire, RepertoireId,
|
||||
RepertoireTree, SrsPolicy, StatsData, StatsStore, TrainingMode, TrainingScope, fen4,
|
||||
Library, LibraryStore, MergeReport, QueueMode, Repertoire, RepertoireId, RepertoireTree,
|
||||
SrsPolicy, StatsData, StatsStore, TrainingMode, TrainingScope, fen4,
|
||||
};
|
||||
|
||||
use crate::board::{BoardState, BoardView};
|
||||
|
|
@ -46,6 +46,11 @@ struct ImportPreview {
|
|||
target: Option<RepertoireId>,
|
||||
}
|
||||
|
||||
struct LibraryLoadError {
|
||||
library: Option<Library>,
|
||||
message: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct CountKey {
|
||||
id: RepertoireId,
|
||||
|
|
@ -83,8 +88,6 @@ pub struct RepertoireUi {
|
|||
error: Option<String>,
|
||||
selected: Option<RepertoireId>,
|
||||
detail: bool,
|
||||
active: NodeId,
|
||||
scope: TrainingScope,
|
||||
tree: Option<Arc<RepertoireTree>>,
|
||||
trees: HashMap<RepertoireId, Arc<RepertoireTree>>,
|
||||
counts: HashMap<CountKey, Option<usize>>,
|
||||
|
|
@ -92,13 +95,9 @@ pub struct RepertoireUi {
|
|||
indexing: bool,
|
||||
preparing: bool,
|
||||
training_generation: u64,
|
||||
rows: Vec<(NodeId, usize)>,
|
||||
expanded: HashSet<NodeId>,
|
||||
cleanup: Option<RepertoireId>,
|
||||
board: BoardState,
|
||||
mode: TrainingMode,
|
||||
queue: QueueMode,
|
||||
policy: SrsPolicy,
|
||||
training: Option<TrainingUi>,
|
||||
training_visible: bool,
|
||||
return_to_game: Option<String>,
|
||||
|
|
@ -121,9 +120,9 @@ impl RepertoireUi {
|
|||
Self::with_stores(library_store, stats_store)
|
||||
}
|
||||
fn with_stores(library_store: LibraryStore, stats_store: StatsStore) -> Self {
|
||||
let (library, library_error) = match library_store.load() {
|
||||
let (library, library_error) = match load_library(&library_store) {
|
||||
Ok(data) => (data, None),
|
||||
Err(e) => (Library::default(), Some(e.to_string())),
|
||||
Err(e) => (e.library.unwrap_or_default(), Some(e.message)),
|
||||
};
|
||||
let (stats, stats_error) = match stats_store.load() {
|
||||
Ok(data) => (data, None),
|
||||
|
|
@ -141,8 +140,6 @@ impl RepertoireUi {
|
|||
error: None,
|
||||
selected,
|
||||
detail: false,
|
||||
active: NodeId::ROOT,
|
||||
scope: TrainingScope::whole(),
|
||||
tree: None,
|
||||
trees: HashMap::new(),
|
||||
counts: HashMap::new(),
|
||||
|
|
@ -150,13 +147,9 @@ impl RepertoireUi {
|
|||
indexing: false,
|
||||
preparing: false,
|
||||
training_generation: 0,
|
||||
rows: Vec::new(),
|
||||
expanded: HashSet::new(),
|
||||
cleanup: None,
|
||||
board: BoardState::default(),
|
||||
mode: TrainingMode::White,
|
||||
queue: QueueMode::Practice,
|
||||
policy: SrsPolicy::Due,
|
||||
training: None,
|
||||
training_visible: false,
|
||||
return_to_game: None,
|
||||
|
|
@ -217,16 +210,11 @@ impl RepertoireUi {
|
|||
self.preparing = false;
|
||||
self.selected = Some(id.clone());
|
||||
self.detail = true;
|
||||
self.active = NodeId::ROOT;
|
||||
self.expanded.clear();
|
||||
self.scope = TrainingScope::whole();
|
||||
let (mode, queue) = settings
|
||||
self.mode = settings
|
||||
.repertoire_modes
|
||||
.get(id.as_str())
|
||||
.copied()
|
||||
.unwrap_or((TrainingMode::White, QueueMode::Practice));
|
||||
self.mode = mode;
|
||||
self.queue = queue;
|
||||
.map(|(mode, _)| *mode)
|
||||
.unwrap_or(TrainingMode::White);
|
||||
self.update_selected_tree();
|
||||
}
|
||||
fn update_selected_tree(&mut self) {
|
||||
|
|
@ -235,13 +223,9 @@ impl RepertoireUi {
|
|||
.as_ref()
|
||||
.and_then(|id| self.trees.get(id))
|
||||
.cloned();
|
||||
self.rows = self
|
||||
.tree
|
||||
.as_ref()
|
||||
.map(|tree| tree_rows(tree.game(), &self.expanded))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
fn rebuild_tree(&mut self) {
|
||||
normalize_library(&mut self.library);
|
||||
self.counts.clear();
|
||||
self.index_generation += 1;
|
||||
self.indexing = true;
|
||||
|
|
@ -266,6 +250,7 @@ impl RepertoireUi {
|
|||
if self.library_error.is_some() {
|
||||
return false;
|
||||
}
|
||||
normalize_library(&mut library);
|
||||
match self.library_store.save(&mut library) {
|
||||
Ok(()) => {
|
||||
self.library = library;
|
||||
|
|
@ -312,19 +297,11 @@ impl RepertoireUi {
|
|||
else {
|
||||
return;
|
||||
};
|
||||
let queue = if self.mode == TrainingMode::Both && self.queue == QueueMode::SpacedRepetition
|
||||
{
|
||||
QueueMode::LeastRecent
|
||||
} else {
|
||||
self.queue
|
||||
};
|
||||
if self.preparing {
|
||||
return;
|
||||
}
|
||||
let repertoire = r.clone();
|
||||
let scope = self.scope.clone();
|
||||
let mode = self.mode;
|
||||
let policy = self.policy;
|
||||
let stats = self.stats.clone();
|
||||
let store = self.stats_store.clone();
|
||||
let tx = self.tx.clone();
|
||||
|
|
@ -332,21 +309,12 @@ impl RepertoireUi {
|
|||
let generation = self.training_generation;
|
||||
settings
|
||||
.repertoire_modes
|
||||
.insert(r.id.to_string(), (mode, queue));
|
||||
.insert(r.id.to_string(), (mode, QueueMode::Practice));
|
||||
self.preparing = true;
|
||||
if let Err(error) = crate::platform::spawn("repertoire-training-start", move || {
|
||||
let result = TrainingUi::new_with_policy(
|
||||
&repertoire,
|
||||
scope,
|
||||
mode,
|
||||
queue,
|
||||
stats,
|
||||
store,
|
||||
false,
|
||||
policy,
|
||||
)
|
||||
.map(Box::new)
|
||||
.map_err(|e| e.to_string());
|
||||
let result = TrainingUi::new_random(&repertoire, mode, stats, store, false)
|
||||
.map(Box::new)
|
||||
.map_err(|e| e.to_string());
|
||||
let _ = tx.send(Event::TrainingReady(generation, result));
|
||||
}) {
|
||||
self.preparing = false;
|
||||
|
|
@ -490,10 +458,7 @@ impl RepertoireUi {
|
|||
self.debug_moves(&moves);
|
||||
}
|
||||
}
|
||||
Ok(_) => {
|
||||
self.error =
|
||||
Some(tr("No enabled moves for this mode and depth").to_owned())
|
||||
}
|
||||
Ok(_) => self.error = Some(tr("No targets in this mode").to_owned()),
|
||||
Err(error) => self.error = Some(error),
|
||||
}
|
||||
}
|
||||
|
|
@ -637,13 +602,19 @@ impl RepertoireUi {
|
|||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(e).color(ui.visuals().error_fg_color));
|
||||
if ui.button(tr("Retry")).clicked() {
|
||||
match self.library_store.load() {
|
||||
match load_library(&self.library_store) {
|
||||
Ok(data) => {
|
||||
self.library = data;
|
||||
self.library_error = None;
|
||||
self.rebuild_tree();
|
||||
}
|
||||
Err(e) => self.library_error = Some(e.to_string()),
|
||||
Err(e) => {
|
||||
if let Some(library) = e.library {
|
||||
self.library = library;
|
||||
self.rebuild_tree();
|
||||
}
|
||||
self.library_error = Some(e.message);
|
||||
}
|
||||
}
|
||||
match self.stats_store.load() {
|
||||
Ok(data) => {
|
||||
|
|
@ -778,21 +749,23 @@ impl RepertoireUi {
|
|||
} else {
|
||||
110.0
|
||||
}))
|
||||
.column(egui_extras::Column::exact(if compact {
|
||||
82.0
|
||||
} else {
|
||||
110.0
|
||||
}))
|
||||
.column(egui_extras::Column::exact(if compact {
|
||||
82.0
|
||||
} else {
|
||||
130.0
|
||||
}))
|
||||
.column(egui_extras::Column::exact(28.0))
|
||||
.header(30.0, |mut header| {
|
||||
for key in ["Name", "White: due", "Black: due", "Both sides", ""] {
|
||||
for (column, key) in ["Name", "Variants", ""].into_iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate());
|
||||
if column == 1 {
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(key)).strong())
|
||||
.truncate(),
|
||||
);
|
||||
},
|
||||
);
|
||||
} else {
|
||||
ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate());
|
||||
}
|
||||
});
|
||||
}
|
||||
})
|
||||
|
|
@ -814,33 +787,15 @@ impl RepertoireUi {
|
|||
open = Some(r.id.clone());
|
||||
}
|
||||
});
|
||||
for mode in [TrainingMode::White, TrainingMode::Black] {
|
||||
row.col(|ui| {
|
||||
match self.task_count(
|
||||
&r.id,
|
||||
mode,
|
||||
QueueMode::SpacedRepetition,
|
||||
SrsPolicy::Due,
|
||||
&TrainingScope::whole(),
|
||||
) {
|
||||
Some(n) => {
|
||||
ui.label(n.to_string());
|
||||
}
|
||||
None => {
|
||||
ui.spinner();
|
||||
ui.ctx().request_repaint_after(
|
||||
std::time::Duration::from_millis(100),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
row.col(|ui| {
|
||||
ui.label(
|
||||
self.stats
|
||||
.runs(&r.id, TrainingMode::Both)
|
||||
.map_or_else(|| "—".to_owned(), |s| s.completions.to_string()),
|
||||
let count = self.task_count(
|
||||
&r.id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&TrainingScope::whole(),
|
||||
);
|
||||
count_cell(ui, count);
|
||||
});
|
||||
row.col(|ui| {
|
||||
ui.menu_button("⋯", |ui| {
|
||||
|
|
@ -991,7 +946,7 @@ impl RepertoireUi {
|
|||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.add_enabled_ui(!self.preparing, |ui| {
|
||||
let previous = (self.mode, self.queue);
|
||||
let previous_mode = self.mode;
|
||||
ui.add(egui::Label::new(RichText::new(&r.name).heading()).truncate())
|
||||
.on_hover_text(&r.name);
|
||||
ui.add_space(6.0);
|
||||
|
|
@ -1004,101 +959,13 @@ impl RepertoireUi {
|
|||
}
|
||||
});
|
||||
ui.separator();
|
||||
egui::Grid::new("repertoire_options")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 8.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(tr("Depth"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let mut depth = r.max_plies;
|
||||
let mut unlimited = depth == u32::MAX;
|
||||
let mut changed =
|
||||
ui.checkbox(&mut unlimited, tr("No limit")).changed();
|
||||
if !unlimited {
|
||||
if depth == u32::MAX {
|
||||
depth = 20;
|
||||
}
|
||||
changed |= ui
|
||||
.add(
|
||||
egui::DragValue::new(&mut depth)
|
||||
.range(1..=10000)
|
||||
.suffix(format!(" {}", tr("half-moves"))),
|
||||
)
|
||||
.changed();
|
||||
}
|
||||
if changed {
|
||||
let mut library = self.library.clone();
|
||||
if let Some(r) = library.repertoire_mut(id) {
|
||||
r.max_plies = if unlimited { u32::MAX } else { depth };
|
||||
}
|
||||
self.persist(library);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Color"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for mode in
|
||||
[TrainingMode::White, TrainingMode::Black, TrainingMode::Both]
|
||||
{
|
||||
ui.selectable_value(&mut self.mode, mode, mode_label(mode));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Mode"));
|
||||
egui::ComboBox::from_id_salt("repertoire_queue")
|
||||
.width(180.0)
|
||||
.wrap_mode(egui::TextWrapMode::Truncate)
|
||||
.selected_text(queue_label(self.queue))
|
||||
.show_ui(ui, |ui| {
|
||||
for queue in [
|
||||
QueueMode::Practice,
|
||||
QueueMode::SpacedRepetition,
|
||||
] {
|
||||
if self.mode != TrainingMode::Both
|
||||
|| queue != QueueMode::SpacedRepetition
|
||||
{
|
||||
ui.selectable_value(
|
||||
&mut self.queue,
|
||||
queue,
|
||||
queue_label(queue),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
if self.mode == TrainingMode::Both
|
||||
&& self.queue != QueueMode::Practice
|
||||
{
|
||||
self.queue = QueueMode::Practice;
|
||||
}
|
||||
ui.end_row();
|
||||
if self.mode != TrainingMode::Both
|
||||
&& self.queue == QueueMode::SpacedRepetition
|
||||
{
|
||||
ui.label(tr("Spaced schedule"));
|
||||
egui::ComboBox::from_id_salt("srs_policy")
|
||||
.selected_text(policy_label(self.policy))
|
||||
.show_ui(ui, |ui| {
|
||||
for policy in [
|
||||
SrsPolicy::Due,
|
||||
SrsPolicy::Introduce,
|
||||
SrsPolicy::EarlyReview,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut self.policy,
|
||||
policy,
|
||||
policy_label(policy),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Color"));
|
||||
for mode in [TrainingMode::White, TrainingMode::Black, TrainingMode::Both] {
|
||||
ui.selectable_value(&mut self.mode, mode, mode_label(mode));
|
||||
}
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(tr(if self.queue == QueueMode::Practice {
|
||||
"Play a variation from start to finish. Any enabled move is accepted; the program plays the other side."
|
||||
} else {
|
||||
"Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded."
|
||||
}));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
let available = self.available_tasks();
|
||||
if available.is_none() {
|
||||
|
|
@ -1108,17 +975,9 @@ impl RepertoireUi {
|
|||
}
|
||||
let count_label =
|
||||
available.map_or_else(|| "…".to_owned(), |n| n.to_string());
|
||||
ui.label(format!(
|
||||
"{}: {count_label}",
|
||||
if self.mode == TrainingMode::Both || self.queue == QueueMode::Practice {
|
||||
tr("Paths")
|
||||
} else {
|
||||
tr("Moves")
|
||||
}
|
||||
));
|
||||
ui.label(format!("{}: {count_label}", tr("Paths")));
|
||||
let ready = !self.preparing
|
||||
&& (available.is_some_and(|n| n > 0)
|
||||
|| ((self.mode == TrainingMode::Both || self.queue == QueueMode::Practice) && self.tree.is_some()))
|
||||
&& available.is_some_and(|n| n > 0)
|
||||
&& self.stats_error.is_none()
|
||||
&& self.library_error.is_none();
|
||||
if ui
|
||||
|
|
@ -1128,56 +987,30 @@ impl RepertoireUi {
|
|||
self.start(settings);
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
if self.mode != TrainingMode::Both
|
||||
&& self.queue == QueueMode::SpacedRepetition
|
||||
&& self.policy == SrsPolicy::Due
|
||||
&& available == Some(0)
|
||||
&& ui.button(tr("Introduce new moves")).clicked()
|
||||
{
|
||||
self.policy = SrsPolicy::Introduce;
|
||||
}
|
||||
});
|
||||
if matches!(self.queue, QueueMode::ReviewInOrder | QueueMode::LeastRecent) {
|
||||
ui.label(tr("Early review · schedule unchanged"));
|
||||
}
|
||||
if previous != (self.mode, self.queue) {
|
||||
if previous_mode != self.mode {
|
||||
settings
|
||||
.repertoire_modes
|
||||
.insert(id.to_string(), (self.mode, self.queue));
|
||||
.insert(id.to_string(), (self.mode, QueueMode::Practice));
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(if self.scope.prefix.is_empty() {
|
||||
tr("Whole repertoire").to_owned()
|
||||
} else {
|
||||
format!("{}: {}", tr("Scope"), self.scope.prefix.join(" "))
|
||||
});
|
||||
if ui.button(tr("Reset scope")).clicked() {
|
||||
self.scope = TrainingScope::whole();
|
||||
}
|
||||
if self.active != NodeId::ROOT
|
||||
&& ui.button(tr("Use selected as scope")).clicked()
|
||||
&& let Some(path) = self.tree.as_ref().and_then(|t| t.path(self.active))
|
||||
{
|
||||
self.scope = TrainingScope::from_prefix(path.to_vec());
|
||||
}
|
||||
if ui.button(tr("End scope here")).clicked()
|
||||
&& let Some(path) = self.tree.as_ref().and_then(|t| t.path(self.active))
|
||||
{
|
||||
self.scope.end_prefix = Some(path.to_vec());
|
||||
}
|
||||
});
|
||||
if self.import.is_some() {
|
||||
self.import_preview(ui, settings);
|
||||
}
|
||||
ui.separator();
|
||||
self.tree_panel(ui, r);
|
||||
self.statistics_panel(ui, r);
|
||||
});
|
||||
});
|
||||
}
|
||||
fn available_tasks(&mut self) -> Option<usize> {
|
||||
let id = self.selected.clone()?;
|
||||
self.task_count(&id, self.mode, self.queue, self.policy, &self.scope.clone())
|
||||
self.task_count(
|
||||
&id,
|
||||
self.mode,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&TrainingScope::whole(),
|
||||
)
|
||||
}
|
||||
fn task_count(
|
||||
&mut self,
|
||||
|
|
@ -1223,7 +1056,19 @@ impl RepertoireUi {
|
|||
});
|
||||
self.counts.insert(key.clone(), None);
|
||||
if let Err(error) = crate::platform::spawn("repertoire-count", move || {
|
||||
let count = if mode == TrainingMode::Both || queue == QueueMode::Practice {
|
||||
let count = if queue == QueueMode::Practice {
|
||||
use chess_core::shakmaty::Position;
|
||||
let start_turn = tree.position(tree.root()).map(|position| position.turn());
|
||||
let mut count = 0usize;
|
||||
tree.visit_training_paths(&job_key.scope, |moves| {
|
||||
if start_turn.is_some_and(|turn| path_has_mode_move(mode, turn, moves.len())) {
|
||||
count = count.saturating_add(1);
|
||||
}
|
||||
std::ops::ControlFlow::Continue(())
|
||||
})
|
||||
.map(|()| count)
|
||||
.unwrap_or(0)
|
||||
} else if mode == TrainingMode::Both {
|
||||
tree.training_path_count(&job_key.scope).unwrap_or(0)
|
||||
} else if queue == QueueMode::SpacedRepetition {
|
||||
stats
|
||||
|
|
@ -1245,7 +1090,7 @@ impl RepertoireUi {
|
|||
let Some(tree) = &self.tree else {
|
||||
return;
|
||||
};
|
||||
let Some(pos) = tree.game().position(self.active) else {
|
||||
let Some(pos) = tree.game().position(NodeId::ROOT) else {
|
||||
return;
|
||||
};
|
||||
let side = ui.available_width().min(ui.available_height()).max(80.0);
|
||||
|
|
@ -1279,103 +1124,10 @@ impl RepertoireUi {
|
|||
.show(ui, &mut self.board);
|
||||
});
|
||||
}
|
||||
fn tree_panel(&mut self, ui: &mut Ui, r: &Repertoire) {
|
||||
let Some(tree) = &self.tree else {
|
||||
fn statistics_panel(&mut self, ui: &mut Ui, r: &Repertoire) {
|
||||
if self.tree.is_none() {
|
||||
return;
|
||||
};
|
||||
let game = tree.game();
|
||||
let mut select = None;
|
||||
let mut toggle = None;
|
||||
let mut expand = None;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong(tr("Tree"));
|
||||
if ui
|
||||
.selectable_label(self.active == NodeId::ROOT, tr("Start position"))
|
||||
.clicked()
|
||||
{
|
||||
select = Some(NodeId::ROOT);
|
||||
}
|
||||
});
|
||||
let rows = &self.rows;
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_moves")
|
||||
.max_height(260.0)
|
||||
.show_rows(ui, 24.0, rows.len(), |ui, range| {
|
||||
for index in range {
|
||||
let (node, depth) = rows[index];
|
||||
let path = tree.path(node).unwrap_or(&[]);
|
||||
let disabled = r.is_prefix_disabled(path);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space((depth.min(10) as f32) * 12.0);
|
||||
let mut enabled = !disabled;
|
||||
if ui
|
||||
.checkbox(&mut enabled, "")
|
||||
.on_hover_text(tr("Enable for training"))
|
||||
.changed()
|
||||
{
|
||||
toggle = Some((path.to_vec(), !enabled));
|
||||
}
|
||||
if game.children(node).len() > 1 {
|
||||
let is_open = self.expanded.contains(&node);
|
||||
if ui
|
||||
.add_sized(
|
||||
[18.0, 20.0],
|
||||
egui::Button::new(if is_open { "▾" } else { "▸" }).frame(false),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
expand = Some(node);
|
||||
}
|
||||
} else {
|
||||
ui.add_space(18.0);
|
||||
}
|
||||
let label = game.move_label(node).unwrap_or_default();
|
||||
let text = if disabled {
|
||||
RichText::new(crate::san::show(&label)).weak()
|
||||
} else {
|
||||
RichText::new(crate::san::show(&label))
|
||||
};
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(100.0, 22.0),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
if ui.selectable_label(self.active == node, text).clicked() {
|
||||
select = Some(node);
|
||||
}
|
||||
},
|
||||
);
|
||||
if disabled {
|
||||
ui.label(RichText::new(tr(" ∅ not trained")).weak());
|
||||
}
|
||||
if path.len() > r.max_plies as usize {
|
||||
ui.label(RichText::new(format!(">{}", r.max_plies)).weak());
|
||||
}
|
||||
if !self.scope.prefix.is_empty() && path == self.scope.prefix {
|
||||
ui.label("▶");
|
||||
}
|
||||
let transpositions = tree.transpositions(node);
|
||||
if transpositions.len() > 1 {
|
||||
ui.menu_button(format!("⇄ {}", transpositions.len()), |ui| {
|
||||
for alternate in transpositions {
|
||||
if ui.button(prefix_label(game, *alternate)).clicked() {
|
||||
select = Some(*alternate);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(n) = game.node(node) {
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
RichText::new(n.comments_after().join(" ")).weak(),
|
||||
)
|
||||
.truncate(),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_statistics")
|
||||
.show(ui, |ui| {
|
||||
|
|
@ -1401,110 +1153,7 @@ impl RepertoireUi {
|
|||
format_time(run.last)
|
||||
));
|
||||
}
|
||||
if let Some(n) = game.node(self.active) {
|
||||
ui.label(
|
||||
n.comments_before()
|
||||
.iter()
|
||||
.chain(n.comments_after())
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
);
|
||||
ui.label(
|
||||
n.nags()
|
||||
.iter()
|
||||
.map(|n| format!("${}", n.0))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" "),
|
||||
);
|
||||
}
|
||||
if self.active != NodeId::ROOT
|
||||
&& let Some(before) = game.position_before(self.active)
|
||||
{
|
||||
let uci = tree
|
||||
.path(self.active)
|
||||
.and_then(|p| p.last())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let key = MoveKey {
|
||||
repertoire_id: r.id.clone(),
|
||||
mode: self.mode,
|
||||
position_fen4: fen4(before),
|
||||
expected_uci: if self.mode == TrainingMode::Both {
|
||||
String::new()
|
||||
} else {
|
||||
uci
|
||||
},
|
||||
};
|
||||
ui.strong(tr("Move statistics"));
|
||||
if let Some(stats) = self.stats.get(&key) {
|
||||
ui.label(format!(
|
||||
"{}: {} · {}: {} · {}: {}",
|
||||
tr("Correct"),
|
||||
stats.correct,
|
||||
tr("Wrong"),
|
||||
stats.wrong,
|
||||
tr("Hints"),
|
||||
stats.hints
|
||||
));
|
||||
ui.label(format!(
|
||||
"{}: {}",
|
||||
tr("Last attempt"),
|
||||
format_time(stats.last_attempt)
|
||||
));
|
||||
if self.mode != TrainingMode::Both {
|
||||
ui.label(format!("{}: {}", tr("Next review"), format_time(stats.due)));
|
||||
}
|
||||
} else {
|
||||
ui.label(tr("No attempts in the selected mode"));
|
||||
}
|
||||
}
|
||||
if self.mode == TrainingMode::Both {
|
||||
let prefix = tree.path(self.active).unwrap_or(&[]);
|
||||
ui.strong(tr("Branch statistics"));
|
||||
for path in
|
||||
self.stats.path_stats.iter().filter(|p| {
|
||||
p.key.repertoire_id == r.id && p.key.path.starts_with(prefix)
|
||||
})
|
||||
{
|
||||
ui.label(format!(
|
||||
"{} · {}: {} · {}",
|
||||
path.key.path.join(" "),
|
||||
tr("Completions"),
|
||||
path.completions,
|
||||
format_time(path.last_completion)
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(node) = select {
|
||||
self.active = node;
|
||||
for parent in game.path(node) {
|
||||
self.expanded.insert(parent);
|
||||
}
|
||||
}
|
||||
if let Some(node) = expand
|
||||
&& !self.expanded.remove(&node)
|
||||
{
|
||||
self.expanded.insert(node);
|
||||
}
|
||||
if select.is_some() || expand.is_some() {
|
||||
self.rows = tree_rows(game, &self.expanded);
|
||||
}
|
||||
if let Some((path, disabled)) = toggle {
|
||||
let mut library = self.library.clone();
|
||||
if let Some(rep) = library.repertoire_mut(&r.id) {
|
||||
if !disabled && !rep.disabled_prefixes.contains(&path) {
|
||||
self.error = Some(tr("Enable the parent branch first").to_owned());
|
||||
return;
|
||||
}
|
||||
if let Err(e) = rep.set_prefix_disabled(&path, disabled) {
|
||||
self.error = Some(e.to_string());
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.persist(library);
|
||||
}
|
||||
}
|
||||
fn show_add(&mut self, ui: &mut Ui, actions: &mut Vec<RepertoireAction>) {
|
||||
let Some(mut add) = self.add.take() else {
|
||||
|
|
@ -1634,7 +1283,6 @@ impl RepertoireUi {
|
|||
"black" => TrainingMode::Black,
|
||||
_ => TrainingMode::Both,
|
||||
};
|
||||
self.queue = QueueMode::Practice;
|
||||
self.start(settings);
|
||||
}
|
||||
_ => {}
|
||||
|
|
@ -1731,43 +1379,56 @@ fn read_import(
|
|||
target,
|
||||
})
|
||||
}
|
||||
fn tree_rows(game: &Game, expanded: &HashSet<NodeId>) -> Vec<(NodeId, usize)> {
|
||||
let mut rows = Vec::new();
|
||||
let mut stack: Vec<_> = game
|
||||
.children(NodeId::ROOT)
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|id| (*id, 0))
|
||||
.collect();
|
||||
while let Some((id, depth)) = stack.pop() {
|
||||
rows.push((id, depth));
|
||||
for (index, child) in game.children(id).iter().enumerate().rev() {
|
||||
if index == 0 || expanded.contains(&id) {
|
||||
stack.push((*child, depth + usize::from(index != 0)));
|
||||
}
|
||||
}
|
||||
fn path_has_mode_move(mode: TrainingMode, start_turn: Color, plies: usize) -> bool {
|
||||
match mode.user_color() {
|
||||
Some(color) => plies > usize::from(start_turn != color),
|
||||
None => plies > 0,
|
||||
}
|
||||
rows
|
||||
}
|
||||
fn count_cell(ui: &mut Ui, count: Option<usize>) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if let Some(count) = count {
|
||||
ui.label(count.to_string());
|
||||
} else {
|
||||
ui.spinner();
|
||||
ui.ctx()
|
||||
.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
});
|
||||
}
|
||||
fn now() -> i64 {
|
||||
web_time::SystemTime::now()
|
||||
.duration_since(web_time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as i64)
|
||||
}
|
||||
fn queue_label(q: QueueMode) -> &'static str {
|
||||
tr(match q {
|
||||
QueueMode::Practice => "Play through variations",
|
||||
QueueMode::SpacedRepetition => "Review individual moves",
|
||||
QueueMode::ReviewInOrder => "Review in order",
|
||||
QueueMode::LeastRecent => "Least recent and unseen first",
|
||||
})
|
||||
fn load_library(store: &LibraryStore) -> Result<Library, LibraryLoadError> {
|
||||
let mut library = store.load().map_err(|error| LibraryLoadError {
|
||||
library: None,
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
if normalize_library(&mut library)
|
||||
&& let Err(error) = store.save(&mut library)
|
||||
{
|
||||
return Err(LibraryLoadError {
|
||||
library: Some(library),
|
||||
message: error.to_string(),
|
||||
});
|
||||
}
|
||||
Ok(library)
|
||||
}
|
||||
fn policy_label(p: SrsPolicy) -> &'static str {
|
||||
tr(match p {
|
||||
SrsPolicy::Due => "Review due moves",
|
||||
SrsPolicy::Introduce => "Introduce new moves",
|
||||
SrsPolicy::EarlyReview => "Review future moves early",
|
||||
})
|
||||
fn normalize_library(library: &mut Library) -> bool {
|
||||
let mut changed = false;
|
||||
for repertoire in &mut library.repertoires {
|
||||
if repertoire.max_plies != u32::MAX {
|
||||
repertoire.max_plies = u32::MAX;
|
||||
changed = true;
|
||||
}
|
||||
if !repertoire.disabled_prefixes.is_empty() {
|
||||
repertoire.disabled_prefixes.clear();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
fn prefix_label(game: &Game, at: NodeId) -> String {
|
||||
game.path(at)
|
||||
|
|
|
|||
|
|
@ -50,8 +50,7 @@ impl Fixture {
|
|||
}
|
||||
|
||||
fn start(&mut self) {
|
||||
self.ui.mode = TrainingMode::Both;
|
||||
self.ui.queue = QueueMode::ReviewInOrder;
|
||||
self.ui.mode = TrainingMode::White;
|
||||
self.ui.start(&mut self.settings);
|
||||
assert!(self.ui.preparing);
|
||||
}
|
||||
|
|
@ -63,6 +62,127 @@ impl Drop for Fixture {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_persists_migration_of_legacy_training_limits() {
|
||||
let f = Fixture::new();
|
||||
let store = LibraryStore::new(f.dir.join("legacy-limits.json"));
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create("Legacy limits", &chess_core::parse_str("1. e4 e5 *").game)
|
||||
.unwrap();
|
||||
let repertoire = library.repertoire_mut(&id).unwrap();
|
||||
repertoire.max_plies = 1;
|
||||
repertoire
|
||||
.set_prefix_disabled(&["e2e4".to_owned()], true)
|
||||
.unwrap();
|
||||
let pgn = repertoire.pgn.clone();
|
||||
store.save(&mut library).unwrap();
|
||||
|
||||
let ui = RepertoireUi::with_stores(
|
||||
store.clone(),
|
||||
StatsStore::new(f.dir.join("legacy-stats.json")),
|
||||
);
|
||||
assert!(ui.library_error.is_none(), "{:?}", ui.library_error);
|
||||
let saved = store.load().unwrap();
|
||||
for library in [&ui.library, &saved] {
|
||||
let repertoire = library.repertoire(&id).unwrap();
|
||||
assert_eq!(repertoire.max_plies, u32::MAX);
|
||||
assert!(repertoire.disabled_prefixes.is_empty());
|
||||
assert_eq!(repertoire.pgn, pgn);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_write_failure_keeps_the_loaded_library_available() {
|
||||
let f = Fixture::new();
|
||||
let store = LibraryStore::new(f.dir.join("migration-failure.json"));
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create(
|
||||
"Read only migration",
|
||||
&chess_core::parse_str("1. e4 e5 *").game,
|
||||
)
|
||||
.unwrap();
|
||||
let repertoire = library.repertoire_mut(&id).unwrap();
|
||||
repertoire.max_plies = 1;
|
||||
repertoire
|
||||
.set_prefix_disabled(&["e2e4".to_owned()], true)
|
||||
.unwrap();
|
||||
store.save(&mut library).unwrap();
|
||||
let lock = f.dir.join("migration-failure.json.lock");
|
||||
std::fs::remove_file(&lock).unwrap();
|
||||
std::fs::create_dir(lock).unwrap();
|
||||
|
||||
let ui = RepertoireUi::with_stores(
|
||||
store.clone(),
|
||||
StatsStore::new(f.dir.join("migration-failure-stats.json")),
|
||||
);
|
||||
assert!(ui.library_error.is_some());
|
||||
let migrated = ui.library.repertoire(&id).unwrap();
|
||||
assert_eq!(migrated.max_plies, u32::MAX);
|
||||
assert!(migrated.disabled_prefixes.is_empty());
|
||||
let on_disk = store.load().unwrap();
|
||||
let unchanged = on_disk.repertoire(&id).unwrap();
|
||||
assert_eq!(unchanged.max_plies, 1);
|
||||
assert_eq!(unchanged.disabled_prefixes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn practice_count_requires_a_move_for_the_selected_color() {
|
||||
let mut f = Fixture::new();
|
||||
let mut library = f.ui.library.clone();
|
||||
let id = library
|
||||
.create("White only", &chess_core::parse_str("1. e4 *").game)
|
||||
.unwrap();
|
||||
assert!(f.ui.persist(library));
|
||||
f.deliver(f.completed_job());
|
||||
|
||||
for (mode, expected) in [
|
||||
(TrainingMode::White, 1),
|
||||
(TrainingMode::Black, 0),
|
||||
(TrainingMode::Both, 1),
|
||||
] {
|
||||
let scope = TrainingScope::whole();
|
||||
assert_eq!(
|
||||
f.ui.task_count(&id, mode, QueueMode::Practice, SrsPolicy::Due, &scope),
|
||||
None
|
||||
);
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.task_count(&id, mode, QueueMode::Practice, SrsPolicy::Due, &scope),
|
||||
Some(expected)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_normalizes_limits_before_saving_and_indexing() {
|
||||
let mut f = Fixture::new();
|
||||
let mut library = f.ui.library.clone();
|
||||
let repertoire = library.repertoire_mut(&f.id).unwrap();
|
||||
repertoire.max_plies = 1;
|
||||
repertoire
|
||||
.set_prefix_disabled(&["e2e4".to_owned()], true)
|
||||
.unwrap();
|
||||
let pgn = repertoire.pgn.clone();
|
||||
|
||||
assert!(f.ui.persist(library));
|
||||
let saved = f.ui.library_store.load().unwrap();
|
||||
for library in [&f.ui.library, &saved] {
|
||||
let repertoire = library.repertoire(&f.id).unwrap();
|
||||
assert_eq!(repertoire.max_plies, u32::MAX);
|
||||
assert!(repertoire.disabled_prefixes.is_empty());
|
||||
assert_eq!(repertoire.pgn, pgn);
|
||||
}
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.trees[&f.id]
|
||||
.training_path_count(&TrainingScope::whole())
|
||||
.unwrap(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_index_cannot_replace_a_newer_rebuild() {
|
||||
let mut f = Fixture::new();
|
||||
|
|
@ -132,13 +252,47 @@ fn async_start_can_finish_a_real_opening_and_persist_its_statistics() {
|
|||
assert!(!training.has_unsaved());
|
||||
let saved = f.ui.stats_store.load().unwrap();
|
||||
assert_eq!(
|
||||
saved.runs(&f.id, TrainingMode::Both).unwrap().completions,
|
||||
saved.runs(&f.id, TrainingMode::White).unwrap().completions,
|
||||
1
|
||||
);
|
||||
assert_eq!(saved.move_stats.iter().map(|s| s.correct).sum::<u32>(), 2);
|
||||
assert_eq!(saved.move_stats.iter().map(|s| s.correct).sum::<u32>(), 1);
|
||||
assert!(f.ui.error.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_ignores_legacy_queue() {
|
||||
let mut f = Fixture::new();
|
||||
f.settings.repertoire_modes.insert(
|
||||
f.id.to_string(),
|
||||
(TrainingMode::White, QueueMode::SpacedRepetition),
|
||||
);
|
||||
f.ui.select(f.id.clone(), &f.settings);
|
||||
assert_eq!(f.ui.mode, TrainingMode::White);
|
||||
|
||||
f.ui.start(&mut f.settings);
|
||||
assert!(f.ui.preparing);
|
||||
assert_eq!(
|
||||
f.settings.repertoire_modes.get(f.id.as_str()),
|
||||
Some(&(TrainingMode::White, QueueMode::Practice))
|
||||
);
|
||||
|
||||
f.deliver(f.completed_job());
|
||||
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());
|
||||
assert_eq!(
|
||||
f.ui.stats_store
|
||||
.load()
|
||||
.unwrap()
|
||||
.runs(&f.id, TrainingMode::White)
|
||||
.unwrap()
|
||||
.completions,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn due_count_reuses_pending_work_across_minutes_and_discards_evicted_results() {
|
||||
let mut f = Fixture::new();
|
||||
|
|
@ -195,6 +349,70 @@ fn both_and_review_counts_have_no_minute_expiry_and_complete_asynchronously() {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variant_count_does_not_depend_on_completed_training_runs() {
|
||||
let mut f = Fixture::new();
|
||||
let game = chess_core::parse_str("1. e4 e5 (1... c5) 2. Nf3 *").game;
|
||||
let mut library = f.ui.library.clone();
|
||||
let id = library.create("Two paths", &game).unwrap();
|
||||
assert!(f.ui.persist(library));
|
||||
f.deliver(f.completed_job());
|
||||
assert!(f.ui.stats.runs(&id, TrainingMode::Both).is_none());
|
||||
|
||||
let scope = TrainingScope::whole();
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
None
|
||||
);
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
Some(2)
|
||||
);
|
||||
|
||||
f.ui.stats.runs.push(trainer::repertoire::RunStats {
|
||||
repertoire_id: id.clone(),
|
||||
mode: TrainingMode::Both,
|
||||
completions: 7,
|
||||
last: Some(now()),
|
||||
recent: Vec::new(),
|
||||
});
|
||||
f.ui.stats.revision += 1;
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
None
|
||||
);
|
||||
f.deliver(f.completed_job());
|
||||
assert_eq!(
|
||||
f.ui.task_count(
|
||||
&id,
|
||||
TrainingMode::Both,
|
||||
QueueMode::Practice,
|
||||
SrsPolicy::Due,
|
||||
&scope
|
||||
),
|
||||
Some(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual corpus import and indexing measurement"]
|
||||
fn corpus_import_preserves_source_and_reports_real_outcome() {
|
||||
|
|
@ -308,24 +526,3 @@ fn corpus_import_preserves_source_and_reports_real_outcome() {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue