wip: opening trainer v2 desktop UI (repertoires, session, lines), i18n, devhooks doc
One repertoire_ui test still fails (see docs/qa/opening-trainer-v2-devhooks.md).
This commit is contained in:
parent
3db35e4d03
commit
98f0e4749f
18 changed files with 9865 additions and 13790 deletions
File diff suppressed because it is too large
Load diff
|
|
@ -1,763 +0,0 @@
|
|||
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 HEADER_HEIGHT: f32 = 40.0;
|
||||
const ROW_HEIGHT: f32 = 32.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]));
|
||||
}
|
||||
|
||||
ui.add(
|
||||
egui::Label::new(tr(
|
||||
"Continuations to review. Shared moves may appear in several variations.",
|
||||
))
|
||||
.wrap(),
|
||||
);
|
||||
ui.add_space(6.0);
|
||||
let include_repertoire = include_repertoire_names(rows);
|
||||
let mut clicked = None;
|
||||
show_table(
|
||||
ui,
|
||||
rows,
|
||||
names,
|
||||
labels,
|
||||
include_repertoire,
|
||||
selected.as_ref(),
|
||||
&mut clicked,
|
||||
);
|
||||
if let Some(selection) = clicked {
|
||||
*selected = Some(selection);
|
||||
}
|
||||
|
||||
if 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]) -> bool {
|
||||
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_table(
|
||||
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 numeric_width = (ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4 / 3.0;
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_branches")
|
||||
.striped(true)
|
||||
.sense(Sense::click())
|
||||
.max_scroll_height(192.0)
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().clip(true))
|
||||
.column(Column::exact(numeric_width).clip(true))
|
||||
.column(Column::exact(numeric_width).clip(true))
|
||||
.column(Column::exact(numeric_width).clip(true))
|
||||
.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in ["Variation start", "Learnt", "Due now", "Accuracy"]
|
||||
.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 [
|
||||
format!("{} / {}", row.summary.learnt, row.summary.total),
|
||||
row.summary.due.to_string(),
|
||||
format_percent(row.summary.accuracy_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 = [
|
||||
(
|
||||
"Learnt moves",
|
||||
format!("{} / {}", row.summary.learnt, row.summary.total),
|
||||
),
|
||||
("Due now", row.summary.due.to_string()),
|
||||
("Not practised yet", row.summary.unseen.to_string()),
|
||||
("Accuracy", format_percent(row.summary.accuracy_percent)),
|
||||
];
|
||||
show_details_rows(ui, &details);
|
||||
}
|
||||
|
||||
fn show_details_rows(ui: &mut Ui, details: &[(&'static str, String)]) {
|
||||
let label_width = (ui.available_width() * 0.36).clamp(110.0, 160.0);
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_details")
|
||||
.vscroll(false)
|
||||
.cell_layout(Layout::left_to_right(Align::Min))
|
||||
.column(Column::exact(label_width).clip(true))
|
||||
.column(Column::remainder().at_least(80.0).clip(true))
|
||||
.body(|body| {
|
||||
body.rows(36.0, details.len(), |mut row| {
|
||||
let (label, value) = &details[row.index()];
|
||||
row.col(|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE))
|
||||
.wrap(),
|
||||
);
|
||||
});
|
||||
row.col(|ui| {
|
||||
ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap());
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn header_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response {
|
||||
ui.add(egui::Label::new(RichText::new(text).strong().size(BODY_TEXT_SIZE)).wrap())
|
||||
}
|
||||
|
||||
fn text_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response {
|
||||
ui.add(egui::Label::new(RichText::new(text).size(BODY_TEXT_SIZE)).truncate())
|
||||
}
|
||||
|
||||
fn format_percent(value: Option<f64>) -> String {
|
||||
value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %"))
|
||||
}
|
||||
|
||||
#[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 = fixture.names.clone();
|
||||
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 unified_layout_stays_in_bounds_in_light_and_dark() {
|
||||
let fixture = fixture();
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(1400.0, 900.0), (960.0, 600.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);
|
||||
for key in [
|
||||
"Variation start",
|
||||
"Learnt",
|
||||
"Due now",
|
||||
"Accuracy",
|
||||
"Learnt moves",
|
||||
"Not practised yet",
|
||||
] {
|
||||
assert!(
|
||||
has_translated_text(&shapes, key),
|
||||
"missing header/detail {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_fit_accepted_matrix_in_russian_and_german() {
|
||||
let cases = [
|
||||
["Начало варианта", "Изучено", "Повторить", "Точность"],
|
||||
["Variantenanfang", "Gelernt", "Wiederholen", "Genauigkeit"],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] {
|
||||
for headers in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, height),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
let numeric_width =
|
||||
(ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4
|
||||
/ 3.0;
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_branches_wide_header_test")
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(120.0).clip(true));
|
||||
for _ in 0..3 {
|
||||
table = table.column(Column::exact(numeric_width).clip(true));
|
||||
}
|
||||
table.header(HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
assert_bounds(&shapes, width, height);
|
||||
for expected in headers {
|
||||
let (rect, clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == *expected =>
|
||||
{
|
||||
Some((
|
||||
egui::Rect::from_min_size(text.pos, text.galley.size()),
|
||||
clipped.clip_rect,
|
||||
text.galley.text().lines().count(),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
panic!("missing full header {expected} at {width}x{height}")
|
||||
});
|
||||
assert!(lines <= 2, "header wraps too much: {expected}");
|
||||
assert!(
|
||||
rect.min.x >= clip.min.x - 0.1
|
||||
&& rect.min.y >= clip.min.y - 0.1
|
||||
&& rect.max.x <= clip.max.x + 0.1
|
||||
&& rect.max.y <= clip.max.y + 0.1,
|
||||
"clipped header {expected} at {width}x{height}: {rect:?} {clip:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn 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 ["Learnt moves", "Due now", "Not practised yet", "Accuracy"] {
|
||||
assert!(has_translated_text(&shapes, key), "missing detail {key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn details_keep_long_labels_readable_at_all_widths() {
|
||||
let cases: Vec<Vec<(&str, String)>> = vec![
|
||||
vec![
|
||||
("Новый", "2".to_owned()),
|
||||
("Изучается", "1".to_owned()),
|
||||
("Изучено", "4".to_owned()),
|
||||
("Не подтверждено", "1".to_owned()),
|
||||
("К повторению", "3".to_owned()),
|
||||
("Точность", "75 %".to_owned()),
|
||||
("Последняя тренировка", "2026-11-04 08:26".to_owned()),
|
||||
],
|
||||
vec![
|
||||
("Neu", "2".to_owned()),
|
||||
("Wird gelernt", "1".to_owned()),
|
||||
("Gelernt", "4".to_owned()),
|
||||
("Nicht bestätigt", "1".to_owned()),
|
||||
("Fällig", "3".to_owned()),
|
||||
("Genauigkeit", "75 %".to_owned()),
|
||||
("Zuletzt trainiert", "2026-11-04 08:26".to_owned()),
|
||||
],
|
||||
];
|
||||
for visuals in [egui::Visuals::light(), egui::Visuals::dark()] {
|
||||
for width in [320.0, 360.0, 420.0, 640.0] {
|
||||
for details in &cases {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_visuals(visuals.clone());
|
||||
let mut expected_label_width = 0.0;
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(width, 700.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
expected_label_width =
|
||||
(ui.available_width() * 0.36).clamp(110.0, 160.0);
|
||||
show_details_rows(ui, details);
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
assert_bounds(&shapes, width, 700.0);
|
||||
for (label, _) in details {
|
||||
let (clip, lines) = shapes
|
||||
.iter()
|
||||
.find_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text)
|
||||
if text.galley.text().replace('\n', " ") == *label =>
|
||||
{
|
||||
Some((clipped.clip_rect, text.galley.text().lines().count()))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing full label {label} at {width}"));
|
||||
assert!(
|
||||
(clip.width() - expected_label_width).abs() < 0.1,
|
||||
"label column at {width}: {clip:?}, expected {expected_label_width}: {label}"
|
||||
);
|
||||
assert!(lines <= 2, "label wraps too much at {width}: {label}");
|
||||
}
|
||||
assert!(has_text(&shapes, "2026-11-04 08:26"));
|
||||
assert!(has_text(&shapes, "75 %"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_accuracy_renders_as_dashes_in_table_and_details() {
|
||||
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 >= 2,
|
||||
"expected null accuracy in table and details: {dashes}"
|
||||
);
|
||||
assert_eq!(format_percent(None), "—");
|
||||
assert_eq!(format_percent(Some(75.0)), "75 %");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_selected_notation_wraps_in_details_and_row_retains_wide_column() {
|
||||
let mut fixture = fixture();
|
||||
fixture.rows.truncate(1);
|
||||
fixture.rows[0].branch_root = (0..40).map(|i| format!("move{i}")).collect();
|
||||
let notation: Vec<_> = (1..=40).map(|i| format!("{i}.Nf3")).collect();
|
||||
fixture.labels.insert(
|
||||
(
|
||||
fixture.rows[0].repertoire_id.clone(),
|
||||
fixture.rows[0].branch_root.clone(),
|
||||
),
|
||||
notation,
|
||||
);
|
||||
let expected = san_path(&fixture.rows[0], &fixture.labels);
|
||||
for width in [960.0, 1400.0] {
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
width,
|
||||
900.0,
|
||||
0.0,
|
||||
Vec::new(),
|
||||
&fixture.rows,
|
||||
&fixture.names,
|
||||
&fixture.labels,
|
||||
&mut selected,
|
||||
);
|
||||
assert_bounds(&shapes, width, 900.0);
|
||||
let texts: Vec<_> = shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text() == expected => {
|
||||
Some((clipped, text))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(texts.len(), 2, "table row and full selected notation");
|
||||
assert!(texts[0].0.clip_rect.width() >= width * 0.5);
|
||||
assert_eq!(
|
||||
texts[0].1.galley.rows.len(),
|
||||
1,
|
||||
"table notation stays on one line"
|
||||
);
|
||||
assert!(
|
||||
texts[1].1.galley.rows.len() > 1,
|
||||
"full selected notation wraps"
|
||||
);
|
||||
assert!(has_text(&shapes, "4 / 8"));
|
||||
}
|
||||
}
|
||||
|
||||
#[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"));
|
||||
}
|
||||
}
|
||||
|
|
@ -1,507 +0,0 @@
|
|||
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 [
|
||||
("Still learning", palette[0], Marker::Circle),
|
||||
("Learnt moves", palette[1], Marker::Square),
|
||||
("Long overdue learnt moves", 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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,204 +0,0 @@
|
|||
use trainer::repertoire::LearningContextPolicy;
|
||||
|
||||
use crate::i18n::tr;
|
||||
|
||||
fn hint(ui: &mut egui::Ui, text: &'static str) {
|
||||
ui.add(egui::Label::new(egui::RichText::new(tr(text)).weak()).wrap());
|
||||
}
|
||||
|
||||
pub fn show(ui: &mut egui::Ui, policy: &mut LearningContextPolicy) -> bool {
|
||||
let before = *policy;
|
||||
ui.strong(tr("Moves before the task"));
|
||||
hint(ui, "The app shows the moves leading to the task position.");
|
||||
ui.add_space(6.0);
|
||||
ui.checkbox(
|
||||
&mut policy.consider_leadup_moves,
|
||||
tr("Ask me to play preceding moves"),
|
||||
);
|
||||
ui.add_enabled_ui(
|
||||
policy.consider_leadup_moves || !policy.use_fixed_piece_speed,
|
||||
|ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Correct answers in a row"));
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut policy.reinforce_minimum_correct).range(0..=u32::MAX),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
hint(
|
||||
ui,
|
||||
"Ask until this streak is reached. This also sets the maximum acceleration point for adaptive playback.",
|
||||
);
|
||||
ui.add_space(6.0);
|
||||
ui.add_enabled_ui(policy.consider_leadup_moves, |ui| {
|
||||
let mut enabled = policy.reinforce_minimum_days.is_some();
|
||||
if ui
|
||||
.checkbox(&mut enabled, tr("Review ahead of schedule"))
|
||||
.changed()
|
||||
{
|
||||
policy.reinforce_minimum_days = enabled.then_some(7);
|
||||
}
|
||||
ui.add_enabled_ui(enabled, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Days before the due date"));
|
||||
let mut days = policy.reinforce_minimum_days.unwrap_or(7);
|
||||
if ui
|
||||
.add(egui::DragValue::new(&mut days).range(0..=u32::MAX))
|
||||
.changed()
|
||||
{
|
||||
policy.reinforce_minimum_days = Some(days);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
hint(ui, "Also ask moves that are already due.");
|
||||
ui.add_space(10.0);
|
||||
ui.separator();
|
||||
ui.strong(tr("Skip a familiar opening"));
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Skip after this many correct answers in a row"));
|
||||
ui.add(
|
||||
egui::DragValue::new(&mut policy.dont_show_start_moves_threshold).range(0..=u32::MAX),
|
||||
);
|
||||
});
|
||||
hint(
|
||||
ui,
|
||||
"Each of your opening moves must reach this streak. 0 means always show the opening.",
|
||||
);
|
||||
ui.add_space(10.0);
|
||||
ui.separator();
|
||||
ui.strong(tr("Playback speed"));
|
||||
let mut adaptive = !policy.use_fixed_piece_speed;
|
||||
if ui
|
||||
.checkbox(&mut adaptive, tr("Speed up familiar moves"))
|
||||
.changed()
|
||||
{
|
||||
policy.use_fixed_piece_speed = !adaptive;
|
||||
}
|
||||
hint(
|
||||
ui,
|
||||
"Base animation speed comes from board settings. Familiar moves play up to twice as fast.",
|
||||
);
|
||||
if adaptive {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(tr("Base speed multiplier"));
|
||||
ui.add(egui::DragValue::new(&mut policy.move_speed_adjustment)
|
||||
.range(-2.0..=2.0).speed(0.05).fixed_decimals(2).suffix(" ×"))
|
||||
.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×."));
|
||||
});
|
||||
hint(ui, "0 or less uses the minimum speed (0.25×).");
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
hint(ui, "Learning counters do not use these playback settings.");
|
||||
*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 context_options_preserve_values_until_changed_and_enable_dependencies() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut policy = LearningContextPolicy::default();
|
||||
let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 0.0, Vec::new(), &mut policy);
|
||||
assert!(!changed);
|
||||
assert_eq!(policy, LearningContextPolicy::default());
|
||||
let leadup = text_position(&shapes, "Ask me to play preceding moves").unwrap();
|
||||
let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 1.0, click(leadup), &mut policy);
|
||||
assert!(changed);
|
||||
assert!(policy.consider_leadup_moves);
|
||||
let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 2.0, Vec::new(), &mut policy);
|
||||
assert!(!changed);
|
||||
let days = text_position(&shapes, "Review ahead of schedule").unwrap();
|
||||
let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 3.0, click(days), &mut policy);
|
||||
assert!(changed);
|
||||
assert_eq!(policy.reinforce_minimum_days, Some(7));
|
||||
let speed = text_position(&shapes, "Speed up familiar moves").unwrap();
|
||||
let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 4.0, click(speed), &mut policy);
|
||||
assert!(changed);
|
||||
assert!(!policy.use_fixed_piece_speed);
|
||||
assert_eq!(policy.move_speed_adjustment, 1.0);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -30,16 +30,6 @@ 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)]
|
||||
|
|
@ -48,6 +38,12 @@ mod notation;
|
|||
mod online;
|
||||
#[cfg(not(web))]
|
||||
mod online_ui;
|
||||
#[cfg(not(web))]
|
||||
mod opening_layout;
|
||||
#[cfg(not(web))]
|
||||
mod opening_lines;
|
||||
#[cfg(not(web))]
|
||||
mod opening_session;
|
||||
mod own_db;
|
||||
pub mod platform;
|
||||
mod play;
|
||||
|
|
@ -56,10 +52,6 @@ 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;
|
||||
mod review;
|
||||
mod review_engine;
|
||||
|
|
|
|||
498
apps/desktop/src/opening_layout.rs
Normal file
498
apps/desktop/src/opening_layout.rs
Normal file
|
|
@ -0,0 +1,498 @@
|
|||
//! What the three opening-training screens share (docs/design/opening-trainer-v2-spec.md
|
||||
//! §1): the frame of the game screen, the card, the board's PGN marks and the texts
|
||||
//! about moves, sides and dates.
|
||||
|
||||
use chess_core::shakmaty::{Color, Square, uci::UciMove};
|
||||
use chess_core::{Annotation, CommentPart, Game, MoveKind, NodeId, parse_comment};
|
||||
use egui::{Color32, RichText, Ui, vec2};
|
||||
use trainer::repertoire::{LearningSide, RepertoireId, TrainingMode};
|
||||
|
||||
use crate::board::{Arrow, Badge};
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::settings::Settings;
|
||||
|
||||
/// The panel's least width (the game's reference tab, `REF_MIN`).
|
||||
const SIDE_LEAST: f32 = 320.0;
|
||||
/// Under a stacked board: the panel's least height (`STACK_BOTTOM_MIN`).
|
||||
const STACK_BOTTOM_MIN: f32 = 300.0;
|
||||
const BOARD_MIN: f32 = 220.0;
|
||||
/// Space between the blocks of the panel.
|
||||
pub(crate) const GAP: f32 = 6.0;
|
||||
/// The new moves of one session and of "10 more new".
|
||||
pub(crate) const NEW_PER_SESSION: usize = 10;
|
||||
|
||||
/// Header, side panel and board in the places of the game screen. The same panel id on
|
||||
/// every screen of the section: switching screens never moves the board.
|
||||
pub(crate) fn screen<T: ?Sized>(
|
||||
ui: &mut Ui,
|
||||
this: &mut T,
|
||||
header: impl FnOnce(&mut T, &mut Ui),
|
||||
side: impl FnOnce(&mut T, &mut Ui),
|
||||
board: impl FnOnce(&mut T, &mut Ui),
|
||||
) {
|
||||
egui::Panel::top("opening_header").show(ui, |ui| header(this, ui));
|
||||
let width = ui.available_width();
|
||||
let height = ui.available_height();
|
||||
let board_side = (height - 16.0).min(width - SIDE_LEAST - 24.0);
|
||||
let board_stack = (width - 16.0).min(height - STACK_BOTTOM_MIN - 16.0);
|
||||
let stacked = board_stack >= 1.25 * board_side;
|
||||
let panel = if stacked {
|
||||
let most = (height - BOARD_MIN - 16.0).max(STACK_BOTTOM_MIN);
|
||||
let rest = (height - board_stack - 16.0).clamp(STACK_BOTTOM_MIN, most);
|
||||
egui::Panel::bottom("opening_side_stacked")
|
||||
.resizable(true)
|
||||
.default_size(rest)
|
||||
.size_range(STACK_BOTTOM_MIN..=most)
|
||||
.show(ui, |ui| side(this, ui))
|
||||
} else {
|
||||
let board = height - 16.0;
|
||||
let most = (width - BOARD_MIN - 24.0).max(SIDE_LEAST);
|
||||
let room = (width - board - 24.0).clamp(SIDE_LEAST, most);
|
||||
egui::Panel::right("opening_side")
|
||||
.resizable(true)
|
||||
.default_size((width * 0.4).clamp(260.0, 460.0).min(room))
|
||||
.size_range(SIDE_LEAST..=most)
|
||||
.show(ui, |ui| side(this, ui))
|
||||
};
|
||||
crate::widgets::check_panel("opening_side", &panel.response);
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
let area = ui.available_rect_before_wrap();
|
||||
let side = area.width().min(area.height()).max(1.0).floor();
|
||||
let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor();
|
||||
let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor();
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| board(this, ui));
|
||||
});
|
||||
}
|
||||
|
||||
/// The frame of a state card (the player's card of a game against the computer).
|
||||
pub(crate) fn card(ui: &Ui, active: bool, alert: bool) -> egui::Frame {
|
||||
let mut frame = egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(10, 6))
|
||||
.corner_radius(4)
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0,
|
||||
ui.visuals().widgets.noninteractive.bg_stroke.color,
|
||||
));
|
||||
if active {
|
||||
frame = frame.fill(ui.visuals().selection.bg_fill.gamma_multiply(0.35));
|
||||
}
|
||||
if alert {
|
||||
frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color));
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
/// A block of a fixed height: whatever it holds, what follows never moves.
|
||||
pub(crate) fn fixed_block<R>(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover());
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(rect)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add(&mut child)
|
||||
}
|
||||
|
||||
/// One line of text cut with "…", the whole text on hover.
|
||||
pub(crate) fn line(ui: &mut Ui, text: impl Into<RichText>) -> egui::Response {
|
||||
let text = text.into();
|
||||
let hover = text.text().to_owned();
|
||||
let response = ui.add(egui::Label::new(text).truncate());
|
||||
if hover.is_empty() {
|
||||
response
|
||||
} else {
|
||||
response.on_hover_text(hover)
|
||||
}
|
||||
}
|
||||
|
||||
/// The trained colour of a repertoire, kept in the settings since 2.2.0 (an old "both
|
||||
/// colours" repertoire opens for White).
|
||||
pub(crate) fn side_of(settings: &Settings, id: &RepertoireId) -> LearningSide {
|
||||
match settings.repertoire_modes.get(id.as_str()) {
|
||||
Some((TrainingMode::Black, _)) => LearningSide::Black,
|
||||
_ => LearningSide::White,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_side(settings: &mut Settings, id: &RepertoireId, side: LearningSide) {
|
||||
let mode = match side {
|
||||
LearningSide::White => TrainingMode::White,
|
||||
LearningSide::Black => TrainingMode::Black,
|
||||
};
|
||||
settings.repertoire_modes.insert(
|
||||
id.to_string(),
|
||||
(mode, trainer::repertoire::QueueMode::SpacedRepetition),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn king(side: LearningSide) -> &'static str {
|
||||
match side {
|
||||
LearningSide::White => "♔",
|
||||
LearningSide::Black => "♚",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn you_play(side: LearningSide) -> &'static str {
|
||||
tr(match side {
|
||||
LearningSide::White => "You play White",
|
||||
LearningSide::Black => "You play Black",
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn orientation(side: LearningSide) -> Color {
|
||||
side.color()
|
||||
}
|
||||
|
||||
/// "4. Ba4" or "4… Nf6" in the notation of the application.
|
||||
pub(crate) fn move_text(game: &Game, node: NodeId) -> Option<String> {
|
||||
let (number, color) = game.move_number(node)?;
|
||||
let san = crate::san::show(&game.game_move(node)?.san).into_owned();
|
||||
Some(match color {
|
||||
Color::White => format!("{number}. {san}"),
|
||||
Color::Black => format!("{number}… {san}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The symbol of a move's assessment (`!`, `?!` …) and its colour for text.
|
||||
pub(crate) fn assessment(game: &Game, node: NodeId, dark: bool) -> Option<(&'static str, Color32)> {
|
||||
let nag = game
|
||||
.node(node)?
|
||||
.nags()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|nag| nag.is_move_assessment())?;
|
||||
Some((
|
||||
nag.symbol()?,
|
||||
crate::notation::assessment_text_color(nag, dark)?,
|
||||
))
|
||||
}
|
||||
|
||||
/// The node reached from the root by these UCI moves.
|
||||
pub(crate) fn node_at(game: &Game, path: &[String]) -> Option<NodeId> {
|
||||
let mut at = NodeId::ROOT;
|
||||
for uci in path {
|
||||
let mv = uci
|
||||
.parse::<UciMove>()
|
||||
.ok()?
|
||||
.to_move(game.position(at)?)
|
||||
.ok()?;
|
||||
at = game.find_child(at, mv)?;
|
||||
}
|
||||
Some(at)
|
||||
}
|
||||
|
||||
/// The UCI moves from the root to a node.
|
||||
pub(crate) fn uci_path(game: &Game, node: NodeId) -> Vec<String> {
|
||||
game.path(node)
|
||||
.into_iter()
|
||||
.skip(1)
|
||||
.filter_map(|id| game.game_move(id).and_then(|mv| mv.uci()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// "C84 · Ruy Lopez: Closed": the most precise named position on the way to `node`.
|
||||
pub(crate) fn opening_text(game: &Game, node: NodeId) -> String {
|
||||
let keys: Vec<u64> = game
|
||||
.path(node)
|
||||
.into_iter()
|
||||
.filter_map(|id| game.position(id))
|
||||
.map(chess_openings::key)
|
||||
.collect();
|
||||
match chess_openings::deepest(&keys) {
|
||||
Some((_, id)) => {
|
||||
let opening = chess_openings::get(id);
|
||||
format!("{} · {}", opening.eco, opening.name)
|
||||
}
|
||||
None => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The start a repertoire's lines share: the last move before the first branching.
|
||||
pub(crate) fn common_start(game: &Game) -> NodeId {
|
||||
let mut at = NodeId::ROOT;
|
||||
while let [only] = game.children(at) {
|
||||
at = *only;
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
pub(crate) fn last_move(game: &Game, node: NodeId) -> Option<(Square, Square)> {
|
||||
match game.game_move(node)?.kind {
|
||||
MoveKind::Normal(mv) => Some((
|
||||
mv.from().unwrap_or_else(|| mv.to()),
|
||||
crate::board::ui_target(&mv),
|
||||
)),
|
||||
MoveKind::Null => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of a repertoire: the paths of its last moves, without switched-off
|
||||
/// branches, in PGN order.
|
||||
pub(crate) fn lines(game: &Game, disabled: impl Fn(&[String]) -> bool) -> Vec<Vec<String>> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![(NodeId::ROOT, Vec::new())];
|
||||
while let Some((node, path)) = stack.pop() {
|
||||
let children: Vec<_> = game
|
||||
.children(node)
|
||||
.iter()
|
||||
.filter_map(|child| {
|
||||
let uci = game.game_move(*child)?.uci()?;
|
||||
let mut next = path.clone();
|
||||
next.push(uci);
|
||||
(!disabled(&next)).then_some((*child, next))
|
||||
})
|
||||
.collect();
|
||||
if children.is_empty() {
|
||||
if !path.is_empty() {
|
||||
out.push(path);
|
||||
}
|
||||
} else {
|
||||
stack.extend(children.into_iter().rev());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The end of the local day: "today" in the counts includes everything due before it.
|
||||
pub(crate) fn end_of_today() -> i64 {
|
||||
use chrono::{Local, TimeZone};
|
||||
let now = Local::now();
|
||||
let tomorrow = now.date_naive().succ_opt().unwrap_or(now.date_naive());
|
||||
tomorrow
|
||||
.and_hms_opt(0, 0, 0)
|
||||
.and_then(|midnight| Local.from_local_datetime(&midnight).earliest())
|
||||
.map_or(now.timestamp() + 24 * 60 * 60, |midnight| {
|
||||
midnight.timestamp() - 1
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn now() -> i64 {
|
||||
chrono::Local::now().timestamp()
|
||||
}
|
||||
|
||||
/// "today at 18:40", "tomorrow", "in 3 days", then a date as in the library.
|
||||
pub(crate) fn when(at: i64, now: i64) -> String {
|
||||
use chrono::{Local, TimeZone};
|
||||
let (Some(at), Some(now)) = (
|
||||
Local.timestamp_opt(at, 0).single(),
|
||||
Local.timestamp_opt(now, 0).single(),
|
||||
) else {
|
||||
return String::new();
|
||||
};
|
||||
let days = (at.date_naive() - now.date_naive()).num_days();
|
||||
match days {
|
||||
..=0 => trf("today at {time}", &[("time", &at.format("%H:%M"))]),
|
||||
1 => tr("tomorrow").to_owned(),
|
||||
2..=6 => trf("in {days} days", &[("days", &days)]),
|
||||
_ => at.format("%d.%m.%Y").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct BoardAnnotations {
|
||||
pub(crate) arrows: Vec<Arrow>,
|
||||
pub(crate) circles: Vec<(Square, Color32)>,
|
||||
pub(crate) badge: Option<Badge>,
|
||||
}
|
||||
|
||||
/// The marks of a PGN move on the board: its assessment badge, `[%cal]` arrows and
|
||||
/// `[%csl]` squares.
|
||||
pub(crate) fn pgn_annotations_at(game: &Game, at: NodeId) -> BoardAnnotations {
|
||||
let mut out = BoardAnnotations::default();
|
||||
let Some(node) = game.node(at) else {
|
||||
return out;
|
||||
};
|
||||
let square = node.game_move().and_then(|game_move| match game_move.kind {
|
||||
MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)),
|
||||
MoveKind::Null => None,
|
||||
});
|
||||
if let Some(square) = square {
|
||||
out.badge = node
|
||||
.nags()
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|nag| nag.is_move_assessment())
|
||||
.and_then(|nag| {
|
||||
Some(Badge {
|
||||
square,
|
||||
text: nag.symbol()?,
|
||||
color: crate::notation::assessment_color(nag)?,
|
||||
})
|
||||
});
|
||||
}
|
||||
for comment in node.comments_after() {
|
||||
for part in parse_comment(comment) {
|
||||
match part {
|
||||
CommentPart::Annotation(Annotation::Arrows(list)) => {
|
||||
out.arrows
|
||||
.extend(list.into_iter().map(|(color, from, to)| Arrow {
|
||||
from,
|
||||
to,
|
||||
color: crate::game_view::shape_color(color),
|
||||
weight: 0.9,
|
||||
}));
|
||||
}
|
||||
CommentPart::Annotation(Annotation::Squares(list)) => {
|
||||
out.circles.extend(
|
||||
list.into_iter()
|
||||
.map(|(color, square)| (square, crate::game_view::shape_color(color))),
|
||||
);
|
||||
}
|
||||
CommentPart::Text(_) | CommentPart::Annotation(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The position after a node, for a board that only shows it.
|
||||
pub(crate) fn position_of(game: &Game, node: NodeId) -> chess_core::shakmaty::Chess {
|
||||
game.position(node)
|
||||
.or_else(|| game.position(NodeId::ROOT))
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A board that only shows a position.
|
||||
pub(crate) fn still_board(
|
||||
ui: &mut Ui,
|
||||
state: &mut crate::board::BoardState,
|
||||
settings: &Settings,
|
||||
pos: &chess_core::shakmaty::Chess,
|
||||
orientation: Color,
|
||||
last_move: Option<(Square, Square)>,
|
||||
annotations: &BoardAnnotations,
|
||||
) {
|
||||
crate::board::BoardView {
|
||||
pos,
|
||||
orientation,
|
||||
last_move,
|
||||
arrows: &annotations.arrows,
|
||||
circles: &annotations.circles,
|
||||
badge: annotations.badge,
|
||||
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, state);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() {
|
||||
for (nag, symbol) in [
|
||||
(1, "!"),
|
||||
(2, "?"),
|
||||
(3, "!!"),
|
||||
(4, "??"),
|
||||
(5, "!?"),
|
||||
(6, "?!"),
|
||||
] {
|
||||
let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
let badge = pgn_annotations_at(&game, node).badge.unwrap();
|
||||
assert_eq!(badge.text, symbol);
|
||||
assert_eq!(badge.square, Square::E4);
|
||||
assert_eq!(
|
||||
badge.color,
|
||||
crate::notation::assessment_color(chess_core::Nag(nag)).unwrap()
|
||||
);
|
||||
}
|
||||
for (fen, san, expected) in [
|
||||
("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1),
|
||||
("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8),
|
||||
] {
|
||||
let game =
|
||||
chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"))
|
||||
.game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
assert_eq!(
|
||||
pgn_annotations_at(&game, node).badge.unwrap().square,
|
||||
expected
|
||||
);
|
||||
}
|
||||
let game = chess_core::parse_str("1. e4 $14 *").game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
assert!(
|
||||
pgn_annotations_at(&game, node).badge.is_none(),
|
||||
"position assessments are not move badges"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pgn_shapes_of_a_move_become_arrows_and_circles() {
|
||||
let game = chess_core::parse_str("1. e4 {[%cal Re2e4,Ge7e5] [%csl Ye4]} *").game;
|
||||
let node = game.main_child(NodeId::ROOT).unwrap();
|
||||
let marks = pgn_annotations_at(&game, node);
|
||||
assert_eq!(marks.arrows.len(), 2);
|
||||
assert_eq!(
|
||||
marks.arrows[0].color,
|
||||
crate::game_view::shape_color(chess_core::ShapeColor::Red)
|
||||
);
|
||||
assert_eq!(
|
||||
marks.circles,
|
||||
[(
|
||||
Square::E4,
|
||||
crate::game_view::shape_color(chess_core::ShapeColor::Yellow)
|
||||
)]
|
||||
);
|
||||
assert!(pgn_annotations_at(&game, NodeId::ROOT).badge.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_start_stops_before_the_first_branching() {
|
||||
let game = chess_core::parse_str("1. e4 e5 2. Nf3 (2. Bc4) Nc6 *").game;
|
||||
let start = common_start(&game);
|
||||
assert_eq!(uci_path(&game, start), ["e2e4", "e7e5"]);
|
||||
let game = chess_core::parse_str("1. e4 (1. d4) *").game;
|
||||
assert_eq!(common_start(&game), NodeId::ROOT);
|
||||
let game = chess_core::parse_str("*").game;
|
||||
assert_eq!(common_start(&game), NodeId::ROOT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_are_the_last_moves_in_pgn_order_without_switched_off_branches() {
|
||||
let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *").game;
|
||||
let all = lines(&game, |_| false);
|
||||
assert_eq!(
|
||||
all,
|
||||
[
|
||||
vec!["e2e4", "e7e5", "g1f3"],
|
||||
vec!["e2e4", "e7e5", "f1c4"],
|
||||
vec!["e2e4", "c7c5", "g1f3"],
|
||||
]
|
||||
.map(|line| line.into_iter().map(str::to_owned).collect::<Vec<_>>())
|
||||
);
|
||||
let without_c5 = lines(&game, |path| {
|
||||
path.starts_with(&["e2e4".into(), "c7c5".into()])
|
||||
});
|
||||
assert_eq!(without_c5.len(), 2);
|
||||
let node = node_at(&game, &all[1]).unwrap();
|
||||
assert_eq!(uci_path(&game, node), all[1]);
|
||||
assert_eq!(move_text(&game, node).as_deref(), Some("2. Bc4"));
|
||||
let black = node_at(&game, &all[2][..2]).unwrap();
|
||||
assert_eq!(move_text(&game, black).as_deref(), Some("1… c5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dates_read_as_today_tomorrow_days_then_a_date() {
|
||||
let at = 1_800_000_000;
|
||||
assert!(when(at + 60, at).contains(':'));
|
||||
assert_eq!(when(at + 24 * 3600, at), tr("tomorrow"));
|
||||
assert!(when(at + 3 * 24 * 3600, at).contains('3'));
|
||||
assert_eq!(when(at + 30 * 24 * 3600, at).len(), 10);
|
||||
assert!(end_of_today() >= now());
|
||||
assert!(end_of_today() - now() < 24 * 3600 + 3600);
|
||||
}
|
||||
}
|
||||
584
apps/desktop/src/opening_lines.rs
Normal file
584
apps/desktop/src/opening_lines.rs
Normal file
|
|
@ -0,0 +1,584 @@
|
|||
//! The «Lines» screen of opening training (spec §6.3): the repertoire's tree, read only,
|
||||
//! to choose what to train and which branches to leave out.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::mpsc;
|
||||
|
||||
use chess_core::shakmaty::Color;
|
||||
use chess_core::{Game, NodeId};
|
||||
use egui::{Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2};
|
||||
use trainer::repertoire::{
|
||||
LearningData, LearningItemKey, LearningSide, Library, Repertoire, RepertoireId, StatsScope,
|
||||
active_learning_memberships,
|
||||
};
|
||||
|
||||
use crate::board::BoardState;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::opening_layout::{self as layout, GAP, pgn_annotations_at};
|
||||
use crate::settings::Settings;
|
||||
|
||||
const SELECTED_H: f32 = 92.0;
|
||||
const TOOL_H: f32 = 28.0;
|
||||
const MAIN_W: f32 = 170.0;
|
||||
|
||||
pub enum LinesAction {
|
||||
Back,
|
||||
OpenSettings,
|
||||
/// Train the lines through this move (empty: every line).
|
||||
Train {
|
||||
through: Vec<String>,
|
||||
label: String,
|
||||
},
|
||||
/// Switch a branch off (`true`) or on again, from the move at this path.
|
||||
SetDisabled {
|
||||
path: Vec<String>,
|
||||
disabled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// The repertoire's own moves with their paths and which of them are learnt; computed
|
||||
/// off the frame.
|
||||
struct Counts {
|
||||
moves: Vec<(Vec<String>, LearningItemKey)>,
|
||||
learnt: BTreeSet<LearningItemKey>,
|
||||
}
|
||||
|
||||
pub struct OpeningLinesUi {
|
||||
id: RepertoireId,
|
||||
name: String,
|
||||
side: LearningSide,
|
||||
repertoire: Repertoire,
|
||||
game: Game,
|
||||
lines: Vec<Vec<String>>,
|
||||
cursor: NodeId,
|
||||
scroll: bool,
|
||||
orientation: Color,
|
||||
board: BoardState,
|
||||
counts: Option<Counts>,
|
||||
counting: Option<mpsc::Receiver<Result<Counts, String>>>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
impl OpeningLinesUi {
|
||||
pub fn new(
|
||||
library: &Library,
|
||||
learning: &LearningData,
|
||||
id: RepertoireId,
|
||||
side: LearningSide,
|
||||
cursor: Option<Vec<String>>,
|
||||
) -> Option<Self> {
|
||||
let repertoire = library.repertoire(&id)?.clone();
|
||||
let game = repertoire.game();
|
||||
let cursor = cursor
|
||||
.and_then(|path| layout::node_at(&game, &path))
|
||||
.unwrap_or(NodeId::ROOT);
|
||||
let lines = layout::lines(&game, |path| repertoire.is_prefix_disabled(path));
|
||||
let mut this = Self {
|
||||
id,
|
||||
name: repertoire.name.clone(),
|
||||
side,
|
||||
repertoire,
|
||||
game,
|
||||
lines,
|
||||
cursor,
|
||||
scroll: true,
|
||||
orientation: layout::orientation(side),
|
||||
board: BoardState::default(),
|
||||
counts: None,
|
||||
counting: None,
|
||||
error: None,
|
||||
};
|
||||
this.count(library, learning);
|
||||
Some(this)
|
||||
}
|
||||
|
||||
pub fn id(&self) -> &RepertoireId {
|
||||
&self.id
|
||||
}
|
||||
|
||||
pub fn cursor_path(&self) -> Vec<String> {
|
||||
layout::uci_path(&self.game, self.cursor)
|
||||
}
|
||||
|
||||
/// The library changed (a branch switched off or on): recount, keep the move.
|
||||
pub fn refresh(&mut self, library: &Library, learning: &LearningData) {
|
||||
if let Some(repertoire) = library.repertoire(&self.id) {
|
||||
self.repertoire = repertoire.clone();
|
||||
self.name = repertoire.name.clone();
|
||||
self.lines = layout::lines(&self.game, |path| repertoire.is_prefix_disabled(path));
|
||||
}
|
||||
self.count(library, learning);
|
||||
}
|
||||
|
||||
fn count(&mut self, library: &Library, learning: &LearningData) {
|
||||
let library = library.clone();
|
||||
let learning = learning.clone();
|
||||
let scope = StatsScope::for_repertoire(self.id.clone(), self.side, layout::now());
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.counting = Some(rx);
|
||||
if let Err(error) = crate::platform::spawn("repertoire-lines-count", move || {
|
||||
let result = active_learning_memberships(&library, &scope)
|
||||
.map(|memberships| {
|
||||
let learnt = memberships
|
||||
.iter()
|
||||
.filter(|membership| {
|
||||
learning
|
||||
.item(&membership.key)
|
||||
.is_some_and(|item| item.is_learnt())
|
||||
})
|
||||
.map(|membership| membership.key.clone())
|
||||
.collect();
|
||||
Counts {
|
||||
moves: memberships
|
||||
.into_iter()
|
||||
.map(|membership| (membership.path, membership.key))
|
||||
.collect(),
|
||||
learnt,
|
||||
}
|
||||
})
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = tx.send(result);
|
||||
}) {
|
||||
self.counting = None;
|
||||
self.error = Some(error.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self) {
|
||||
let Some(rx) = &self.counting else {
|
||||
return;
|
||||
};
|
||||
match rx.try_recv() {
|
||||
Ok(Ok(counts)) => {
|
||||
self.counts = Some(counts);
|
||||
self.counting = None;
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
self.error = Some(error);
|
||||
self.counting = None;
|
||||
}
|
||||
Err(mpsc::TryRecvError::Empty) => {}
|
||||
Err(mpsc::TryRecvError::Disconnected) => self.counting = None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The prefix that switches this path off, if any.
|
||||
fn disabled_by(&self, path: &[String]) -> Option<Vec<String>> {
|
||||
self.repertoire
|
||||
.disabled_prefixes
|
||||
.iter()
|
||||
.filter(|prefix| path.starts_with(prefix))
|
||||
.min_by_key(|prefix| prefix.len())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn goto(&mut self, node: NodeId) {
|
||||
if self.game.node(node).is_some() {
|
||||
self.cursor = node;
|
||||
self.scroll = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn keyboard(&mut self, ui: &Ui, actions: &mut Vec<LinesAction>) {
|
||||
if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) {
|
||||
return;
|
||||
}
|
||||
let mut command = None;
|
||||
ui.input_mut(|input| {
|
||||
for (key, name) in [
|
||||
(Key::ArrowLeft, "back"),
|
||||
(Key::ArrowRight, "forward"),
|
||||
(Key::ArrowUp, "previous"),
|
||||
(Key::ArrowDown, "next"),
|
||||
(Key::Home, "home"),
|
||||
(Key::End, "end"),
|
||||
(Key::F, "flip"),
|
||||
(Key::Enter, "train"),
|
||||
(Key::Escape, "back_screen"),
|
||||
] {
|
||||
if command.is_none()
|
||||
&& (input.consume_key(Modifiers::NONE, key)
|
||||
|| input.consume_key(Modifiers::SHIFT, key))
|
||||
{
|
||||
command = Some(name);
|
||||
}
|
||||
}
|
||||
if command.is_none()
|
||||
&& input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W))
|
||||
{
|
||||
command = Some("back_screen");
|
||||
}
|
||||
});
|
||||
let game = &self.game;
|
||||
let cursor = self.cursor;
|
||||
match command {
|
||||
Some("back") => {
|
||||
if let Some(parent) = game.parent(cursor) {
|
||||
self.goto(parent);
|
||||
}
|
||||
}
|
||||
Some("forward") => {
|
||||
if let Some(next) = game.main_child(cursor) {
|
||||
self.goto(next);
|
||||
}
|
||||
}
|
||||
Some("previous") => {
|
||||
if let Some(other) = game.prev_sibling(cursor) {
|
||||
self.goto(other);
|
||||
}
|
||||
}
|
||||
Some("next") => {
|
||||
if let Some(other) = game.next_sibling(cursor) {
|
||||
self.goto(other);
|
||||
}
|
||||
}
|
||||
Some("home") => self.goto(NodeId::ROOT),
|
||||
Some("end") => {
|
||||
let end = game.line_end(cursor);
|
||||
self.goto(end);
|
||||
}
|
||||
Some("flip") => self.orientation = self.orientation.other(),
|
||||
Some("train") => actions.push(self.train_action()),
|
||||
Some("back_screen") => actions.push(LinesAction::Back),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn train_action(&self) -> LinesAction {
|
||||
let through = self.cursor_path();
|
||||
let label = self.path_label(self.cursor);
|
||||
LinesAction::Train { through, label }
|
||||
}
|
||||
|
||||
/// "… 4. Ba4 Nf6": the moves to a node in the notation of the application.
|
||||
fn path_label(&self, node: NodeId) -> String {
|
||||
let mut words = Vec::new();
|
||||
for id in self.game.path(node).into_iter().skip(1) {
|
||||
let Some(mv) = self.game.game_move(id) else {
|
||||
continue;
|
||||
};
|
||||
let san = crate::san::show(&mv.san).into_owned();
|
||||
match self.game.move_number(id) {
|
||||
Some((number, Color::White)) => words.push(format!("{number}. {san}")),
|
||||
Some((number, Color::Black)) if words.is_empty() => {
|
||||
words.push(format!("{number}… {san}"))
|
||||
}
|
||||
_ => words.push(san),
|
||||
}
|
||||
}
|
||||
words.join(" ")
|
||||
}
|
||||
|
||||
fn below(&self, path: &[String]) -> Option<(usize, usize, usize)> {
|
||||
let counts = self.counts.as_ref()?;
|
||||
let lines = self
|
||||
.lines
|
||||
.iter()
|
||||
.filter(|line| line.starts_with(path))
|
||||
.count();
|
||||
let mine: Vec<_> = counts
|
||||
.moves
|
||||
.iter()
|
||||
.filter(|(move_path, _)| move_path.starts_with(path))
|
||||
.collect();
|
||||
let learnt = mine
|
||||
.iter()
|
||||
.filter(|(_, key)| counts.learnt.contains(key))
|
||||
.count();
|
||||
Some((lines, mine.len(), learnt))
|
||||
}
|
||||
|
||||
fn selected_block(&self, ui: &mut Ui, actions: &mut Vec<LinesAction>) {
|
||||
let path = self.cursor_path();
|
||||
let disabled = self.disabled_by(&path);
|
||||
layout::fixed_block(ui, SELECTED_H, |ui| {
|
||||
let inner = vec2(ui.available_width() - 20.0, SELECTED_H - 12.0);
|
||||
layout::card(ui, false, false).show(ui, |ui| {
|
||||
ui.set_min_size(inner);
|
||||
ui.set_max_size(inner);
|
||||
ui.spacing_mut().item_spacing.y = 4.0;
|
||||
if self.cursor == NodeId::ROOT {
|
||||
layout::line(ui, RichText::new(tr("Start position")).strong());
|
||||
} else {
|
||||
let label = self.path_label(self.cursor);
|
||||
// Cut on the left: the last moves matter.
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.set_max_height(20.0);
|
||||
layout::line(ui, RichText::new(label).strong());
|
||||
});
|
||||
}
|
||||
if disabled.is_some() {
|
||||
layout::line(
|
||||
ui,
|
||||
RichText::new(tr("Not trained")).color(ui.visuals().warn_fg_color),
|
||||
);
|
||||
} else {
|
||||
let text = match self.below(&path) {
|
||||
Some((lines, mine, learnt)) => trf(
|
||||
"Below: {n} lines · {y} your moves · learned {x}",
|
||||
&[("n", &lines), ("y", &mine), ("x", &learnt)],
|
||||
),
|
||||
None => tr("Counting moves…").to_owned(),
|
||||
};
|
||||
layout::line(ui, RichText::new(text).weak());
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let label = if self.cursor == NodeId::ROOT {
|
||||
tr("Review all lines")
|
||||
} else {
|
||||
tr("Train this branch")
|
||||
};
|
||||
let width = MAIN_W.min(ui.available_width() / 2.0 - 4.0);
|
||||
let can_train = disabled.is_none() && !self.lines.is_empty();
|
||||
if ui
|
||||
.add_enabled_ui(can_train, |ui| {
|
||||
crate::widgets::primary_wide(ui, label, width)
|
||||
})
|
||||
.inner
|
||||
.on_hover_text("Enter")
|
||||
.clicked()
|
||||
{
|
||||
actions.push(self.train_action());
|
||||
}
|
||||
if self.cursor != NodeId::ROOT {
|
||||
let (label, action) = match &disabled {
|
||||
Some(prefix) => (
|
||||
tr("Train again"),
|
||||
LinesAction::SetDisabled {
|
||||
path: prefix.clone(),
|
||||
disabled: false,
|
||||
},
|
||||
),
|
||||
None => (
|
||||
tr("Don't train"),
|
||||
LinesAction::SetDisabled {
|
||||
path: path.clone(),
|
||||
disabled: true,
|
||||
},
|
||||
),
|
||||
};
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(label)
|
||||
.truncate()
|
||||
.min_size(vec2(width, 30.0)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(action);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn side(&mut self, ui: &mut Ui, actions: &mut Vec<LinesAction>) {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
let footer_h = TOOL_H + 12.0;
|
||||
let footer = egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())),
|
||||
rect.max,
|
||||
);
|
||||
let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top()));
|
||||
let mut clicked = None;
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| {
|
||||
ui.set_clip_rect(body.intersect(ui.clip_rect()));
|
||||
ui.spacing_mut().item_spacing.y = GAP;
|
||||
ui.add_space(4.0);
|
||||
let opening = layout::opening_text(&self.game, self.cursor);
|
||||
layout::fixed_block(ui, 20.0, |ui| {
|
||||
layout::line(ui, RichText::new(opening).weak());
|
||||
});
|
||||
let tree = (ui.available_height() - SELECTED_H - GAP).max(0.0);
|
||||
let scroll = std::mem::take(&mut self.scroll);
|
||||
let game = &self.game;
|
||||
let cursor = self.cursor;
|
||||
let response = layout::fixed_block(ui, tree, |ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("opening_lines_tree")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
crate::notation::Notation {
|
||||
game,
|
||||
cursor,
|
||||
scroll_to_cursor: scroll,
|
||||
marks: None,
|
||||
preview: None,
|
||||
translations: None,
|
||||
editor: None,
|
||||
read_only: true,
|
||||
dim_until: None,
|
||||
mistakes: None,
|
||||
}
|
||||
.show(ui)
|
||||
})
|
||||
.inner
|
||||
});
|
||||
clicked = response.clicked;
|
||||
if let Some(error) = &self.error {
|
||||
ui.colored_label(ui.visuals().warn_fg_color, error);
|
||||
}
|
||||
self.selected_block(ui, actions);
|
||||
});
|
||||
if let Some(node) = clicked {
|
||||
self.cursor = node;
|
||||
}
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| {
|
||||
ui.separator();
|
||||
ui.horizontal(|ui| {
|
||||
let icon = |s: &str| {
|
||||
egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H))
|
||||
};
|
||||
let game = &self.game;
|
||||
let mut target = None;
|
||||
if ui.add(icon("⏮")).clicked() {
|
||||
target = Some(NodeId::ROOT);
|
||||
}
|
||||
if ui.add(icon("◀")).clicked() {
|
||||
target = game.parent(self.cursor);
|
||||
}
|
||||
if ui.add(icon("▶")).clicked() {
|
||||
target = game.main_child(self.cursor);
|
||||
}
|
||||
if ui.add(icon("⏭")).clicked() {
|
||||
target = Some(game.line_end(self.cursor));
|
||||
}
|
||||
ui.separator();
|
||||
if ui
|
||||
.add(icon("🔃"))
|
||||
.on_hover_text(tr("Flip board (F)"))
|
||||
.clicked()
|
||||
{
|
||||
self.orientation = self.orientation.other();
|
||||
}
|
||||
if let Some(target) = target {
|
||||
self.goto(target);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec<LinesAction> {
|
||||
self.poll();
|
||||
if self.counting.is_some() {
|
||||
ui.ctx()
|
||||
.request_repaint_after(std::time::Duration::from_millis(50));
|
||||
}
|
||||
let mut actions = Vec::new();
|
||||
self.keyboard(ui, &mut actions);
|
||||
let back = if ui.available_width() < 600.0 {
|
||||
"⬅"
|
||||
} else {
|
||||
tr("⬅ Repertoires")
|
||||
};
|
||||
let subtitle = trf(
|
||||
"Lines · {n} lines · {y} your moves",
|
||||
&[
|
||||
("n", &self.lines.len()),
|
||||
(
|
||||
"y",
|
||||
&self
|
||||
.counts
|
||||
.as_ref()
|
||||
.map_or_else(|| "…".to_owned(), |counts| counts.moves.len().to_string()),
|
||||
),
|
||||
],
|
||||
);
|
||||
let name = self.name.clone();
|
||||
let mut header = (false, false);
|
||||
layout::screen(
|
||||
ui,
|
||||
self,
|
||||
|_, ui| header = crate::widgets::section_header_sub(ui, back, &name, &subtitle),
|
||||
|this, ui| this.side(ui, &mut actions),
|
||||
|this, ui| {
|
||||
let position = layout::position_of(&this.game, this.cursor);
|
||||
let marks = pgn_annotations_at(&this.game, this.cursor);
|
||||
let last = layout::last_move(&this.game, this.cursor);
|
||||
layout::still_board(
|
||||
ui,
|
||||
&mut this.board,
|
||||
settings,
|
||||
&position,
|
||||
this.orientation,
|
||||
last,
|
||||
&marks,
|
||||
);
|
||||
},
|
||||
);
|
||||
if header.0 {
|
||||
actions.push(LinesAction::Back);
|
||||
}
|
||||
if header.1 {
|
||||
actions.push(LinesAction::OpenSettings);
|
||||
}
|
||||
actions
|
||||
}
|
||||
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub fn debug_select(&mut self, path: &[String]) {
|
||||
if let Some(node) = layout::node_at(&self.game, path) {
|
||||
self.goto(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lines_ui(pgn: &str) -> (Library, OpeningLinesUi) {
|
||||
let mut library = Library::default();
|
||||
let id = library
|
||||
.create("Lines", &chess_core::parse_str(pgn).game)
|
||||
.unwrap();
|
||||
let mut ui = OpeningLinesUi::new(
|
||||
&library,
|
||||
&LearningData::default(),
|
||||
id,
|
||||
LearningSide::White,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while ui.counting.is_some() && web_time::Instant::now() < deadline {
|
||||
ui.poll();
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
(library, ui)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_below_a_move_and_branches_switched_off() {
|
||||
let (mut library, mut ui) = lines_ui("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *");
|
||||
assert_eq!(ui.below(&[]), Some((3, 4, 0)));
|
||||
let c5 = ["e2e4".to_owned(), "c7c5".to_owned()];
|
||||
assert_eq!(ui.below(&c5), Some((1, 1, 0)));
|
||||
ui.debug_select(&c5);
|
||||
assert_eq!(ui.cursor_path(), c5);
|
||||
assert_eq!(ui.path_label(ui.cursor), "1. e4 c5");
|
||||
assert!(matches!(
|
||||
ui.train_action(),
|
||||
LinesAction::Train { through, .. } if through == c5
|
||||
));
|
||||
let id = ui.id().clone();
|
||||
library
|
||||
.repertoire_mut(&id)
|
||||
.unwrap()
|
||||
.set_prefix_disabled(&c5, true)
|
||||
.unwrap();
|
||||
ui.refresh(&library, &LearningData::default());
|
||||
let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
while ui.counting.is_some() && web_time::Instant::now() < deadline {
|
||||
ui.poll();
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
assert_eq!(ui.lines.len(), 2);
|
||||
assert_eq!(
|
||||
ui.disabled_by(&[c5[0].clone(), c5[1].clone(), "g1f3".into()]),
|
||||
Some(c5.to_vec())
|
||||
);
|
||||
assert_eq!(ui.below(&[]), Some((2, 3, 0)));
|
||||
}
|
||||
}
|
||||
2426
apps/desktop/src/opening_session.rs
Normal file
2426
apps/desktop/src/opening_session.rs
Normal file
File diff suppressed because it is too large
Load diff
2129
apps/desktop/src/opening_session_tests.rs
Normal file
2129
apps/desktop/src/opening_session_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -11,6 +11,7 @@ pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response {
|
|||
|
||||
/// A section header: reserve global actions before laying out a long title.
|
||||
/// Returns (back, settings).
|
||||
#[allow(dead_code)]
|
||||
pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) {
|
||||
let mut clicked = (false, false);
|
||||
let compact = ui.available_width() < 600.0;
|
||||
|
|
@ -29,6 +30,37 @@ pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) {
|
|||
clicked
|
||||
}
|
||||
|
||||
/// A two-line section header in the places of the game's (title and a quiet line under
|
||||
/// it; an empty subtitle keeps its line, so the header never changes height).
|
||||
/// Returns (back, settings).
|
||||
pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) -> (bool, bool) {
|
||||
let mut clicked = (false, false);
|
||||
let compact = ui.available_width() < 600.0;
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
clicked.0 = ui.button(back).clicked();
|
||||
ui.separator();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
clicked.1 = settings_button(ui, compact).clicked();
|
||||
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate())
|
||||
.on_hover_text(title);
|
||||
let sub = ui.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(if subtitle.is_empty() { " " } else { subtitle })
|
||||
.weak(),
|
||||
)
|
||||
.truncate(),
|
||||
);
|
||||
if !subtitle.is_empty() {
|
||||
sub.on_hover_text(subtitle);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
clicked
|
||||
}
|
||||
|
||||
/// A dev check (`CP_PANEL_CHECK=1`): a panel whose content is wider than the panel. egui
|
||||
/// then moves a right panel out (its left part under the central panel, its right part
|
||||
/// off the window); the content of every panel must fit its least width
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue