feat: implement ChessTempo opening learning trainer
This commit is contained in:
parent
b08aca0b4c
commit
d1733b4fe5
44 changed files with 21416 additions and 622 deletions
|
|
@ -32,6 +32,9 @@ pub enum Drawn {
|
|||
Circle(chess_core::ShapeColor, Square),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) type TestAnimation<'a> = (f64, &'a [(Piece, Square, Square)], f32);
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct BoardState {
|
||||
selected: Option<Square>,
|
||||
|
|
@ -93,6 +96,12 @@ impl BoardState {
|
|||
pub fn is_busy(&self) -> bool {
|
||||
self.selected.is_some() || self.drag.is_some() || self.promotion.is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn animation_at(&self, now: f64) -> Option<TestAnimation<'_>> {
|
||||
let anim = self.anim.as_ref()?;
|
||||
Some((anim.duration, &anim.slides, anim.rest(now)?))
|
||||
}
|
||||
}
|
||||
|
||||
/// Pieces moving from one position to the next, as on Lichess (chessground): each piece
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
690
apps/desktop/src/learning_branches.rs
Normal file
690
apps/desktop/src/learning_branches.rs
Normal file
|
|
@ -0,0 +1,690 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use egui::{Align, Layout, RichText, Sense, Ui};
|
||||
use egui_extras::{Column, TableBuilder};
|
||||
use trainer::repertoire::{BranchLearningAnalytics, RepertoireId};
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
const WIDE_WIDTH: f32 = 900.0;
|
||||
const HEADER_HEIGHT: f32 = 40.0;
|
||||
const ROW_HEIGHT: f32 = 24.0;
|
||||
const BODY_TEXT_SIZE: f32 = 14.0;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BranchSelection {
|
||||
pub repertoire_id: RepertoireId,
|
||||
pub branch_root: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn show(
|
||||
ui: &mut egui::Ui,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
selected: &mut Option<BranchSelection>,
|
||||
) {
|
||||
ui.style_mut().interaction.selectable_labels = false;
|
||||
if rows.is_empty() {
|
||||
*selected = None;
|
||||
ui.label(tr("No branches in this scope"));
|
||||
return;
|
||||
}
|
||||
if selected
|
||||
.as_ref()
|
||||
.is_none_or(|selection| !rows.iter().any(|row| selection == &selection_for(row)))
|
||||
{
|
||||
*selected = Some(selection_for(&rows[0]));
|
||||
}
|
||||
|
||||
let wide = ui.available_width() >= WIDE_WIDTH;
|
||||
let include_repertoire = include_repertoire_names(rows, names);
|
||||
let mut clicked = None;
|
||||
if wide {
|
||||
show_wide(
|
||||
ui,
|
||||
rows,
|
||||
names,
|
||||
labels,
|
||||
include_repertoire,
|
||||
selected.as_ref(),
|
||||
&mut clicked,
|
||||
);
|
||||
} else {
|
||||
show_narrow(
|
||||
ui,
|
||||
rows,
|
||||
names,
|
||||
labels,
|
||||
include_repertoire,
|
||||
selected.as_ref(),
|
||||
&mut clicked,
|
||||
);
|
||||
}
|
||||
if let Some(selection) = clicked {
|
||||
*selected = Some(selection);
|
||||
}
|
||||
|
||||
if !wide
|
||||
&& let Some(selection) = selected.as_ref()
|
||||
&& let Some(row) = rows.iter().find(|row| selection == &selection_for(row))
|
||||
{
|
||||
ui.separator();
|
||||
show_details(ui, row, names, labels, include_repertoire);
|
||||
}
|
||||
}
|
||||
|
||||
fn selection_for(row: &BranchLearningAnalytics) -> BranchSelection {
|
||||
BranchSelection {
|
||||
repertoire_id: row.repertoire_id.clone(),
|
||||
branch_root: row.branch_root.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn include_repertoire_names(
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
) -> bool {
|
||||
names.len() > 1
|
||||
|| rows.first().is_some_and(|first| {
|
||||
rows.iter()
|
||||
.any(|row| row.repertoire_id != first.repertoire_id)
|
||||
})
|
||||
}
|
||||
|
||||
fn san_path(
|
||||
row: &BranchLearningAnalytics,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
) -> String {
|
||||
let labels = labels.get(&(row.repertoire_id.clone(), row.branch_root.clone()));
|
||||
row.branch_root
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, uci)| {
|
||||
let label = labels.and_then(|labels| labels.get(index)).unwrap_or(uci);
|
||||
crate::san::show(label).into_owned()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
fn branch_text(
|
||||
row: &BranchLearningAnalytics,
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
) -> String {
|
||||
let path = san_path(row, labels);
|
||||
if !include_repertoire {
|
||||
return if path.is_empty() {
|
||||
"—".to_owned()
|
||||
} else {
|
||||
path
|
||||
};
|
||||
}
|
||||
let name = names
|
||||
.get(&row.repertoire_id)
|
||||
.map_or_else(|| row.repertoire_id.as_str(), String::as_str);
|
||||
if path.is_empty() {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("{name} · {path}")
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn show_wide(
|
||||
ui: &mut Ui,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
selected: Option<&BranchSelection>,
|
||||
clicked: &mut Option<BranchSelection>,
|
||||
) {
|
||||
let headers = [
|
||||
"Branch",
|
||||
"Total",
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
"Accuracy",
|
||||
"Learnt %",
|
||||
"Last trained",
|
||||
];
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_wide")
|
||||
.striped(true)
|
||||
.sense(Sense::click())
|
||||
.max_scroll_height(360.0)
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(120.0).clip(true));
|
||||
for width in [30.0, 66.0, 70.0, 52.0, 72.0, 46.0, 68.0, 64.0, 136.0] {
|
||||
table = table.column(Column::exact(width).clip(true));
|
||||
}
|
||||
table
|
||||
.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.into_iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
});
|
||||
}
|
||||
})
|
||||
.body(|body| {
|
||||
body.rows(ROW_HEIGHT, rows.len(), |mut table_row| {
|
||||
let row = &rows[table_row.index()];
|
||||
let selection = selection_for(row);
|
||||
table_row.set_selected(selected == Some(&selection));
|
||||
table_row.col(|ui| {
|
||||
let text = branch_text(row, names, labels, include_repertoire);
|
||||
text_cell(ui, &text, false).on_hover_text(text);
|
||||
});
|
||||
let summary = &row.summary;
|
||||
let values = [
|
||||
summary.total.to_string(),
|
||||
summary.unseen.to_string(),
|
||||
summary.learning.to_string(),
|
||||
summary.learnt.to_string(),
|
||||
summary.uncertain.to_string(),
|
||||
summary.due.to_string(),
|
||||
format_percent(summary.accuracy_percent),
|
||||
format_percent(summary.learnt_percent),
|
||||
format_time(row.last_independent_at),
|
||||
];
|
||||
for value in values {
|
||||
table_row.col(|ui| {
|
||||
text_cell(ui, &value, true);
|
||||
});
|
||||
}
|
||||
if table_row.response().clicked() {
|
||||
*clicked = Some(selection);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn show_narrow(
|
||||
ui: &mut Ui,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
selected: Option<&BranchSelection>,
|
||||
clicked: &mut Option<BranchSelection>,
|
||||
) {
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_narrow")
|
||||
.striped(true)
|
||||
.sense(Sense::click())
|
||||
.max_scroll_height(192.0)
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(88.0).clip(true))
|
||||
.column(Column::exact(62.0).clip(true))
|
||||
.column(Column::exact(52.0).clip(true))
|
||||
.column(Column::exact(76.0).clip(true))
|
||||
.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in ["Branch", "Total", "Due", "Learnt %"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
});
|
||||
}
|
||||
})
|
||||
.body(|body| {
|
||||
body.rows(ROW_HEIGHT, rows.len(), |mut table_row| {
|
||||
let row = &rows[table_row.index()];
|
||||
let selection = selection_for(row);
|
||||
table_row.set_selected(selected == Some(&selection));
|
||||
table_row.col(|ui| {
|
||||
let text = branch_text(row, names, labels, include_repertoire);
|
||||
text_cell(ui, &text, false).on_hover_text(text);
|
||||
});
|
||||
for value in [
|
||||
row.summary.total.to_string(),
|
||||
row.summary.due.to_string(),
|
||||
format_percent(row.summary.learnt_percent),
|
||||
] {
|
||||
table_row.col(|ui| {
|
||||
text_cell(ui, &value, true);
|
||||
});
|
||||
}
|
||||
if table_row.response().clicked() {
|
||||
*clicked = Some(selection);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn show_details(
|
||||
ui: &mut Ui,
|
||||
row: &BranchLearningAnalytics,
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
include_repertoire: bool,
|
||||
) {
|
||||
let branch = branch_text(row, names, labels, include_repertoire);
|
||||
ui.add(egui::Label::new(RichText::new(&branch).strong().size(BODY_TEXT_SIZE)).wrap())
|
||||
.on_hover_text(branch);
|
||||
ui.add_space(4.0);
|
||||
let details = [
|
||||
("Unseen", row.summary.unseen.to_string()),
|
||||
("Learning", row.summary.learning.to_string()),
|
||||
("Learnt", row.summary.learnt.to_string()),
|
||||
("Uncertain", row.summary.uncertain.to_string()),
|
||||
("Due", row.summary.due.to_string()),
|
||||
("Accuracy", format_percent(row.summary.accuracy_percent)),
|
||||
("Last trained", format_time(row.last_independent_at)),
|
||||
];
|
||||
egui::Grid::new("learning_branches_details")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 5.0])
|
||||
.show(ui, |ui| {
|
||||
for (label, value) in details {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE)).wrap(),
|
||||
);
|
||||
ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap());
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn header_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response {
|
||||
let text = RichText::new(text).strong().size(BODY_TEXT_SIZE);
|
||||
if numeric {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(text).wrap())
|
||||
})
|
||||
.inner
|
||||
} else {
|
||||
ui.add(egui::Label::new(text).wrap())
|
||||
}
|
||||
}
|
||||
|
||||
fn text_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response {
|
||||
let text = RichText::new(text).size(BODY_TEXT_SIZE);
|
||||
if numeric {
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(text).truncate())
|
||||
})
|
||||
.inner
|
||||
} else {
|
||||
ui.add(egui::Label::new(text).truncate())
|
||||
}
|
||||
}
|
||||
|
||||
fn format_percent(value: Option<f64>) -> String {
|
||||
value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %"))
|
||||
}
|
||||
|
||||
fn format_time(at: Option<i64>) -> String {
|
||||
at.and_then(|at| chrono::DateTime::from_timestamp(at, 0))
|
||||
.map(|at| {
|
||||
at.with_timezone(&chrono::Local)
|
||||
.format("%Y-%m-%d %H:%M")
|
||||
.to_string()
|
||||
})
|
||||
.unwrap_or_else(|| "—".to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use trainer::repertoire::{LearningAggregate, Repertoire};
|
||||
|
||||
use super::*;
|
||||
|
||||
const BASE: i64 = 1_800_000_000;
|
||||
|
||||
struct Fixture {
|
||||
rows: Vec<BranchLearningAnalytics>,
|
||||
names: HashMap<RepertoireId, String>,
|
||||
labels: HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
}
|
||||
|
||||
fn fixture() -> Fixture {
|
||||
let first = Repertoire::default().id;
|
||||
let second = Repertoire::default().id;
|
||||
let branch_root = vec!["e2e4".to_owned(), "e7e5".to_owned()];
|
||||
let summary = LearningAggregate {
|
||||
total: 8,
|
||||
unseen: 2,
|
||||
learning: 2,
|
||||
learnt: 4,
|
||||
uncertain: 1,
|
||||
learnt_confident: 3,
|
||||
due: 3,
|
||||
learnt_percent: Some(50.0),
|
||||
accuracy_correct: 6,
|
||||
accuracy_wrong: 2,
|
||||
accuracy_attempts: 8,
|
||||
accuracy_percent: Some(75.0),
|
||||
..LearningAggregate::default()
|
||||
};
|
||||
let rows = vec![
|
||||
BranchLearningAnalytics {
|
||||
repertoire_id: first.clone(),
|
||||
branch_root: branch_root.clone(),
|
||||
summary: summary.clone(),
|
||||
last_independent_at: Some(BASE),
|
||||
},
|
||||
BranchLearningAnalytics {
|
||||
repertoire_id: second.clone(),
|
||||
branch_root: branch_root.clone(),
|
||||
summary,
|
||||
last_independent_at: Some(BASE),
|
||||
},
|
||||
];
|
||||
let names = HashMap::from([
|
||||
(first.clone(), "First".to_owned()),
|
||||
(second.clone(), "Second".to_owned()),
|
||||
]);
|
||||
let labels = HashMap::from([
|
||||
(
|
||||
(first, branch_root.clone()),
|
||||
vec!["1.e4".to_owned(), "1...e5".to_owned()],
|
||||
),
|
||||
((second, branch_root), vec!["1.e4".to_owned()]),
|
||||
]);
|
||||
Fixture {
|
||||
rows,
|
||||
names,
|
||||
labels,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn render(
|
||||
ctx: &egui::Context,
|
||||
width: f32,
|
||||
height: f32,
|
||||
time: f64,
|
||||
events: Vec<egui::Event>,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
labels: &HashMap<(RepertoireId, Vec<String>), Vec<String>>,
|
||||
selected: &mut Option<BranchSelection>,
|
||||
) -> Vec<egui::epaint::ClippedShape> {
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
time: Some(time),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
show(ui, rows, names, labels, selected);
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
shapes
|
||||
}
|
||||
|
||||
fn has_text(shapes: &[egui::epaint::ClippedShape], expected: &str) -> bool {
|
||||
shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected,
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
fn has_translated_text(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> bool {
|
||||
crate::i18n::all_languages(key)
|
||||
.into_iter()
|
||||
.any(|translation| has_text(shapes, translation))
|
||||
}
|
||||
|
||||
fn text_position(shapes: &[egui::epaint::ClippedShape], expected: &str) -> Option<egui::Pos2> {
|
||||
shapes.iter().find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text().replace('\n', " ") == expected => {
|
||||
Some(text.pos + egui::vec2(8.0, 6.0))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn text_occurrences(shapes: &[egui::epaint::ClippedShape], expected: &str) -> usize {
|
||||
shapes
|
||||
.iter()
|
||||
.filter(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected,
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
fn click(position: egui::Pos2) -> Vec<egui::Event> {
|
||||
vec![
|
||||
egui::Event::PointerMoved(position),
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn assert_bounds(shapes: &[egui::epaint::ClippedShape], width: f32, height: f32) {
|
||||
for clipped in shapes {
|
||||
let bounds = clipped.shape.visual_bounding_rect();
|
||||
if bounds.is_finite() && bounds.is_positive() {
|
||||
assert!(
|
||||
bounds.min.x >= -0.5
|
||||
&& bounds.min.y >= -0.5
|
||||
&& bounds.max.x <= width + 0.5
|
||||
&& bounds.max.y <= height + 0.5,
|
||||
"shape outside {width}x{height}: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summarized_shared_rows_are_not_deduplicated_and_labels_fall_back_to_uci() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
1200.0,
|
||||
800.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, Some(selection_for(&fixture.rows[0])));
|
||||
assert!(has_text(&shapes, "First · 1.e4 1...e5"));
|
||||
assert!(has_text(&shapes, "Second · 1.e4 e7e5"));
|
||||
|
||||
let names = HashMap::from([(fixture.rows[0].repertoire_id.clone(), "First".to_owned())]);
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
1200.0,
|
||||
800.0,
|
||||
1.0,
|
||||
Vec::new(),
|
||||
&fixture.rows[..1],
|
||||
&names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert!(has_text(&shapes, "1.e4 1...e5"));
|
||||
assert!(!has_text(&shapes, "First · 1.e4 1...e5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_and_narrow_layouts_stay_in_bounds_in_light_and_dark() {
|
||||
let fixture = fixture();
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(1200.0, 800.0), (640.0, 480.0)] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut selected = None;
|
||||
for pass in 0..2 {
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
pass as f64,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert!(!shapes.is_empty());
|
||||
assert_bounds(&shapes, width, height);
|
||||
if width < WIDE_WIDTH {
|
||||
for key in [
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
"Accuracy",
|
||||
"Last trained",
|
||||
] {
|
||||
assert!(
|
||||
has_translated_text(&shapes, key),
|
||||
"missing narrow detail {key}"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for key in [
|
||||
"Branch",
|
||||
"Total",
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
"Accuracy",
|
||||
"Learnt %",
|
||||
"Last trained",
|
||||
] {
|
||||
assert!(
|
||||
has_translated_text(&shapes, key),
|
||||
"missing wide header {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_details_are_visible_and_click_selects_the_branch() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, Some(selection_for(&fixture.rows[0])));
|
||||
let second = text_position(&shapes, "Second · 1.e4 e7e5")
|
||||
.expect("second branch row should be visible");
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
1.0,
|
||||
click(second),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, Some(selection_for(&fixture.rows[1])));
|
||||
assert!(text_occurrences(&shapes, "Second · 1.e4 e7e5") >= 2);
|
||||
for key in [
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
"Accuracy",
|
||||
"Last trained",
|
||||
] {
|
||||
assert!(has_translated_text(&shapes, key), "missing detail {key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_accuracy_and_last_training_render_as_dashes() {
|
||||
let fixture = fixture();
|
||||
let mut row = fixture.rows[0].clone();
|
||||
row.summary.accuracy_percent = None;
|
||||
row.summary.learnt_percent = None;
|
||||
row.last_independent_at = None;
|
||||
let names = HashMap::from([(row.repertoire_id.clone(), "Only".to_owned())]);
|
||||
let labels = HashMap::new();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
std::slice::from_ref(&row),
|
||||
&names,
|
||||
&labels,
|
||||
&mut selected,
|
||||
);
|
||||
let dashes = text_occurrences(&shapes, "—");
|
||||
assert!(dashes >= 3, "expected null metrics as dashes: {dashes}");
|
||||
assert_eq!(format_percent(None), "—");
|
||||
assert_eq!(format_time(None), "—");
|
||||
assert_eq!(format_time(Some(i64::MAX)), "—");
|
||||
assert_eq!(format_percent(Some(75.0)), "75 %");
|
||||
assert!(format_time(Some(BASE)).contains('-'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_scope_clears_selection() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = Some(selection_for(&fixture.rows[0]));
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
640.0,
|
||||
480.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&[],
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_eq!(selected, None);
|
||||
assert!(has_translated_text(&shapes, "No branches in this scope"));
|
||||
}
|
||||
}
|
||||
507
apps/desktop/src/learning_charts.rs
Normal file
507
apps/desktop/src/learning_charts.rs
Normal file
|
|
@ -0,0 +1,507 @@
|
|||
use std::{collections::BTreeMap, fmt};
|
||||
|
||||
use egui::{
|
||||
Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Sense, Shape, Stroke, Ui, Visuals,
|
||||
pos2, vec2,
|
||||
};
|
||||
use trainer::repertoire::{LearningSnapshot, ScheduledBuckets, SequenceHistograms};
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
const CHART_HEIGHT: f32 = 180.0;
|
||||
const HISTORY_DATE_HEIGHT: f32 = 18.0;
|
||||
const SCHEDULED_LABEL_HEIGHT: f32 = 40.0;
|
||||
const HISTOGRAM_LABEL_HEIGHT: f32 = 28.0;
|
||||
const MAX_HISTOGRAM_BARS: usize = 12;
|
||||
const WIDE_SEQUENCE_WIDTH: f32 = 900.0;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Marker {
|
||||
Circle,
|
||||
Square,
|
||||
Diamond,
|
||||
}
|
||||
|
||||
type HistorySeries = (Color32, Marker, fn(&LearningSnapshot) -> usize);
|
||||
|
||||
impl Marker {
|
||||
fn paint(self, painter: &Painter, center: Pos2, color: Color32) {
|
||||
match self {
|
||||
Self::Circle => {
|
||||
painter.circle_filled(center, 2.8, color);
|
||||
}
|
||||
Self::Square => {
|
||||
painter.rect_filled(Rect::from_center_size(center, vec2(5.2, 5.2)), 0.0, color);
|
||||
}
|
||||
Self::Diamond => {
|
||||
painter.add(Shape::convex_polygon(
|
||||
vec![
|
||||
pos2(center.x, center.y - 3.4),
|
||||
pos2(center.x + 3.4, center.y),
|
||||
pos2(center.x, center.y + 3.4),
|
||||
pos2(center.x - 3.4, center.y),
|
||||
],
|
||||
color,
|
||||
Stroke::NONE,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn history(ui: &mut Ui, snapshots: &[LearningSnapshot]) {
|
||||
if snapshots.is_empty() {
|
||||
return;
|
||||
}
|
||||
let palette = series_palette(ui.visuals());
|
||||
history_legend(ui, &palette);
|
||||
ui.add_space(4.0);
|
||||
|
||||
let mut ordered = snapshots.iter().collect::<Vec<_>>();
|
||||
ordered.sort_by_key(|snapshot| snapshot.as_of);
|
||||
let (Some(first), Some(last)) = (ordered.first(), ordered.last()) else {
|
||||
return;
|
||||
};
|
||||
let start = first.as_of;
|
||||
let end = last.as_of;
|
||||
let max_value = snapshots.iter().fold(0_usize, |max, snapshot| {
|
||||
max.max(snapshot.learning)
|
||||
.max(snapshot.learnt)
|
||||
.max(snapshot.uncertain)
|
||||
});
|
||||
|
||||
let (rect, painter) = chart_area(ui);
|
||||
let plot = plot_rect(&painter, rect, max_value, HISTORY_DATE_HEIGHT);
|
||||
draw_axes(&painter, plot, max_value, ui.visuals());
|
||||
|
||||
let series: [HistorySeries; 3] = [
|
||||
(palette[0], Marker::Circle, |snapshot| snapshot.learning),
|
||||
(palette[1], Marker::Square, |snapshot| snapshot.learnt),
|
||||
(palette[2], Marker::Diamond, |snapshot| snapshot.uncertain),
|
||||
];
|
||||
for (color, marker, value) in series {
|
||||
let points = ordered
|
||||
.iter()
|
||||
.map(|snapshot| {
|
||||
pos2(
|
||||
time_x(snapshot.as_of, start, end, plot.left(), plot.right()),
|
||||
value_y(value(snapshot), max_value, plot.top(), plot.bottom()),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if points.len() >= 2 {
|
||||
painter.add(Shape::line(points.clone(), Stroke::new(1.6, color)));
|
||||
}
|
||||
for point in points {
|
||||
marker.paint(&painter, point, color);
|
||||
}
|
||||
}
|
||||
|
||||
let text_color = ui.visuals().weak_text_color();
|
||||
if ordered.len() == 1 {
|
||||
painter.text(
|
||||
pos2(plot.center().x, rect.bottom()),
|
||||
Align2::CENTER_BOTTOM,
|
||||
&first.date,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
} else {
|
||||
painter.text(
|
||||
pos2(plot.left(), rect.bottom()),
|
||||
Align2::LEFT_BOTTOM,
|
||||
&first.date,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
painter.text(
|
||||
pos2(plot.right(), rect.bottom()),
|
||||
Align2::RIGHT_BOTTOM,
|
||||
&last.date,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn scheduled(ui: &mut Ui, buckets: ScheduledBuckets) {
|
||||
let rows = [
|
||||
(tr("Overdue").to_owned(), buckets.overdue),
|
||||
(tr("Today").to_owned(), buckets.today),
|
||||
(tr("Next 7 days").to_owned(), buckets.week),
|
||||
(tr("Next 30 days").to_owned(), buckets.month),
|
||||
(tr("Next 365 days").to_owned(), buckets.year),
|
||||
(tr("Later").to_owned(), buckets.later),
|
||||
];
|
||||
let color = series_palette(ui.visuals())[0];
|
||||
bar_chart(ui, &rows, color, SCHEDULED_LABEL_HEIGHT, 56.0);
|
||||
}
|
||||
|
||||
pub fn sequences(ui: &mut Ui, histograms: &SequenceHistograms) {
|
||||
let correct = histogram_rows(&histograms.correct_streak);
|
||||
let wrong = histogram_rows(&histograms.wrong_streak);
|
||||
let attempts = histogram_rows(&histograms.attempts);
|
||||
let palette = series_palette(ui.visuals());
|
||||
|
||||
if ui.available_width() >= WIDE_SEQUENCE_WIDTH {
|
||||
ui.columns(3, |columns| {
|
||||
sequence_chart(&mut columns[0], "Correct streak", &correct, palette[1]);
|
||||
sequence_chart(&mut columns[1], "Wrong streak", &wrong, palette[2]);
|
||||
sequence_chart(&mut columns[2], "Attempts", &attempts, palette[0]);
|
||||
});
|
||||
} else {
|
||||
sequence_chart(ui, "Correct streak", &correct, palette[1]);
|
||||
sequence_chart(ui, "Wrong streak", &wrong, palette[2]);
|
||||
sequence_chart(ui, "Attempts", &attempts, palette[0]);
|
||||
}
|
||||
}
|
||||
|
||||
fn history_legend(ui: &mut Ui, palette: &[Color32; 3]) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (key, color, marker) in [
|
||||
("Learning", palette[0], Marker::Circle),
|
||||
("Learnt", palette[1], Marker::Square),
|
||||
("Uncertain", palette[2], Marker::Diamond),
|
||||
] {
|
||||
ui.horizontal(|ui| {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(18.0, 12.0), Sense::hover());
|
||||
let painter = ui.painter().with_clip_rect(rect);
|
||||
let y = rect.center().y;
|
||||
painter.line_segment(
|
||||
[pos2(rect.left(), y), pos2(rect.right(), y)],
|
||||
Stroke::new(1.6, color),
|
||||
);
|
||||
marker.paint(&painter, rect.center(), color);
|
||||
ui.label(tr(key));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn sequence_chart(ui: &mut Ui, title: &'static str, rows: &[(String, usize)], color: Color32) {
|
||||
ui.add(egui::Label::new(RichText::new(tr(title)).strong()).truncate());
|
||||
ui.add_space(4.0);
|
||||
bar_chart(ui, rows, color, HISTOGRAM_LABEL_HEIGHT, 38.0);
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
|
||||
fn chart_area(ui: &mut Ui) -> (Rect, Painter) {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, CHART_HEIGHT), Sense::hover());
|
||||
let painter = ui.painter().with_clip_rect(rect);
|
||||
(rect, painter)
|
||||
}
|
||||
|
||||
fn plot_rect(painter: &Painter, rect: Rect, max_value: usize, label_height: f32) -> Rect {
|
||||
let text_color = Color32::TRANSPARENT;
|
||||
let y_label_width = [max_value.to_string(), "0".to_owned()]
|
||||
.into_iter()
|
||||
.map(|label| {
|
||||
painter
|
||||
.layout_no_wrap(label, label_font(), text_color)
|
||||
.size()
|
||||
.x
|
||||
})
|
||||
.fold(0.0_f32, f32::max);
|
||||
let reserved = (y_label_width + 8.0).min((rect.width() - 32.0).max(0.0));
|
||||
let right = (rect.right() - 4.0).max(rect.left());
|
||||
let left = (rect.left() + reserved).min(right);
|
||||
let top = (rect.top() + 6.0).min(rect.bottom());
|
||||
let bottom = (rect.bottom() - label_height).max(top).min(rect.bottom());
|
||||
Rect::from_min_max(pos2(left, top), pos2(right, bottom))
|
||||
}
|
||||
|
||||
fn draw_axes(painter: &Painter, plot: Rect, max_value: usize, visuals: &Visuals) {
|
||||
let grid_color = visuals.weak_text_color().gamma_multiply(0.18);
|
||||
for y in [plot.top(), plot.center().y, plot.bottom()] {
|
||||
painter.line_segment(
|
||||
[pos2(plot.left(), y), pos2(plot.right(), y)],
|
||||
Stroke::new(1.0, grid_color),
|
||||
);
|
||||
}
|
||||
let axis_color = visuals.weak_text_color().gamma_multiply(0.55);
|
||||
painter.line_segment(
|
||||
[plot.left_top(), plot.left_bottom()],
|
||||
Stroke::new(1.0, axis_color),
|
||||
);
|
||||
painter.line_segment(
|
||||
[plot.left_bottom(), plot.right_bottom()],
|
||||
Stroke::new(1.0, axis_color),
|
||||
);
|
||||
let text_color = visuals.weak_text_color();
|
||||
painter.text(
|
||||
pos2(plot.left() - 6.0, plot.top()),
|
||||
Align2::RIGHT_TOP,
|
||||
max_value,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
painter.text(
|
||||
pos2(plot.left() - 6.0, plot.bottom()),
|
||||
Align2::RIGHT_BOTTOM,
|
||||
0,
|
||||
label_font(),
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
|
||||
fn bar_chart(
|
||||
ui: &mut Ui,
|
||||
rows: &[(String, usize)],
|
||||
color: Color32,
|
||||
label_height: f32,
|
||||
max_bar_width: f32,
|
||||
) {
|
||||
let max_value = rows.iter().map(|(_, count)| *count).max().unwrap_or(0);
|
||||
let (rect, painter) = chart_area(ui);
|
||||
let plot = plot_rect(&painter, rect, max_value, label_height);
|
||||
draw_axes(&painter, plot, max_value, ui.visuals());
|
||||
if rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let slot_width = (plot.width() / rows.len() as f32).max(0.0);
|
||||
let text_color = ui.visuals().weak_text_color();
|
||||
for (index, (label, count)) in rows.iter().enumerate() {
|
||||
let center = plot.left() + (index as f32 + 0.5) * slot_width;
|
||||
if *count > 0 && max_value > 0 {
|
||||
let width = (slot_width - 6.0).max(0.0).min(max_bar_width);
|
||||
if width > 0.0 {
|
||||
let top = value_y(*count, max_value, plot.top(), plot.bottom());
|
||||
painter.rect_filled(
|
||||
Rect::from_min_max(
|
||||
pos2(center - width / 2.0, top),
|
||||
pos2(center + width / 2.0, plot.bottom()),
|
||||
),
|
||||
0.0,
|
||||
color,
|
||||
);
|
||||
}
|
||||
}
|
||||
let galley = painter.layout(label.clone(), label_font(), text_color, slot_width.max(1.0));
|
||||
painter.galley(
|
||||
pos2(
|
||||
center - galley.size().x / 2.0,
|
||||
rect.bottom() - galley.size().y,
|
||||
),
|
||||
galley,
|
||||
text_color,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn value_y(value: usize, max_value: usize, top: f32, bottom: f32) -> f32 {
|
||||
if max_value == 0 {
|
||||
return bottom;
|
||||
}
|
||||
let fraction = (value as f64 / max_value as f64).clamp(0.0, 1.0) as f32;
|
||||
bottom - (bottom - top) * fraction
|
||||
}
|
||||
|
||||
fn time_x(at: i64, start: i64, end: i64, left: f32, right: f32) -> f32 {
|
||||
if start == end {
|
||||
return (left + right) / 2.0;
|
||||
}
|
||||
let numerator = i128::from(at) - i128::from(start);
|
||||
let denominator = i128::from(end) - i128::from(start);
|
||||
let fraction = (numerator as f64 / denominator as f64).clamp(0.0, 1.0) as f32;
|
||||
left + (right - left) * fraction
|
||||
}
|
||||
|
||||
fn histogram_rows<K: Ord + fmt::Display>(histogram: &BTreeMap<K, usize>) -> Vec<(String, usize)> {
|
||||
if histogram.len() <= MAX_HISTOGRAM_BARS {
|
||||
return histogram
|
||||
.iter()
|
||||
.map(|(value, count)| (value.to_string(), *count))
|
||||
.collect();
|
||||
}
|
||||
|
||||
let mut rows = histogram
|
||||
.iter()
|
||||
.take(MAX_HISTOGRAM_BARS - 1)
|
||||
.map(|(value, count)| (value.to_string(), *count))
|
||||
.collect::<Vec<_>>();
|
||||
if let Some((value, _)) = histogram.iter().nth(MAX_HISTOGRAM_BARS - 1) {
|
||||
let count = histogram
|
||||
.iter()
|
||||
.skip(MAX_HISTOGRAM_BARS - 1)
|
||||
.fold(0_usize, |sum, (_, count)| sum.saturating_add(*count));
|
||||
rows.push((format!("{value}+"), count));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn series_palette(visuals: &Visuals) -> [Color32; 3] {
|
||||
if visuals.dark_mode {
|
||||
[
|
||||
Color32::from_rgb(112, 184, 232),
|
||||
Color32::from_rgb(126, 200, 150),
|
||||
Color32::from_rgb(232, 174, 100),
|
||||
]
|
||||
} else {
|
||||
[
|
||||
Color32::from_rgb(35, 105, 155),
|
||||
Color32::from_rgb(45, 125, 80),
|
||||
Color32::from_rgb(170, 95, 35),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
fn label_font() -> FontId {
|
||||
FontId::proportional(12.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use trainer::repertoire::{LearningSide, LocalDatePolicy, StatsScope};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn snapshot(
|
||||
at: i64,
|
||||
date: &str,
|
||||
learning: usize,
|
||||
learnt: usize,
|
||||
uncertain: usize,
|
||||
) -> LearningSnapshot {
|
||||
LearningSnapshot {
|
||||
date: date.to_owned(),
|
||||
scope: StatsScope::new(Vec::new(), LearningSide::White, at),
|
||||
as_of: at,
|
||||
timezone: LocalDatePolicy::UTC,
|
||||
total: learning + learnt,
|
||||
unseen: 0,
|
||||
learning,
|
||||
learnt,
|
||||
uncertain,
|
||||
due: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn input(width: f32, height: f32) -> egui::RawInput {
|
||||
egui::RawInput {
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, height))),
|
||||
time: Some(0.0),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_scaling_has_stable_endpoints() {
|
||||
assert_eq!(value_y(0, 20, 10.0, 150.0), 150.0);
|
||||
assert_eq!(value_y(20, 20, 10.0, 150.0), 10.0);
|
||||
assert_eq!(value_y(10, 20, 10.0, 150.0), 80.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_scaling_stays_on_the_baseline() {
|
||||
assert_eq!(value_y(0, 0, 10.0, 150.0), 150.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_time_point_is_centered() {
|
||||
assert_eq!(time_x(42, 42, 42, 20.0, 220.0), 120.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn time_scaling_handles_the_full_timestamp_range() {
|
||||
assert_eq!(time_x(i64::MIN, i64::MIN, i64::MAX, 20.0, 220.0), 20.0);
|
||||
assert_eq!(time_x(i64::MAX, i64::MIN, i64::MAX, 20.0, 220.0), 220.0);
|
||||
let middle = time_x(0, i64::MIN, i64::MAX, 20.0, 220.0);
|
||||
assert!((middle - 120.0).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_tail_preserves_zero_and_total() {
|
||||
let histogram = (0_u64..25).map(|value| (value, 1_usize)).collect();
|
||||
let rows = histogram_rows(&histogram);
|
||||
assert_eq!(rows.len(), MAX_HISTOGRAM_BARS);
|
||||
assert_eq!(rows[0], ("0".to_owned(), 1));
|
||||
assert_eq!(rows.last(), Some(&("11+".to_owned(), 14)));
|
||||
assert_eq!(rows.iter().map(|(_, count)| count).sum::<usize>(), 25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_snapshot_paints_a_visible_marker() {
|
||||
let snapshots = [snapshot(42, "2026-11-04", 2, 3, 1)];
|
||||
let ctx = egui::Context::default();
|
||||
let output = ctx.run_ui(input(640.0, 480.0), |ui| history(ui, &snapshots));
|
||||
assert!(
|
||||
output
|
||||
.shapes
|
||||
.iter()
|
||||
.any(|clipped| matches!(&clipped.shape, Shape::Circle(_)))
|
||||
);
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn charts_render_wide_narrow_light_and_dark_without_horizontal_overflow() {
|
||||
let snapshots = vec![
|
||||
snapshot(100, "2026-11-02", 8, 2, 0),
|
||||
snapshot(200, "2026-11-03", 5, 5, 1),
|
||||
snapshot(300, "2026-11-04", 3, 9, 2),
|
||||
];
|
||||
let scheduled_buckets = ScheduledBuckets {
|
||||
overdue: 4,
|
||||
today: 2,
|
||||
week: 7,
|
||||
month: 3,
|
||||
year: 5,
|
||||
later: 1,
|
||||
};
|
||||
let histograms = SequenceHistograms {
|
||||
correct_streak: (0_u32..18).map(|key| (key, 2)).collect(),
|
||||
wrong_streak: BTreeMap::from([(0, 8), (1, 3), (2, 1)]),
|
||||
attempts: (0_u64..16).map(|key| (key, 1)).collect(),
|
||||
};
|
||||
|
||||
for visuals in [Visuals::light(), Visuals::dark()] {
|
||||
for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
for _ in 0..2 {
|
||||
let output = ctx.run_ui(input(width, height), |ui| {
|
||||
history(ui, &snapshots);
|
||||
ui.separator();
|
||||
scheduled(ui, scheduled_buckets);
|
||||
ui.separator();
|
||||
sequences(ui, &histograms);
|
||||
});
|
||||
assert!(!output.shapes.is_empty());
|
||||
for clipped in &output.shapes {
|
||||
let bounds = clipped
|
||||
.shape
|
||||
.visual_bounding_rect()
|
||||
.intersect(clipped.clip_rect);
|
||||
if bounds.is_finite() && bounds.is_positive() {
|
||||
assert!(
|
||||
bounds.min.x >= -0.5 && bounds.max.x <= width + 0.5,
|
||||
"horizontal overflow at {width}x{height}: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_all_zero_inputs_render() {
|
||||
let zero_histograms = SequenceHistograms {
|
||||
correct_streak: BTreeMap::from([(0, 0)]),
|
||||
wrong_streak: BTreeMap::from([(0, 0)]),
|
||||
attempts: BTreeMap::from([(0_u64, 0)]),
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let output = ctx.run_ui(input(640.0, 480.0), |ui| {
|
||||
history(ui, &[]);
|
||||
scheduled(ui, ScheduledBuckets::default());
|
||||
sequences(ui, &SequenceHistograms::default());
|
||||
sequences(ui, &zero_histograms);
|
||||
});
|
||||
assert!(!output.shapes.is_empty());
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
}
|
||||
291
apps/desktop/src/learning_context_controls.rs
Normal file
291
apps/desktop/src/learning_context_controls.rs
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
use trainer::repertoire::LearningContextPolicy;
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
pub fn show(ui: &mut egui::Ui, policy: &mut LearningContextPolicy) -> bool {
|
||||
let before = *policy;
|
||||
egui::CollapsingHeader::new(tr("Context and move speed"))
|
||||
.id_salt("learning_context_controls")
|
||||
.default_open(std::env::var_os("CP_REPERTOIRE_CONTEXT_OPEN").is_some())
|
||||
.show_unindented(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 0.0;
|
||||
ui.add_space(16.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap);
|
||||
let label = |ui: &mut egui::Ui, text: &'static str| {
|
||||
ui.add(egui::Label::new(tr(text)).wrap());
|
||||
};
|
||||
let column_width = ((ui.available_width() - 12.0) / 2.0).max(1.0);
|
||||
egui::Grid::new("learning_context_controls_grid")
|
||||
.num_columns(2)
|
||||
.max_col_width(column_width)
|
||||
.spacing(egui::vec2(12.0, 6.0))
|
||||
.show(ui, |ui| {
|
||||
label(ui, "Reinforce minimum correct");
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut policy.reinforce_minimum_correct)
|
||||
.range(0..=u32::MAX),
|
||||
);
|
||||
ui.end_row();
|
||||
|
||||
let mut enabled = policy.reinforce_minimum_days.is_some();
|
||||
if ui
|
||||
.checkbox(&mut enabled, tr("Reinforce minimum days"))
|
||||
.changed()
|
||||
{
|
||||
policy.reinforce_minimum_days = enabled.then_some(7);
|
||||
}
|
||||
let mut days = policy.reinforce_minimum_days.unwrap_or(7);
|
||||
if ui
|
||||
.add_enabled(
|
||||
enabled,
|
||||
egui::DragValue::new(&mut days).range(0..=u32::MAX),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
policy.reinforce_minimum_days = Some(days);
|
||||
}
|
||||
ui.end_row();
|
||||
|
||||
label(ui, "Don't show start moves threshold");
|
||||
ui.add(
|
||||
egui::DragValue::new(
|
||||
&mut policy.dont_show_start_moves_threshold,
|
||||
)
|
||||
.range(0..=u32::MAX),
|
||||
);
|
||||
ui.end_row();
|
||||
|
||||
ui.checkbox(
|
||||
&mut policy.use_fixed_piece_speed,
|
||||
tr("Use fixed piece movement speed"),
|
||||
);
|
||||
ui.end_row();
|
||||
|
||||
label(ui, "Move speed adjustment");
|
||||
ui.add_enabled(
|
||||
!policy.use_fixed_piece_speed,
|
||||
egui::DragValue::new(&mut policy.move_speed_adjustment)
|
||||
.range(-2.0..=2.0)
|
||||
.speed(0.05)
|
||||
.fixed_decimals(1),
|
||||
)
|
||||
.on_hover_text(tr("Range −2…2. Adaptive speed = adjustment × (1 + learned fraction), limited to 0.25×–4×: 1.5 gives 3× for a fully learned move; 0 or less gives 0.25×."));
|
||||
ui.end_row();
|
||||
|
||||
ui.checkbox(
|
||||
&mut policy.consider_leadup_moves,
|
||||
tr("Consider leadup moves when training branch"),
|
||||
);
|
||||
ui.end_row();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
*policy != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn render(
|
||||
ctx: &egui::Context,
|
||||
width: f32,
|
||||
height: f32,
|
||||
container_width: f32,
|
||||
time: f64,
|
||||
events: Vec<egui::Event>,
|
||||
policy: &mut LearningContextPolicy,
|
||||
) -> (Vec<egui::epaint::ClippedShape>, bool, egui::Rect) {
|
||||
let mut changed = false;
|
||||
let mut container =
|
||||
egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(container_width, height));
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
time: Some(time),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
let available = ui.available_rect_before_wrap();
|
||||
container = egui::Rect::from_min_size(
|
||||
available.min,
|
||||
egui::vec2(container_width, available.height()),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(container), |ui| {
|
||||
ui.set_clip_rect(container);
|
||||
changed = show(ui, policy);
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
(shapes, changed, container)
|
||||
}
|
||||
|
||||
fn text_rect(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> Option<egui::Rect> {
|
||||
let translations = crate::i18n::all_languages(key);
|
||||
shapes.iter().find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if translations
|
||||
.iter()
|
||||
.any(|candidate| *candidate == text.galley.text()) =>
|
||||
{
|
||||
Some(egui::Rect::from_min_size(text.pos, text.galley.size()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn text_position(
|
||||
shapes: &[egui::epaint::ClippedShape],
|
||||
key: &'static str,
|
||||
) -> Option<egui::Pos2> {
|
||||
text_rect(shapes, key).map(|rect| rect.min + egui::vec2(8.0, 6.0))
|
||||
}
|
||||
|
||||
fn click(position: egui::Pos2) -> Vec<egui::Event> {
|
||||
vec![
|
||||
egui::Event::PointerMoved(position),
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: true,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
egui::Event::PointerButton {
|
||||
pos: position,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed: false,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controls_fit_embedded_side_widths_and_report_only_real_changes() {
|
||||
for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] {
|
||||
for container_width in [320.0, 360.0, 420.0] {
|
||||
let ctx = egui::Context::default();
|
||||
let mut policy = LearningContextPolicy::default();
|
||||
let (collapsed, changed, _) = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
container_width,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&mut policy,
|
||||
);
|
||||
assert!(!changed);
|
||||
assert!(text_position(&collapsed, "Context and move speed").is_some());
|
||||
assert!(text_position(&collapsed, "Reinforce minimum correct").is_none());
|
||||
|
||||
let header = text_position(&collapsed, "Context and move speed").unwrap();
|
||||
let (_, changed, _) = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
container_width,
|
||||
1.0,
|
||||
click(header),
|
||||
&mut policy,
|
||||
);
|
||||
assert!(!changed, "expanding the header must not save settings");
|
||||
assert_eq!(policy, LearningContextPolicy::default());
|
||||
let (expanded, changed, container) = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
container_width,
|
||||
2.0,
|
||||
Vec::new(),
|
||||
&mut policy,
|
||||
);
|
||||
assert!(!changed);
|
||||
for key in [
|
||||
"Reinforce minimum correct",
|
||||
"Reinforce minimum days",
|
||||
"Don't show start moves threshold",
|
||||
"Use fixed piece movement speed",
|
||||
"Move speed adjustment",
|
||||
"Consider leadup moves when training branch",
|
||||
] {
|
||||
assert!(
|
||||
text_position(&expanded, key).is_some(),
|
||||
"missing {key} in {container_width} at {width}x{height}; {container:?}; visible: {:?}",
|
||||
expanded
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) => Some(text.galley.text()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
for clipped in &expanded {
|
||||
if let egui::Shape::Text(text) = &clipped.shape {
|
||||
let rect = egui::Rect::from_min_size(text.pos, text.galley.size());
|
||||
assert!(
|
||||
rect.min.x >= container.min.x
|
||||
&& rect.min.y >= container.min.y
|
||||
&& rect.max.x <= container.max.x + 0.01
|
||||
&& rect.max.y <= container.max.y + 0.01,
|
||||
"text outside {container:?}: {rect:?} {}",
|
||||
text.galley.text()
|
||||
);
|
||||
}
|
||||
}
|
||||
let indent = text_rect(&expanded, "Reinforce minimum correct")
|
||||
.unwrap()
|
||||
.left()
|
||||
- container.left();
|
||||
assert!((indent - 16.0).abs() < 0.01, "body indent: {indent}");
|
||||
|
||||
let fixed = text_position(&expanded, "Use fixed piece movement speed").unwrap();
|
||||
let (_, changed, _) = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
container_width,
|
||||
3.0,
|
||||
click(fixed),
|
||||
&mut policy,
|
||||
);
|
||||
assert!(changed);
|
||||
assert!(!policy.use_fixed_piece_speed);
|
||||
let (_, changed, _) = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
container_width,
|
||||
4.0,
|
||||
Vec::new(),
|
||||
&mut policy,
|
||||
);
|
||||
assert!(!changed, "an unchanged frame must not save settings");
|
||||
|
||||
let days = text_position(&expanded, "Reinforce minimum days").unwrap();
|
||||
let (_, changed, _) = render(
|
||||
&ctx,
|
||||
width,
|
||||
height,
|
||||
container_width,
|
||||
5.0,
|
||||
click(days),
|
||||
&mut policy,
|
||||
);
|
||||
assert!(changed);
|
||||
assert_eq!(policy.reinforce_minimum_days, Some(7));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1998
apps/desktop/src/learning_dashboard.rs
Normal file
1998
apps/desktop/src/learning_dashboard.rs
Normal file
File diff suppressed because it is too large
Load diff
2514
apps/desktop/src/learning_training.rs
Normal file
2514
apps/desktop/src/learning_training.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -30,6 +30,16 @@ mod game_view;
|
|||
mod graphics;
|
||||
mod i18n;
|
||||
mod large_db;
|
||||
#[cfg(not(web))]
|
||||
mod learning_branches;
|
||||
#[cfg(not(web))]
|
||||
mod learning_charts;
|
||||
#[cfg(not(web))]
|
||||
mod learning_context_controls;
|
||||
#[cfg(not(web))]
|
||||
mod learning_dashboard;
|
||||
#[cfg(not(web))]
|
||||
mod learning_training;
|
||||
mod library;
|
||||
mod maia_download;
|
||||
#[cfg(web)]
|
||||
|
|
@ -46,6 +56,8 @@ mod prep_saved;
|
|||
mod prep_ui;
|
||||
mod reference;
|
||||
#[cfg(not(web))]
|
||||
mod repertoire_editor;
|
||||
#[cfg(not(web))]
|
||||
mod repertoire_training;
|
||||
#[cfg(not(web))]
|
||||
mod repertoire_ui;
|
||||
|
|
|
|||
978
apps/desktop/src/repertoire_editor.rs
Normal file
978
apps/desktop/src/repertoire_editor.rs
Normal file
|
|
@ -0,0 +1,978 @@
|
|||
use chess_core::shakmaty::{Chess, Color, Position, san::SanPlus, uci::UciMove};
|
||||
use chess_core::{Game, MoveKind, NodeId};
|
||||
use egui::{RichText, Ui};
|
||||
use trainer::repertoire::{
|
||||
LearningData, LearningItemKey, LearningSide, Library, LibraryStore, MoveLearningAnalytics,
|
||||
MoveLearningStatus, Repertoire, RepertoireError, RepertoireId, RepertoireTree, SrsSettings,
|
||||
StatsScope, scoped_move_learning_analytics,
|
||||
};
|
||||
|
||||
use crate::board::{BoardState, BoardView};
|
||||
use crate::i18n::tr;
|
||||
use crate::settings::Settings;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RepertoireEditorAction {
|
||||
Close,
|
||||
Cancel,
|
||||
Applied {
|
||||
repertoire_id: RepertoireId,
|
||||
library: Library,
|
||||
},
|
||||
Error(String),
|
||||
}
|
||||
|
||||
pub struct RepertoireEditorUi {
|
||||
original: Library,
|
||||
draft: Library,
|
||||
repertoire_id: RepertoireId,
|
||||
tree: RepertoireTree,
|
||||
selected: NodeId,
|
||||
board: BoardState,
|
||||
learning: Option<LearningData>,
|
||||
analytics_cache: Option<Result<Option<MoveLearningAnalytics>, String>>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl RepertoireEditorUi {
|
||||
pub fn new(library: &Library, repertoire_id: RepertoireId) -> Result<Self, RepertoireError> {
|
||||
let repertoire = library
|
||||
.repertoire(&repertoire_id)
|
||||
.ok_or_else(|| RepertoireError::NotFound(repertoire_id.clone()))?;
|
||||
let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new());
|
||||
let selected = tree.root();
|
||||
Ok(Self {
|
||||
original: library.clone(),
|
||||
draft: library.clone(),
|
||||
repertoire_id,
|
||||
tree,
|
||||
selected,
|
||||
board: BoardState::default(),
|
||||
learning: None,
|
||||
analytics_cache: None,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn set_learning(&mut self, learning: &LearningData) {
|
||||
self.learning = Some(learning.clone());
|
||||
self.analytics_cache = None;
|
||||
}
|
||||
|
||||
pub fn has_unsaved(&self) -> bool {
|
||||
self.draft.repertoire(&self.repertoire_id) != self.original.repertoire(&self.repertoire_id)
|
||||
}
|
||||
|
||||
pub fn show(
|
||||
&mut self,
|
||||
ui: &mut Ui,
|
||||
settings: &Settings,
|
||||
library_store: &LibraryStore,
|
||||
) -> Vec<RepertoireEditorAction> {
|
||||
let mut actions = Vec::new();
|
||||
let mut commands = Vec::new();
|
||||
self.show_header(ui, &mut commands);
|
||||
let available = ui.available_rect_before_wrap();
|
||||
if available.width() < 720.0 {
|
||||
let board_bottom = available.top() + (available.height() * 0.46).max(100.0);
|
||||
let board_rect = egui::Rect::from_min_max(
|
||||
available.min,
|
||||
egui::pos2(available.right(), board_bottom.min(available.bottom())),
|
||||
);
|
||||
let panel_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(available.left(), board_rect.bottom()),
|
||||
available.max,
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(board_rect), |ui| {
|
||||
self.show_board(ui, settings);
|
||||
});
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(panel_rect), |ui| {
|
||||
ui.set_clip_rect(panel_rect);
|
||||
self.show_panel(ui, &mut commands);
|
||||
});
|
||||
} else {
|
||||
let panel_width = (available.width() * 0.44).clamp(320.0, 500.0);
|
||||
let panel_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(available.right() - panel_width, available.top()),
|
||||
available.max,
|
||||
);
|
||||
let board_rect = egui::Rect::from_min_max(
|
||||
available.min,
|
||||
egui::pos2(panel_rect.left(), available.bottom()),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(board_rect), |ui| {
|
||||
self.show_board(ui, settings);
|
||||
});
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(panel_rect), |ui| {
|
||||
ui.set_clip_rect(panel_rect);
|
||||
self.show_panel(ui, &mut commands);
|
||||
});
|
||||
}
|
||||
for command in commands {
|
||||
match command {
|
||||
EditorCommand::Close => actions.push(RepertoireEditorAction::Close),
|
||||
EditorCommand::Cancel => {
|
||||
self.cancel();
|
||||
actions.push(RepertoireEditorAction::Cancel);
|
||||
}
|
||||
EditorCommand::Save => match self.save(library_store) {
|
||||
Ok(library) => actions.push(RepertoireEditorAction::Applied {
|
||||
repertoire_id: self.repertoire_id.clone(),
|
||||
library,
|
||||
}),
|
||||
Err(error) => {
|
||||
self.error = Some(error.clone());
|
||||
actions.push(RepertoireEditorAction::Error(error));
|
||||
}
|
||||
},
|
||||
EditorCommand::Select(node) => self.select(node),
|
||||
EditorCommand::SetMainAnswer => {
|
||||
if let Err(error) = self.set_selected_main_answer() {
|
||||
self.error = Some(error.clone());
|
||||
actions.push(RepertoireEditorAction::Error(error));
|
||||
}
|
||||
}
|
||||
EditorCommand::ClearMainAnswer => {
|
||||
self.clear_selected_main_answer();
|
||||
}
|
||||
EditorCommand::SetDisabled(disabled) => {
|
||||
if let Err(error) = self.set_selected_disabled(disabled) {
|
||||
self.error = Some(error.clone());
|
||||
actions.push(RepertoireEditorAction::Error(error));
|
||||
}
|
||||
}
|
||||
EditorCommand::SetDepth(depth) => {
|
||||
if let Some(repertoire) = self.draft.repertoire_mut(&self.repertoire_id) {
|
||||
repertoire.set_max_plies(depth);
|
||||
self.analytics_cache = None;
|
||||
self.error = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
actions
|
||||
}
|
||||
|
||||
fn show_header(&self, ui: &mut Ui, commands: &mut Vec<EditorCommand>) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button(tr("Close")).clicked() {
|
||||
commands.push(EditorCommand::Close);
|
||||
}
|
||||
if let Some(repertoire) = self.draft.repertoire(&self.repertoire_id) {
|
||||
ui.add(egui::Label::new(RichText::new(&repertoire.name).heading()).truncate())
|
||||
.on_hover_text(&repertoire.name);
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
commands.push(EditorCommand::Cancel);
|
||||
}
|
||||
ui.add_enabled_ui(self.has_unsaved(), |ui| {
|
||||
if crate::widgets::primary(ui, tr("Save")).clicked() {
|
||||
commands.push(EditorCommand::Save);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
|
||||
fn show_board(&mut self, ui: &mut Ui, settings: &Settings) {
|
||||
let position = self
|
||||
.tree
|
||||
.position(self.selected)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let last_move = self
|
||||
.tree
|
||||
.game()
|
||||
.game_move(self.selected)
|
||||
.and_then(|game_move| match game_move.kind {
|
||||
MoveKind::Normal(mv) => Some((
|
||||
mv.from().unwrap_or_else(|| mv.to()),
|
||||
crate::board::ui_target(&mv),
|
||||
)),
|
||||
MoveKind::Null => None,
|
||||
});
|
||||
let side = ui
|
||||
.available_width()
|
||||
.min(ui.available_height())
|
||||
.max(1.0)
|
||||
.floor();
|
||||
let available = ui.available_size();
|
||||
let offset = egui::vec2(
|
||||
((available.x - side) / 2.0).max(0.0).floor(),
|
||||
((available.y - side) / 2.0).max(0.0).floor(),
|
||||
);
|
||||
let rect = egui::Rect::from_min_size(ui.cursor().min + offset, egui::vec2(side, side));
|
||||
let orientation = settings
|
||||
.repertoire_modes
|
||||
.get(self.repertoire_id.as_str())
|
||||
.map_or(Color::White, |(mode, _)| match mode {
|
||||
trainer::repertoire::TrainingMode::Black => Color::Black,
|
||||
trainer::repertoire::TrainingMode::White
|
||||
| trainer::repertoire::TrainingMode::Both => Color::White,
|
||||
});
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
BoardView {
|
||||
pos: &position,
|
||||
orientation,
|
||||
last_move,
|
||||
arrows: &[],
|
||||
circles: &[],
|
||||
badge: None,
|
||||
interactive: false,
|
||||
show_coords: settings.show_coords,
|
||||
theme: settings.board_theme.theme(),
|
||||
pieces: settings.piece_set,
|
||||
animation: settings.animation.seconds(),
|
||||
premove: None,
|
||||
auto_queen: false,
|
||||
alert: None,
|
||||
}
|
||||
.show(ui, &mut self.board);
|
||||
});
|
||||
}
|
||||
|
||||
fn show_panel(&mut self, ui: &mut Ui, commands: &mut Vec<EditorCommand>) {
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
if let Some(error) = self.error.clone() {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(&error).color(ui.visuals().error_fg_color))
|
||||
.truncate(),
|
||||
)
|
||||
.on_hover_text(error);
|
||||
ui.separator();
|
||||
}
|
||||
if let Some(repertoire) = self.draft.repertoire(&self.repertoire_id) {
|
||||
let mut depth = repertoire.max_plies;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Depth"));
|
||||
if ui
|
||||
.add(egui::DragValue::new(&mut depth).range(0..=u32::MAX))
|
||||
.changed()
|
||||
{
|
||||
commands.push(EditorCommand::SetDepth(depth));
|
||||
}
|
||||
ui.label(tr("plies"));
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
self.show_selected(ui, commands);
|
||||
ui.separator();
|
||||
self.show_analytics(ui);
|
||||
ui.separator();
|
||||
self.show_tree(ui, commands);
|
||||
});
|
||||
}
|
||||
|
||||
fn show_selected(&self, ui: &mut Ui, commands: &mut Vec<EditorCommand>) {
|
||||
let Some((position_fen4, expected_uci, _)) = self.selected_move_parts() else {
|
||||
ui.label(tr("Select a move in the PGN tree"));
|
||||
return;
|
||||
};
|
||||
let game = self.tree.game();
|
||||
if let Some(label) = game.move_label(self.selected) {
|
||||
ui.strong(crate::san::show(&label));
|
||||
}
|
||||
let main_answer = game
|
||||
.parent(self.selected)
|
||||
.and_then(|parent| self.effective_main_answer(parent));
|
||||
let is_main = main_answer.as_deref() == Some(expected_uci.as_str());
|
||||
if let Some(main_answer) = main_answer {
|
||||
let label = game
|
||||
.position_before(self.selected)
|
||||
.and_then(|position| san_for_uci(position, &main_answer))
|
||||
.unwrap_or_else(|| "—".to_owned());
|
||||
ui.label(format!("{}: {label}", tr("Main answer")));
|
||||
}
|
||||
let has_override = self
|
||||
.draft
|
||||
.repertoire(&self.repertoire_id)
|
||||
.and_then(|repertoire| repertoire.main_answer_override(&position_fen4))
|
||||
.is_some();
|
||||
let disabled = self
|
||||
.draft
|
||||
.repertoire(&self.repertoire_id)
|
||||
.zip(self.tree.path(self.selected))
|
||||
.is_some_and(|(repertoire, path)| repertoire.is_prefix_disabled(path));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.add_enabled(!is_main, egui::Button::new(tr("Make main answer")))
|
||||
.clicked()
|
||||
{
|
||||
commands.push(EditorCommand::SetMainAnswer);
|
||||
}
|
||||
if ui
|
||||
.add_enabled(has_override, egui::Button::new(tr("Clear override")))
|
||||
.clicked()
|
||||
{
|
||||
commands.push(EditorCommand::ClearMainAnswer);
|
||||
}
|
||||
if ui
|
||||
.button(if disabled {
|
||||
tr("Enable")
|
||||
} else {
|
||||
tr("Disable")
|
||||
})
|
||||
.clicked()
|
||||
{
|
||||
commands.push(EditorCommand::SetDisabled(!disabled));
|
||||
}
|
||||
});
|
||||
if disabled {
|
||||
ui.label(tr("Disabled for training"));
|
||||
}
|
||||
}
|
||||
|
||||
fn show_tree(&self, ui: &mut Ui, commands: &mut Vec<EditorCommand>) {
|
||||
ui.strong(tr("PGN tree"));
|
||||
let root = self.tree.root();
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(tr("Initial position"))
|
||||
.selected(self.selected == root)
|
||||
.truncate(),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
commands.push(EditorCommand::Select(root));
|
||||
}
|
||||
for row in tree_rows(&self.tree) {
|
||||
let Some(label) = self.tree.game().move_label(row.node) else {
|
||||
continue;
|
||||
};
|
||||
let mut label = crate::san::show(&label).into_owned();
|
||||
if row.variation {
|
||||
label = format!("↳ {label}");
|
||||
}
|
||||
if self
|
||||
.tree
|
||||
.game()
|
||||
.parent(row.node)
|
||||
.and_then(|parent| self.effective_main_answer(parent))
|
||||
.zip(self.tree.game().game_move(row.node).and_then(|mv| mv.uci()))
|
||||
.is_some_and(|(main, uci)| main == uci)
|
||||
{
|
||||
label.push_str(&format!(" · {}", tr("main")));
|
||||
}
|
||||
if self
|
||||
.draft
|
||||
.repertoire(&self.repertoire_id)
|
||||
.zip(self.tree.path(row.node))
|
||||
.is_some_and(|(repertoire, path)| repertoire.is_prefix_disabled(path))
|
||||
{
|
||||
label.push_str(&format!(" · {}", tr("disabled")));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let indentation = (row.indentation as f32 * 14.0).min(ui.available_width() * 0.35);
|
||||
ui.add_space(indentation);
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(label)
|
||||
.selected(self.selected == row.node)
|
||||
.truncate(),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
commands.push(EditorCommand::Select(row.node));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn show_analytics(&mut self, ui: &mut Ui) {
|
||||
ui.strong(tr("Move analytics"));
|
||||
if self.selected == self.tree.root() {
|
||||
ui.label(tr("Select a move to see its learning analytics"));
|
||||
return;
|
||||
}
|
||||
if self.learning.is_none() {
|
||||
ui.label(tr("Shared learning data is not connected"));
|
||||
return;
|
||||
}
|
||||
match self.selected_analytics() {
|
||||
Ok(Some(analytics)) => {
|
||||
show_move_analytics(ui, &analytics, self.tree.game(), self.selected)
|
||||
}
|
||||
Ok(None) => {
|
||||
ui.label(tr("Learning analytics is kept for the current main answer"));
|
||||
}
|
||||
Err(error) => {
|
||||
ui.colored_label(ui.visuals().error_fg_color, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn select(&mut self, node: NodeId) {
|
||||
if self.tree.game().is_attached(node) {
|
||||
self.selected = node;
|
||||
self.board.clear();
|
||||
self.analytics_cache = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&mut self) {
|
||||
self.draft = self.original.clone();
|
||||
self.selected = self.tree.root();
|
||||
self.board.clear();
|
||||
self.analytics_cache = None;
|
||||
self.error = None;
|
||||
}
|
||||
|
||||
fn save(&mut self, library_store: &LibraryStore) -> Result<Library, String> {
|
||||
let draft = self
|
||||
.draft
|
||||
.repertoire(&self.repertoire_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| tr("Repertoire not found").to_owned())?;
|
||||
let original = self
|
||||
.original
|
||||
.repertoire(&self.repertoire_id)
|
||||
.cloned()
|
||||
.ok_or_else(|| tr("Repertoire not found").to_owned())?;
|
||||
let mut updated = original;
|
||||
updated.max_plies = draft.max_plies;
|
||||
updated.disabled_prefixes = draft.disabled_prefixes;
|
||||
updated.main_answer_overrides = draft.main_answer_overrides;
|
||||
let mut saved = self.original.clone();
|
||||
let slot = saved
|
||||
.repertoire_mut(&self.repertoire_id)
|
||||
.ok_or_else(|| tr("Repertoire not found").to_owned())?;
|
||||
*slot = updated;
|
||||
library_store
|
||||
.save(&mut saved)
|
||||
.map_err(|error| error.to_string())?;
|
||||
self.original = saved.clone();
|
||||
self.draft = saved.clone();
|
||||
self.analytics_cache = None;
|
||||
self.error = None;
|
||||
Ok(saved)
|
||||
}
|
||||
|
||||
fn selected_move_parts(&self) -> Option<(String, String, LearningSide)> {
|
||||
let game = self.tree.game();
|
||||
let parent = game.parent(self.selected)?;
|
||||
let expected_uci = game.game_move(self.selected)?.uci()?;
|
||||
let position_fen4 = self.tree.position_key(parent)?.to_owned();
|
||||
let side = LearningSide::from(game.position(parent)?.turn());
|
||||
Some((position_fen4, expected_uci, side))
|
||||
}
|
||||
|
||||
fn set_selected_main_answer(&mut self) -> Result<(), String> {
|
||||
let (position_fen4, expected_uci, side) = self
|
||||
.selected_move_parts()
|
||||
.ok_or_else(|| tr("Select a move in the PGN tree").to_owned())?;
|
||||
self.assign_main_answer_checked(&position_fen4, &expected_uci, side)
|
||||
}
|
||||
|
||||
fn assign_main_answer_checked(
|
||||
&mut self,
|
||||
position_fen4: &str,
|
||||
expected_uci: &str,
|
||||
side: LearningSide,
|
||||
) -> Result<(), String> {
|
||||
let repertoire = self
|
||||
.draft
|
||||
.repertoire_mut(&self.repertoire_id)
|
||||
.ok_or_else(|| tr("Repertoire not found").to_owned())?;
|
||||
repertoire
|
||||
.set_main_answer_override(position_fen4, expected_uci, side)
|
||||
.map_err(|_| {
|
||||
tr("The selected move cannot be the main answer for this position").to_owned()
|
||||
})?;
|
||||
self.analytics_cache = None;
|
||||
self.error = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear_selected_main_answer(&mut self) {
|
||||
let Some((position_fen4, _, _)) = self.selected_move_parts() else {
|
||||
return;
|
||||
};
|
||||
if let Some(repertoire) = self.draft.repertoire_mut(&self.repertoire_id) {
|
||||
repertoire.clear_main_answer_override(&position_fen4);
|
||||
self.analytics_cache = None;
|
||||
self.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_selected_disabled(&mut self, disabled: bool) -> Result<(), String> {
|
||||
let path = self
|
||||
.tree
|
||||
.path(self.selected)
|
||||
.filter(|path| !path.is_empty())
|
||||
.map(<[String]>::to_vec)
|
||||
.ok_or_else(|| tr("Select a move in the PGN tree").to_owned())?;
|
||||
let repertoire = self
|
||||
.draft
|
||||
.repertoire_mut(&self.repertoire_id)
|
||||
.ok_or_else(|| tr("Repertoire not found").to_owned())?;
|
||||
if disabled {
|
||||
repertoire
|
||||
.set_prefix_disabled(&path, true)
|
||||
.map_err(|_| tr("The selected PGN branch cannot be disabled").to_owned())?;
|
||||
} else {
|
||||
let blocking: Vec<Vec<String>> = repertoire
|
||||
.disabled_prefixes
|
||||
.iter()
|
||||
.filter(|prefix| path.starts_with(prefix))
|
||||
.cloned()
|
||||
.collect();
|
||||
for prefix in blocking {
|
||||
repertoire
|
||||
.set_prefix_disabled(&prefix, false)
|
||||
.map_err(|_| tr("The selected PGN branch cannot be enabled").to_owned())?;
|
||||
}
|
||||
}
|
||||
self.analytics_cache = None;
|
||||
self.error = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn effective_main_answer(&self, parent: NodeId) -> Option<String> {
|
||||
let repertoire = self.draft.repertoire(&self.repertoire_id)?;
|
||||
effective_main_answer(repertoire, &self.tree, parent)
|
||||
}
|
||||
|
||||
fn selected_analytics(&mut self) -> Result<Option<MoveLearningAnalytics>, String> {
|
||||
if self.analytics_cache.is_none() {
|
||||
let result = self.compute_selected_analytics();
|
||||
self.analytics_cache = Some(result);
|
||||
}
|
||||
self.analytics_cache.clone().unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
fn compute_selected_analytics(&self) -> Result<Option<MoveLearningAnalytics>, String> {
|
||||
let Some(learning) = &self.learning else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some((position_fen4, expected_uci, side)) = self.selected_move_parts() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let key = LearningItemKey::local(position_fen4, expected_uci);
|
||||
let mut scope = StatsScope::for_repertoire(self.repertoire_id.clone(), side, now());
|
||||
scope.only_active = false;
|
||||
let analytics =
|
||||
scoped_move_learning_analytics(&self.draft, learning, &scope, &SrsSettings::default())
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok(analytics.into_iter().find(|item| item.key == key))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum EditorCommand {
|
||||
Close,
|
||||
Cancel,
|
||||
Save,
|
||||
Select(NodeId),
|
||||
SetMainAnswer,
|
||||
ClearMainAnswer,
|
||||
SetDisabled(bool),
|
||||
SetDepth(u32),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct TreeRow {
|
||||
node: NodeId,
|
||||
indentation: u32,
|
||||
variation: bool,
|
||||
}
|
||||
|
||||
fn tree_rows(tree: &RepertoireTree) -> Vec<TreeRow> {
|
||||
fn append(game: &Game, parent: NodeId, indentation: u32, rows: &mut Vec<TreeRow>) {
|
||||
for (index, child) in game.children(parent).iter().copied().enumerate() {
|
||||
let variation = index > 0;
|
||||
let child_indentation = indentation + u32::from(variation);
|
||||
rows.push(TreeRow {
|
||||
node: child,
|
||||
indentation: child_indentation,
|
||||
variation,
|
||||
});
|
||||
append(game, child, child_indentation, rows);
|
||||
}
|
||||
}
|
||||
|
||||
let mut rows = Vec::new();
|
||||
append(tree.game(), tree.root(), 0, &mut rows);
|
||||
rows
|
||||
}
|
||||
|
||||
fn effective_main_answer(
|
||||
repertoire: &Repertoire,
|
||||
tree: &RepertoireTree,
|
||||
parent: NodeId,
|
||||
) -> Option<String> {
|
||||
let position_fen4 = tree.position_key(parent)?;
|
||||
let mut candidates = Vec::new();
|
||||
for transposition in tree.transpositions(parent) {
|
||||
if tree.path(*transposition).is_none() {
|
||||
continue;
|
||||
}
|
||||
for child in tree.game().children(*transposition) {
|
||||
if tree.path(*child).is_none() {
|
||||
continue;
|
||||
}
|
||||
let Some(uci) = tree.game().game_move(*child).and_then(|mv| mv.uci()) else {
|
||||
continue;
|
||||
};
|
||||
if !candidates.contains(&uci) {
|
||||
candidates.push(uci);
|
||||
}
|
||||
}
|
||||
}
|
||||
repertoire
|
||||
.main_answer_override(position_fen4)
|
||||
.filter(|override_uci| candidates.iter().any(|uci| uci == override_uci))
|
||||
.map(str::to_owned)
|
||||
.or_else(|| candidates.into_iter().next())
|
||||
}
|
||||
|
||||
fn show_move_analytics(
|
||||
ui: &mut Ui,
|
||||
analytics: &MoveLearningAnalytics,
|
||||
game: &Game,
|
||||
selected: NodeId,
|
||||
) {
|
||||
egui::Grid::new("repertoire_editor_move_analytics")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 4.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(tr("Status"));
|
||||
ui.label(move_status_label(analytics.status));
|
||||
ui.end_row();
|
||||
ui.label(tr("Accuracy"));
|
||||
ui.label(
|
||||
analytics
|
||||
.accuracy_percent
|
||||
.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")),
|
||||
);
|
||||
ui.end_row();
|
||||
ui.label(tr("Correct streak"));
|
||||
ui.label(analytics.correct_streak.to_string());
|
||||
ui.end_row();
|
||||
ui.label(tr("Wrong streak"));
|
||||
ui.label(analytics.wrong_streak.to_string());
|
||||
ui.end_row();
|
||||
ui.label(tr("Next due"));
|
||||
ui.label(format_time(analytics.next_review_at));
|
||||
ui.end_row();
|
||||
ui.label(tr("Response median"));
|
||||
ui.label(
|
||||
analytics
|
||||
.response_time_median_ms
|
||||
.map_or_else(|| "—".to_owned(), format_duration_ms),
|
||||
);
|
||||
ui.end_row();
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(format!("{}:", tr("Wrong moves")));
|
||||
if analytics.wrong_move_histogram.is_empty() {
|
||||
ui.label("—");
|
||||
} else {
|
||||
for (uci, stats) in &analytics.wrong_move_histogram {
|
||||
let label = game
|
||||
.position_before(selected)
|
||||
.and_then(|position| san_for_uci(position, uci))
|
||||
.unwrap_or_else(|| tr("Unknown move").to_owned());
|
||||
ui.label(format!("{label} × {}", stats.count));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn move_status_label(status: MoveLearningStatus) -> &'static str {
|
||||
tr(match status {
|
||||
MoveLearningStatus::Unseen => "Unseen",
|
||||
MoveLearningStatus::Learning => "Learning",
|
||||
MoveLearningStatus::LearntFresh => "Learnt",
|
||||
MoveLearningStatus::Uncertain => "Uncertain",
|
||||
})
|
||||
}
|
||||
|
||||
fn san_for_uci(position: &Chess, uci: &str) -> Option<String> {
|
||||
let mv = uci.parse::<UciMove>().ok()?.to_move(position).ok()?;
|
||||
Some(crate::san::show(&SanPlus::from_move(position.clone(), mv).to_string()).into_owned())
|
||||
}
|
||||
|
||||
fn format_duration_ms(milliseconds: f64) -> String {
|
||||
if milliseconds >= 1000.0 {
|
||||
format!("{:.2} s", milliseconds / 1000.0)
|
||||
} else {
|
||||
format!("{milliseconds:.0} ms")
|
||||
}
|
||||
}
|
||||
|
||||
fn format_time(at: Option<i64>) -> String {
|
||||
at.and_then(|at| chrono::DateTime::from_timestamp(at, 0))
|
||||
.map(|at| {
|
||||
at.with_timezone(&chrono::Local)
|
||||
.format("%Y-%m-%d %H:%M")
|
||||
.to_string()
|
||||
})
|
||||
.unwrap_or_else(|| "—".to_owned())
|
||||
}
|
||||
|
||||
fn now() -> i64 {
|
||||
chrono::Local::now().timestamp()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use trainer::repertoire::{LearningStore, LearningStoreData, WrongMoveStats, fen4};
|
||||
|
||||
use super::*;
|
||||
|
||||
static NEXT_TEST: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
struct TestDir(PathBuf);
|
||||
|
||||
impl TestDir {
|
||||
fn new(name: &str) -> Self {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"cp-repertoire-editor-{}-{}-{name}",
|
||||
std::process::id(),
|
||||
NEXT_TEST.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
|
||||
fn join(&self, path: impl AsRef<Path>) -> PathBuf {
|
||||
self.0.join(path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn library() -> (Library, RepertoireId) {
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create(
|
||||
"King and queen pawn",
|
||||
&chess_core::parse_str("1. e4 (1. d4) e5 *").game,
|
||||
)
|
||||
.unwrap();
|
||||
(library, id)
|
||||
}
|
||||
|
||||
fn child(editor: &RepertoireEditorUi, index: usize) -> NodeId {
|
||||
editor.tree.game().children(editor.tree.root())[index]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn main_answer_assignment_is_validated_and_clear_restores_pgn_default() {
|
||||
let (library, id) = library();
|
||||
let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap();
|
||||
let root_fen = fen4(editor.tree.game().start().position());
|
||||
let pgn = library.repertoire(&id).unwrap().pgn.clone();
|
||||
|
||||
let wrong_side = editor
|
||||
.assign_main_answer_checked(&root_fen, "d2d4", LearningSide::Black)
|
||||
.unwrap_err();
|
||||
assert!(!wrong_side.contains("d2d4"));
|
||||
let missing_move = editor
|
||||
.assign_main_answer_checked(&root_fen, "c2c4", LearningSide::White)
|
||||
.unwrap_err();
|
||||
assert!(!missing_move.contains("c2c4"));
|
||||
assert!(
|
||||
editor
|
||||
.draft
|
||||
.repertoire(&id)
|
||||
.unwrap()
|
||||
.main_answer_overrides
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
editor.select(child(&editor, 1));
|
||||
editor.set_selected_main_answer().unwrap();
|
||||
assert_eq!(
|
||||
editor
|
||||
.draft
|
||||
.repertoire(&id)
|
||||
.unwrap()
|
||||
.main_answer_override(&root_fen),
|
||||
Some("d2d4")
|
||||
);
|
||||
assert_eq!(
|
||||
editor.effective_main_answer(editor.tree.root()).as_deref(),
|
||||
Some("d2d4")
|
||||
);
|
||||
assert_eq!(editor.tree.game().children(editor.tree.root()).len(), 2);
|
||||
assert_eq!(editor.draft.repertoire(&id).unwrap().pgn, pgn);
|
||||
|
||||
editor.clear_selected_main_answer();
|
||||
assert_eq!(
|
||||
editor
|
||||
.draft
|
||||
.repertoire(&id)
|
||||
.unwrap()
|
||||
.main_answer_override(&root_fen),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
editor.effective_main_answer(editor.tree.root()).as_deref(),
|
||||
Some("e2e4")
|
||||
);
|
||||
assert_eq!(editor.tree.game().children(editor.tree.root()).len(), 2);
|
||||
assert_eq!(editor.draft.repertoire(&id).unwrap().pgn, pgn);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_disable_and_override_roundtrip_preserve_source_and_shared_learning() {
|
||||
let dir = TestDir::new("roundtrip");
|
||||
let source = dir.join("source.pgn");
|
||||
let source_bytes = b"[Event \"Original\"]\n\n1. e4 (1. d4) e5 *\n";
|
||||
std::fs::write(&source, source_bytes).unwrap();
|
||||
let (mut library, id) = library();
|
||||
let second = library
|
||||
.create(
|
||||
"Shared transposition",
|
||||
&chess_core::parse_str("1. e4 (1. d4) e5 *").game,
|
||||
)
|
||||
.unwrap();
|
||||
library.repertoire_mut(&id).unwrap().path = Some(source.clone());
|
||||
let original_pgn = library.repertoire(&id).unwrap().pgn.clone();
|
||||
let library_store = LibraryStore::new(dir.join("library.json"));
|
||||
library_store.save(&mut library).unwrap();
|
||||
|
||||
let mut learning = LearningData::default();
|
||||
let root_fen = fen4(library.repertoire(&id).unwrap().game().start().position());
|
||||
let key = LearningItemKey::local(root_fen.clone(), "d2d4");
|
||||
let shared_item = {
|
||||
let item = learning.ensure_item(key.clone());
|
||||
item.introduced = true;
|
||||
item.correct_streak = 4;
|
||||
item.correct_count = 7;
|
||||
item.wrong_count = 2;
|
||||
item.next_review_at = Some(1_900_000_000);
|
||||
item.independent_response_times_ms = vec![500, 700, 900];
|
||||
item.wrong_move_histogram.insert(
|
||||
"c2c4".into(),
|
||||
WrongMoveStats {
|
||||
count: 2,
|
||||
last_at: 1_800_000_000,
|
||||
},
|
||||
);
|
||||
item.clone()
|
||||
};
|
||||
let learning_store = LearningStore::new(dir.join("learning.json"));
|
||||
let learning_data = LearningStoreData {
|
||||
learning: learning.clone(),
|
||||
..LearningStoreData::default()
|
||||
};
|
||||
std::fs::write(
|
||||
learning_store.path(),
|
||||
serde_json::to_vec_pretty(&learning_data).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let learning_bytes = std::fs::read(learning_store.path()).unwrap();
|
||||
|
||||
let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap();
|
||||
editor.set_learning(&learning);
|
||||
editor.select(child(&editor, 1));
|
||||
editor.set_selected_main_answer().unwrap();
|
||||
editor.set_selected_disabled(true).unwrap();
|
||||
editor.draft.repertoire_mut(&id).unwrap().set_max_plies(7);
|
||||
assert_eq!(
|
||||
editor
|
||||
.draft
|
||||
.repertoire(&id)
|
||||
.unwrap()
|
||||
.main_answer_override(&root_fen),
|
||||
Some("d2d4")
|
||||
);
|
||||
assert_eq!(
|
||||
editor.effective_main_answer(editor.tree.root()).as_deref(),
|
||||
Some("d2d4")
|
||||
);
|
||||
|
||||
let analytics = editor.selected_analytics().unwrap().unwrap();
|
||||
assert_eq!(analytics.key, key);
|
||||
assert_eq!(analytics.correct_streak, 4);
|
||||
assert_eq!(analytics.correct_count, 7);
|
||||
assert_eq!(analytics.response_time_median_ms, Some(700.0));
|
||||
|
||||
let saved = editor.save(&library_store).unwrap();
|
||||
assert!(!editor.has_unsaved());
|
||||
assert_eq!(saved.repertoire(&id).unwrap().max_plies, 7);
|
||||
assert_eq!(saved.repertoire(&id).unwrap().disabled_prefixes.len(), 1);
|
||||
assert_eq!(saved.repertoire(&id).unwrap().pgn, original_pgn);
|
||||
assert!(saved.repertoire(&second).is_some());
|
||||
assert_eq!(std::fs::read(&source).unwrap(), source_bytes);
|
||||
assert_eq!(
|
||||
std::fs::read(learning_store.path()).unwrap(),
|
||||
learning_bytes
|
||||
);
|
||||
|
||||
editor.set_selected_disabled(false).unwrap();
|
||||
assert_eq!(
|
||||
editor
|
||||
.draft
|
||||
.repertoire(&id)
|
||||
.unwrap()
|
||||
.main_answer_override(&root_fen),
|
||||
Some("d2d4")
|
||||
);
|
||||
let saved = editor.save(&library_store).unwrap();
|
||||
assert!(saved.repertoire(&id).unwrap().disabled_prefixes.is_empty());
|
||||
assert_eq!(saved.repertoire(&id).unwrap().pgn, original_pgn);
|
||||
assert_eq!(std::fs::read(&source).unwrap(), source_bytes);
|
||||
assert_eq!(
|
||||
std::fs::read(learning_store.path()).unwrap(),
|
||||
learning_bytes
|
||||
);
|
||||
|
||||
let loaded = library_store.load().unwrap();
|
||||
assert_eq!(loaded.repertoire(&id).unwrap().max_plies, 7);
|
||||
assert!(loaded.repertoire(&id).unwrap().disabled_prefixes.is_empty());
|
||||
assert_eq!(loaded.repertoire(&id).unwrap().pgn, original_pgn);
|
||||
let restored_learning = learning_store.load().unwrap();
|
||||
assert_eq!(restored_learning.learning.item(&key), Some(&shared_item));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_restores_the_whole_draft_without_saving() {
|
||||
let dir = TestDir::new("cancel");
|
||||
let (mut library, id) = library();
|
||||
let library_store = LibraryStore::new(dir.join("library.json"));
|
||||
library_store.save(&mut library).unwrap();
|
||||
let before = std::fs::read(library_store.path()).unwrap();
|
||||
let original = library.repertoire(&id).unwrap().clone();
|
||||
let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap();
|
||||
editor.select(child(&editor, 1));
|
||||
editor.set_selected_main_answer().unwrap();
|
||||
editor.set_selected_disabled(true).unwrap();
|
||||
editor.draft.repertoire_mut(&id).unwrap().set_max_plies(3);
|
||||
assert!(editor.has_unsaved());
|
||||
|
||||
editor.cancel();
|
||||
|
||||
assert!(!editor.has_unsaved());
|
||||
assert_eq!(editor.draft.repertoire(&id), Some(&original));
|
||||
assert_eq!(editor.selected, editor.tree.root());
|
||||
assert_eq!(std::fs::read(library_store.path()).unwrap(), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rav_rows_are_indented_without_flattening_the_mainline() {
|
||||
let (library, id) = library();
|
||||
let editor = RepertoireEditorUi::new(&library, id).unwrap();
|
||||
let rows = tree_rows(&editor.tree);
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert_eq!(rows[0].indentation, 0);
|
||||
assert!(!rows[0].variation);
|
||||
assert_eq!(rows[1].indentation, 0);
|
||||
assert!(!rows[1].variation);
|
||||
assert_eq!(rows[2].indentation, 1);
|
||||
assert!(rows[2].variation);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,5 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
use std::{sync::mpsc, time::Duration};
|
||||
|
||||
use chess_core::shakmaty::{Chess, Color, Move, Position, Square, uci::UciMove};
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -168,6 +168,12 @@ pub struct Settings {
|
|||
trainer::repertoire::QueueMode,
|
||||
),
|
||||
>,
|
||||
#[serde(default)]
|
||||
pub repertoire_priorities:
|
||||
std::collections::HashMap<String, trainer::repertoire::LearningPriority>,
|
||||
#[serde(default)]
|
||||
pub repertoire_context_policies:
|
||||
std::collections::HashMap<String, trainer::repertoire::LearningContextPolicy>,
|
||||
}
|
||||
|
||||
/// Options of the opponent preparation; its engine search is the game analysis's.
|
||||
|
|
@ -236,6 +242,8 @@ impl Default for Settings {
|
|||
play: Default::default(),
|
||||
prep: PrepSettings::default(),
|
||||
repertoire_modes: Default::default(),
|
||||
repertoire_priorities: Default::default(),
|
||||
repertoire_context_policies: Default::default(),
|
||||
repertoire_flow_version: 0,
|
||||
}
|
||||
}
|
||||
|
|
@ -247,7 +255,13 @@ impl Settings {
|
|||
return false;
|
||||
}
|
||||
for (_, queue) in self.repertoire_modes.values_mut() {
|
||||
*queue = trainer::repertoire::QueueMode::Practice;
|
||||
if matches!(
|
||||
queue,
|
||||
trainer::repertoire::QueueMode::Practice
|
||||
| trainer::repertoire::QueueMode::SpacedRepetition
|
||||
) {
|
||||
*queue = trainer::repertoire::QueueMode::SpacedRepetition;
|
||||
}
|
||||
}
|
||||
self.repertoire_flow_version = 1;
|
||||
true
|
||||
|
|
@ -389,7 +403,7 @@ mod tests {
|
|||
#[cfg(test)]
|
||||
mod repertoire_flow_tests {
|
||||
use super::*;
|
||||
use trainer::repertoire::{QueueMode, TrainingMode};
|
||||
use trainer::repertoire::{LearningPriority, QueueMode, TrainingMode};
|
||||
#[test]
|
||||
fn old_training_preferences_migrate_once_without_resetting_color_or_custom_settings() {
|
||||
let mut settings = Settings::default();
|
||||
|
|
@ -400,7 +414,11 @@ mod repertoire_flow_tests {
|
|||
assert!(settings.migrate_repertoire_flow());
|
||||
assert_eq!(
|
||||
settings.repertoire_modes["old"],
|
||||
(TrainingMode::Black, QueueMode::Practice)
|
||||
(TrainingMode::Black, QueueMode::SpacedRepetition)
|
||||
);
|
||||
settings.repertoire_modes.insert(
|
||||
"review".into(),
|
||||
(TrainingMode::White, QueueMode::ReviewInOrder),
|
||||
);
|
||||
settings.repertoire_modes.get_mut("old").unwrap().1 = QueueMode::SpacedRepetition;
|
||||
assert!(!settings.migrate_repertoire_flow());
|
||||
|
|
@ -408,5 +426,62 @@ mod repertoire_flow_tests {
|
|||
settings.repertoire_modes["old"].1,
|
||||
QueueMode::SpacedRepetition
|
||||
);
|
||||
assert_eq!(
|
||||
settings.repertoire_modes["review"].1,
|
||||
QueueMode::ReviewInOrder
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn learning_mode_and_priority_roundtrip_and_default_for_legacy_settings() {
|
||||
let mut settings = Settings::default();
|
||||
settings.repertoire_modes.insert(
|
||||
"opening".into(),
|
||||
(TrainingMode::Black, QueueMode::LeastRecent),
|
||||
);
|
||||
settings
|
||||
.repertoire_priorities
|
||||
.insert("opening".into(), LearningPriority::MainLinesFirst);
|
||||
|
||||
let json = serde_json::to_string(&settings).unwrap();
|
||||
let restored: Settings = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(
|
||||
restored.repertoire_modes["opening"],
|
||||
(TrainingMode::Black, QueueMode::LeastRecent)
|
||||
);
|
||||
assert_eq!(
|
||||
restored.repertoire_priorities["opening"],
|
||||
LearningPriority::MainLinesFirst
|
||||
);
|
||||
|
||||
let legacy: Settings = serde_json::from_str("{}").unwrap();
|
||||
assert!(legacy.repertoire_priorities.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn context_policies_roundtrip_and_default_for_legacy_json() {
|
||||
let policy = trainer::repertoire::LearningContextPolicy {
|
||||
reinforce_minimum_correct: 5,
|
||||
reinforce_minimum_days: Some(14),
|
||||
dont_show_start_moves_threshold: 8,
|
||||
use_fixed_piece_speed: false,
|
||||
move_speed_adjustment: 1.5,
|
||||
consider_leadup_moves: true,
|
||||
};
|
||||
let mut settings = Settings::default();
|
||||
settings
|
||||
.repertoire_context_policies
|
||||
.insert("opening".into(), policy);
|
||||
|
||||
let json = serde_json::to_string_pretty(&settings).unwrap();
|
||||
let restored: Settings = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(restored.repertoire_context_policies["opening"], policy);
|
||||
|
||||
let legacy = r#"{
|
||||
"repertoire_modes": {},
|
||||
"repertoire_priorities": {}
|
||||
}"#;
|
||||
let restored: Settings = serde_json::from_str(legacy).unwrap();
|
||||
assert!(restored.repertoire_context_policies.is_empty());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue