fix: refine opening training UI, move feedback and opponent preparation
This commit is contained in:
parent
a4521d94ed
commit
860e84d0d9
38 changed files with 4500 additions and 1575 deletions
|
|
@ -3694,7 +3694,10 @@ impl App {
|
|||
);
|
||||
}
|
||||
self.desktop.was_focused = focused;
|
||||
let events = self.desktop.online.show(ctx, &self.desktop.online_probe);
|
||||
let events = self
|
||||
.desktop
|
||||
.online
|
||||
.show(ctx, &mut self.desktop.online_probe);
|
||||
for e in events {
|
||||
match e {
|
||||
crate::online_ui::OnlineEvent::Added(p) => {
|
||||
|
|
|
|||
|
|
@ -290,9 +290,22 @@ impl BoardView<'_> {
|
|||
}
|
||||
}
|
||||
|
||||
// A released legal drag is already at its destination. Draw that result
|
||||
// in this frame too, before the caller installs the move in its model.
|
||||
// Click moves keep the ordinary animation on the following frame.
|
||||
let dropped_position = result
|
||||
.as_ref()
|
||||
.filter(|_| state.dropped.is_some())
|
||||
.map(|mv| {
|
||||
let mut position = self.pos.clone();
|
||||
position.play_unchecked(*mv);
|
||||
position
|
||||
});
|
||||
let painted_position = dropped_position.as_ref().unwrap_or(self.pos);
|
||||
|
||||
// --- animation ---------------------------------------------------------------------
|
||||
let now = ui.input(|i| i.time);
|
||||
let board = self.pos.board();
|
||||
let board = painted_position.board();
|
||||
if state.shown.as_ref() != Some(board) {
|
||||
state.anim = None;
|
||||
if let Some(prev) = &state.shown
|
||||
|
|
@ -349,8 +362,8 @@ impl BoardView<'_> {
|
|||
hl(&painter, from, red);
|
||||
hl(&painter, to, red);
|
||||
}
|
||||
if self.pos.is_check()
|
||||
&& let Some(k) = self.pos.board().king_of(self.pos.turn())
|
||||
if painted_position.is_check()
|
||||
&& let Some(k) = painted_position.board().king_of(painted_position.turn())
|
||||
{
|
||||
let r = geo.square_rect(k);
|
||||
painter.circle_filled(
|
||||
|
|
@ -373,7 +386,7 @@ impl BoardView<'_> {
|
|||
.paint_tinted(ui, piece, r, Color32::WHITE.gamma_multiply(rest));
|
||||
}
|
||||
}
|
||||
for (sq, piece) in self.pos.board().clone() {
|
||||
for (sq, piece) in painted_position.board().clone() {
|
||||
if state.drag == Some(sq) && response.dragged() {
|
||||
continue;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1153,11 +1153,7 @@ impl GameView {
|
|||
},
|
||||
);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui
|
||||
.button(if compact { "⚙" } else { tr("⚙ Settings") })
|
||||
.on_hover_text(if compact { format!("{} (Ctrl+,)", tr("Settings")) } else { "Ctrl+,".to_owned() })
|
||||
.clicked()
|
||||
{
|
||||
if crate::widgets::settings_button(ui, compact).clicked() {
|
||||
actions.push(GameAction::OpenSettings);
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
|
|
|
|||
|
|
@ -216,6 +216,358 @@ pub fn trf(key: &'static str, args: &[(&str, &dyn Display)]) -> String {
|
|||
// [English, Русский, Français, Deutsch, Español, Italiano, Português (BR), O‘zbekcha, Қазақша]
|
||||
// Uzbek o‘ and g‘ are written with ‘ (U+2018): the interface font has no U+02BB.
|
||||
const ROWS: &[[&str; 9]] = &[
|
||||
[
|
||||
"Checking access to Lichess and Chess.com…",
|
||||
"Проверяем доступность Lichess и Chess.com…",
|
||||
"Vérification de l’accès à Lichess et Chess.com…",
|
||||
"Zugriff auf Lichess und Chess.com wird geprüft…",
|
||||
"Comprobando el acceso a Lichess y Chess.com…",
|
||||
"Verifica dell’accesso a Lichess e Chess.com…",
|
||||
"Verificando o acesso ao Lichess e ao Chess.com…",
|
||||
"Lichess va Chess.com mavjudligi tekshirilmoqda…",
|
||||
"Lichess пен Chess.com қолжетімділігі тексерілуде…",
|
||||
],
|
||||
[
|
||||
"Exit",
|
||||
"Выйти",
|
||||
"Quitter",
|
||||
"Verlassen",
|
||||
"Salir",
|
||||
"Esci",
|
||||
"Sair",
|
||||
"Chiqish",
|
||||
"Шығу",
|
||||
],
|
||||
[
|
||||
"Saving progress…",
|
||||
"Сохранение прогресса…",
|
||||
"Enregistrement du progrès…",
|
||||
"Fortschritt wird gespeichert…",
|
||||
"Guardando progreso…",
|
||||
"Salvataggio progressi…",
|
||||
"Salvando progresso…",
|
||||
"Natija saqlanmoqda…",
|
||||
"Нәтиже сақталуда…",
|
||||
],
|
||||
[
|
||||
"Reset learning progress…",
|
||||
"Сбросить прогресс…",
|
||||
"Réinitialiser la progression…",
|
||||
"Lernfortschritt zurücksetzen…",
|
||||
"Restablecer progreso…",
|
||||
"Azzera i progressi…",
|
||||
"Redefinir progresso…",
|
||||
"O‘rganish natijasini tiklash…",
|
||||
"Оқу нәтижесін ысыру…",
|
||||
],
|
||||
[
|
||||
"Total without duplicates",
|
||||
"Всего без повторов",
|
||||
"Total sans doublons",
|
||||
"Gesamt ohne Duplikate",
|
||||
"Total sin duplicados",
|
||||
"Totale senza duplicati",
|
||||
"Total sem duplicatas",
|
||||
"Takrorsiz jami",
|
||||
"Қайталаусыз барлығы",
|
||||
],
|
||||
[
|
||||
"Training scope: selected part",
|
||||
"Тренировка: часть репертуара",
|
||||
"Entraînement : partie du répertoire",
|
||||
"Training: Teil des Repertoires",
|
||||
"Entrenamiento: parte del repertorio",
|
||||
"Allenamento: parte del repertorio",
|
||||
"Treino: parte do repertório",
|
||||
"Mashq: repertuarning bir qismi",
|
||||
"Жаттығу: репертуардың бір бөлігі",
|
||||
],
|
||||
[
|
||||
"On schedule",
|
||||
"По расписанию",
|
||||
"Selon le calendrier",
|
||||
"Nach Zeitplan",
|
||||
"Según el calendario",
|
||||
"Secondo calendario",
|
||||
"Conforme o calendário",
|
||||
"Jadval bo‘yicha",
|
||||
"Кесте бойынша",
|
||||
],
|
||||
[
|
||||
"Overview",
|
||||
"Обзор",
|
||||
"Vue d’ensemble",
|
||||
"Übersicht",
|
||||
"Resumen",
|
||||
"Panoramica",
|
||||
"Visão geral",
|
||||
"Umumiy ko‘rinish",
|
||||
"Шолу",
|
||||
],
|
||||
[
|
||||
"Long overdue learnt moves",
|
||||
"Давно не повторяли",
|
||||
"Coups appris à revoir",
|
||||
"Lange nicht wiederholt",
|
||||
"Aprendidas sin repasar",
|
||||
"Apprese da ripassare",
|
||||
"Aprendidos sem revisão",
|
||||
"Uzoq vaqt takrorlanmagan",
|
||||
"Көптен қайталанбаған",
|
||||
],
|
||||
[
|
||||
"Of the moves already learnt",
|
||||
"Из числа изученных ходов",
|
||||
"Parmi les coups déjà appris",
|
||||
"Von den bereits gelernten Zügen",
|
||||
"De las jugadas ya aprendidas",
|
||||
"Delle mosse già apprese",
|
||||
"Dos lances já aprendidos",
|
||||
"O‘rganilgan yurishlardan",
|
||||
"Үйренілген жүрістердің ішінен",
|
||||
],
|
||||
[
|
||||
"Train",
|
||||
"Тренироваться",
|
||||
"S’entraîner",
|
||||
"Trainieren",
|
||||
"Entrenar",
|
||||
"Allenati",
|
||||
"Treinar",
|
||||
"Mashq qilish",
|
||||
"Жаттығу",
|
||||
],
|
||||
[
|
||||
"No moves to train",
|
||||
"Нет ходов для тренировки",
|
||||
"Aucun coup à travailler",
|
||||
"Keine Züge zum Trainieren",
|
||||
"No hay jugadas para entrenar",
|
||||
"Nessuna mossa da allenare",
|
||||
"Nenhum lance para treinar",
|
||||
"Mashq uchun yurishlar yo‘q",
|
||||
"Жаттығуға жүрістер жоқ",
|
||||
],
|
||||
[
|
||||
"Add variations in the editor or import PGN",
|
||||
"Добавьте варианты в редакторе или импортируйте PGN",
|
||||
"Ajoutez des variantes dans l’éditeur ou importez un PGN",
|
||||
"Varianten im Editor hinzufügen oder PGN importieren",
|
||||
"Añada variantes en el editor o importe PGN",
|
||||
"Aggiungi varianti nell’editor o importa PGN",
|
||||
"Adicione variantes no editor ou importe PGN",
|
||||
"Tahrirchida variantlar qo‘shing yoki PGN import qiling",
|
||||
"Редакторда нұсқалар қосыңыз немесе PGN импорттаңыз",
|
||||
],
|
||||
[
|
||||
"Learnt {learnt} of {total} moves",
|
||||
"Изучено {learnt} из {total} ходов",
|
||||
"{learnt} coups appris sur {total}",
|
||||
"{learnt} von {total} Zügen gelernt",
|
||||
"{learnt} de {total} jugadas aprendidas",
|
||||
"{learnt} mosse apprese su {total}",
|
||||
"{learnt} de {total} lances aprendidos",
|
||||
"{total} yurishdan {learnt} tasi o‘rganildi",
|
||||
"{total} жүрістің {learnt} үйренілді",
|
||||
],
|
||||
[
|
||||
"Unseen: {unseen} · Due now: {due}",
|
||||
"Не изучались: {unseen} · Пора повторить: {due}",
|
||||
"Non étudiés : {unseen} · À réviser : {due}",
|
||||
"Noch nicht geübt: {unseen} · Fällig: {due}",
|
||||
"Sin practicar: {unseen} · Pendientes: {due}",
|
||||
"Mai studiate: {unseen} · Da ripassare: {due}",
|
||||
"Não praticados: {unseen} · A revisar: {due}",
|
||||
"O‘rganilmagan: {unseen} · Takrorlash: {due}",
|
||||
"Үйренілмеген: {unseen} · Қайталау: {due}",
|
||||
],
|
||||
[
|
||||
"Parameters",
|
||||
"Параметры",
|
||||
"Paramètres",
|
||||
"Parameter",
|
||||
"Parámetros",
|
||||
"Parametri",
|
||||
"Parâmetros",
|
||||
"Parametrlar",
|
||||
"Параметрлер",
|
||||
],
|
||||
[
|
||||
"No depth limit",
|
||||
"Без ограничения глубины",
|
||||
"Profondeur illimitée",
|
||||
"Keine Tiefenbegrenzung",
|
||||
"Sin límite de profundidad",
|
||||
"Profondità illimitata",
|
||||
"Sem limite de profundidade",
|
||||
"Chuqurlik cheklanmagan",
|
||||
"Тереңдік шектеусіз",
|
||||
],
|
||||
[
|
||||
"Learn new moves",
|
||||
"Учить новые",
|
||||
"Apprendre des coups",
|
||||
"Neue Züge lernen",
|
||||
"Aprender jugadas",
|
||||
"Impara mosse",
|
||||
"Aprender lances",
|
||||
"Yangi yurishlar",
|
||||
"Жаңа жүрістер",
|
||||
],
|
||||
[
|
||||
"Training statistics",
|
||||
"Статистика обучения",
|
||||
"Statistiques d’apprentissage",
|
||||
"Lernstatistik",
|
||||
"Estadísticas de aprendizaje",
|
||||
"Statistiche di apprendimento",
|
||||
"Estatísticas de aprendizagem",
|
||||
"O‘rganish statistikasi",
|
||||
"Оқу статистикасы",
|
||||
],
|
||||
[
|
||||
"History is saved automatically once a day when viewed.",
|
||||
"История сохраняется автоматически при первом просмотре за день.",
|
||||
"L’historique est enregistré automatiquement à la première consultation du jour.",
|
||||
"Der Verlauf wird beim ersten Aufruf des Tages automatisch gespeichert.",
|
||||
"El historial se guarda automáticamente en la primera consulta del día.",
|
||||
"La cronologia viene salvata automaticamente alla prima visita del giorno.",
|
||||
"O histórico é salvo automaticamente na primeira consulta do dia.",
|
||||
"Tarix kunning birinchi ko‘rishida avtomatik saqlanadi.",
|
||||
"Тарих күннің алғашқы қарауында автоматты сақталады.",
|
||||
],
|
||||
[
|
||||
"Progress over time",
|
||||
"Динамика",
|
||||
"Évolution",
|
||||
"Entwicklung",
|
||||
"Evolución",
|
||||
"Andamento",
|
||||
"Evolução",
|
||||
"Dinamika",
|
||||
"Динамика",
|
||||
],
|
||||
[
|
||||
"More statistics",
|
||||
"Дополнительно",
|
||||
"Plus de statistiques",
|
||||
"Weitere Statistiken",
|
||||
"Más estadísticas",
|
||||
"Altre statistiche",
|
||||
"Mais estatísticas",
|
||||
"Qo‘shimcha statistika",
|
||||
"Қосымша статистика",
|
||||
],
|
||||
[
|
||||
"All repertoires",
|
||||
"Все репертуары",
|
||||
"Tous les répertoires",
|
||||
"Alle Repertoires",
|
||||
"Todos los repertorios",
|
||||
"Tutti i repertori",
|
||||
"Todos os repertórios",
|
||||
"Barcha repertuarlar",
|
||||
"Барлық репертуарлар",
|
||||
],
|
||||
[
|
||||
"Not practised yet",
|
||||
"Ещё не изучали",
|
||||
"Pas encore pratiqués",
|
||||
"Noch nicht geübt",
|
||||
"Sin practicar aún",
|
||||
"Mai praticate",
|
||||
"Ainda não praticados",
|
||||
"Hali mashq qilinmagan",
|
||||
"Әлі жаттықтырылмаған",
|
||||
],
|
||||
[
|
||||
"Still learning",
|
||||
"В процессе изучения",
|
||||
"En cours d’apprentissage",
|
||||
"Noch im Lernen",
|
||||
"En aprendizaje",
|
||||
"In apprendimento",
|
||||
"Em aprendizagem",
|
||||
"O‘rganilmoqda",
|
||||
"Үйренілуде",
|
||||
],
|
||||
[
|
||||
"Due now",
|
||||
"Пора повторить",
|
||||
"À réviser",
|
||||
"Jetzt wiederholen",
|
||||
"Por repasar",
|
||||
"Da ripassare",
|
||||
"A revisar",
|
||||
"Takrorlash vaqti",
|
||||
"Қайталау уақыты",
|
||||
],
|
||||
[
|
||||
"Progress counts your repertoire moves, with shared positions counted once.",
|
||||
"Считаются ваши ходы из репертуара. Одинаковые позиции учитываются один раз.",
|
||||
"Vos coups du répertoire sont comptés, chaque position commune une seule fois.",
|
||||
"Gezählt werden Ihre Repertoirezüge; gemeinsame Stellungen zählen einmal.",
|
||||
"Se cuentan sus jugadas; las posiciones compartidas se cuentan una sola vez.",
|
||||
"Si contano le proprie mosse; le posizioni condivise contano una sola volta.",
|
||||
"Contam-se seus lances; posições compartilhadas contam uma vez.",
|
||||
"Repertuaringiz yurishlari sanaladi; umumiy pozitsiyalar bir marta hisoblanadi.",
|
||||
"Репертуардағы жүрістер саналады; ортақ позициялар бір рет есептеледі.",
|
||||
],
|
||||
[
|
||||
"Learning details",
|
||||
"Показатели обучения",
|
||||
"Détails d’apprentissage",
|
||||
"Lerndetails",
|
||||
"Detalles del aprendizaje",
|
||||
"Dettagli di apprendimento",
|
||||
"Detalhes da aprendizagem",
|
||||
"O‘rganish tafsilotlari",
|
||||
"Оқу көрсеткіштері",
|
||||
],
|
||||
[
|
||||
"Learnt moves",
|
||||
"Изучено ходов",
|
||||
"Coups appris",
|
||||
"Gelernte Züge",
|
||||
"Jugadas aprendidas",
|
||||
"Mosse apprese",
|
||||
"Lances aprendidos",
|
||||
"O‘rganilgan yurishlar",
|
||||
"Үйренілген жүрістер",
|
||||
],
|
||||
[
|
||||
"Progress history will appear after your first daily snapshot.",
|
||||
"История появится после первого автоматического сохранения.",
|
||||
"L’historique apparaîtra après le premier enregistrement automatique.",
|
||||
"Der Verlauf erscheint nach der ersten automatischen Speicherung.",
|
||||
"El historial aparecerá tras el primer guardado automático.",
|
||||
"La cronologia apparirà dopo il primo salvataggio automatico.",
|
||||
"O histórico aparecerá após o primeiro salvamento automático.",
|
||||
"Tarix birinchi avtomatik saqlashdan keyin paydo bo‘ladi.",
|
||||
"Тарих алғашқы автоматты сақтаудан кейін пайда болады.",
|
||||
],
|
||||
[
|
||||
"Variation start",
|
||||
"Начало варианта",
|
||||
"Début de variante",
|
||||
"Variantenbeginn",
|
||||
"Inicio de variante",
|
||||
"Inizio variante",
|
||||
"Início da variante",
|
||||
"Variant boshi",
|
||||
"Нұсқа басы",
|
||||
],
|
||||
[
|
||||
"Continuations to review. Shared moves may appear in several variations.",
|
||||
"Какие продолжения стоит повторить. Общие ходы могут встречаться в нескольких вариантах.",
|
||||
"Suites à réviser. Les coups communs peuvent apparaître dans plusieurs variantes.",
|
||||
"Fortsetzungen zum Wiederholen. Gemeinsame Züge können in mehreren Varianten vorkommen.",
|
||||
"Continuaciones por repasar. Las jugadas compartidas pueden aparecer en varias variantes.",
|
||||
"Continuazioni da ripassare. Le mosse condivise possono apparire in più varianti.",
|
||||
"Continuações a revisar. Lances compartilhados podem aparecer em várias variantes.",
|
||||
"Takrorlanadigan davomlar. Umumiy yurishlar bir nechta variantda bo‘lishi mumkin.",
|
||||
"Қайталайтын жалғастар. Ортақ жүрістер бірнеше нұсқада кездесуі мүмкін.",
|
||||
],
|
||||
// --- the web version ---
|
||||
[
|
||||
"This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.",
|
||||
|
|
@ -16069,15 +16421,15 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Қай жүріске дейін қосуды таңдаңыз",
|
||||
],
|
||||
[
|
||||
"Opening training",
|
||||
"Тренировка дебюта",
|
||||
"Entraînement aux ouvertures",
|
||||
"Eröffnungstraining",
|
||||
"Entrenamiento de aperturas",
|
||||
"Allenamento nelle aperture",
|
||||
"Treino de aberturas",
|
||||
"Debyut mashg‘uloti",
|
||||
"Дебют жаттығуы",
|
||||
"Opening training (α version)",
|
||||
"Тренировка дебюта (α версия)",
|
||||
"Entraînement aux ouvertures (version α)",
|
||||
"Eröffnungstraining (α-Version)",
|
||||
"Entrenamiento de aperturas (versión α)",
|
||||
"Allenamento nelle aperture (versione α)",
|
||||
"Treino de aberturas (versão α)",
|
||||
"Debyut mashg‘uloti (α versiya)",
|
||||
"Дебют жаттығуы (α нұсқасы)",
|
||||
],
|
||||
[
|
||||
"Add only the path from the start through this move, with its comments and NAGs",
|
||||
|
|
@ -18365,7 +18717,7 @@ const ROWS: &[[&str; 9]] = &[
|
|||
],
|
||||
[
|
||||
"REPLAY_AFTER_ERROR · not an independent success.",
|
||||
"REPLAY_AFTER_ERROR · не самостоятельный успех.",
|
||||
"Ход повторён после ошибки. Самостоятельный ответ не засчитан.",
|
||||
"REPLAY_AFTER_ERROR · pas une réussite indépendante.",
|
||||
"REPLAY_AFTER_ERROR · kein unabhängiger Erfolg.",
|
||||
"REPLAY_AFTER_ERROR · no es un acierto independiente.",
|
||||
|
|
@ -18376,7 +18728,7 @@ const ROWS: &[[&str; 9]] = &[
|
|||
],
|
||||
[
|
||||
"PREVIEWED · replay the shown move; this is not an independent success.",
|
||||
"PREVIEWED · повторите показанный ход; это не самостоятельный успех.",
|
||||
"Повторите показанный ход. Ответ с подсказкой не считается самостоятельным.",
|
||||
"PREVIEWED · rejouez le coup indiqué ; ce n’est pas une réussite indépendante.",
|
||||
"PREVIEWED · wiederholen Sie den angezeigten Zug; dies ist kein unabhängiger Erfolg.",
|
||||
"PREVIEWED · repite la jugada mostrada; no es un acierto independiente.",
|
||||
|
|
@ -18387,7 +18739,7 @@ const ROWS: &[[&str; 9]] = &[
|
|||
],
|
||||
[
|
||||
"PREVIEWED · shown move completed; no independent success recorded.",
|
||||
"PREVIEWED · показанный ход выполнен; самостоятельный успех не записан.",
|
||||
"Ход выполнен с подсказкой. Самостоятельный ответ не засчитан.",
|
||||
"PREVIEWED · coup indiqué joué ; aucune réussite indépendante enregistrée.",
|
||||
"PREVIEWED · angezeigter Zug gespielt; kein unabhängiger Erfolg gespeichert.",
|
||||
"PREVIEWED · jugada mostrada completada; no se registró un acierto independiente.",
|
||||
|
|
@ -18520,7 +18872,7 @@ const ROWS: &[[&str; 9]] = &[
|
|||
],
|
||||
[
|
||||
"Learning priority",
|
||||
"Приоритет обучения",
|
||||
"Порядок изучения",
|
||||
"Priorité d’apprentissage",
|
||||
"Lernpriorität",
|
||||
"Prioridad de aprendizaje",
|
||||
|
|
@ -19685,6 +20037,237 @@ const ROWS: &[[&str; 9]] = &[
|
|||
"Bu doirada tarmoqlar yo‘q",
|
||||
"Бұл аумақта тармақтар жоқ",
|
||||
],
|
||||
[
|
||||
"Training parameters",
|
||||
"Параметры тренировки",
|
||||
"Paramètres d’entraînement",
|
||||
"Trainingseinstellungen",
|
||||
"Parámetros de entrenamiento",
|
||||
"Parametri di allenamento",
|
||||
"Parâmetros de treino",
|
||||
"Mashq parametrlari",
|
||||
"Жаттығу параметрлері",
|
||||
],
|
||||
[
|
||||
"Changes apply to new sessions. Continuing a saved session keeps its previous settings.",
|
||||
"Изменения действуют для новых сессий. При продолжении сохранённой сессии остаются прежние параметры.",
|
||||
"Les modifications s’appliquent aux nouvelles séances. Reprendre une séance enregistrée conserve ses paramètres précédents.",
|
||||
"Änderungen gelten für neue Trainingseinheiten. Beim Fortsetzen einer gespeicherten Einheit bleiben deren bisherige Einstellungen erhalten.",
|
||||
"Los cambios se aplican a las sesiones nuevas. Al continuar una sesión guardada se mantienen sus ajustes anteriores.",
|
||||
"Le modifiche si applicano alle nuove sessioni. Riprendendo una sessione salvata si mantengono le impostazioni precedenti.",
|
||||
"As alterações se aplicam a novas sessões. Ao continuar uma sessão salva, as configurações anteriores são mantidas.",
|
||||
"O‘zgarishlar yangi mashg‘ulotlarga qo‘llanadi. Saqlangan mashg‘ulot davom ettirilganda uning avvalgi sozlamalari saqlanadi.",
|
||||
"Өзгерістер жаңа сеанстарға қолданылады. Сақталған сеансты жалғастырғанда оның бұрынғы параметрлері сақталады.",
|
||||
],
|
||||
[
|
||||
"Moves before the task",
|
||||
"Ходы перед заданием",
|
||||
"Coups avant l’exercice",
|
||||
"Züge vor der Aufgabe",
|
||||
"Jugadas anteriores al ejercicio",
|
||||
"Mosse prima dell’esercizio",
|
||||
"Lances antes do exercício",
|
||||
"Topshiriqdan oldingi yurishlar",
|
||||
"Тапсырмаға дейінгі жүрістер",
|
||||
],
|
||||
[
|
||||
"The app shows the moves leading to the task position.",
|
||||
"Приложение показывает ходы до позиции задания.",
|
||||
"L’application montre les coups menant à la position de l’exercice.",
|
||||
"Die Anwendung zeigt die Züge bis zur Aufgabenstellung.",
|
||||
"La aplicación muestra las jugadas que llevan a la posición del ejercicio.",
|
||||
"L’app mostra le mosse che portano alla posizione dell’esercizio.",
|
||||
"O aplicativo mostra os lances que levam à posição do exercício.",
|
||||
"Ilova topshiriq pozitsiyasiga olib keladigan yurishlarni ko‘rsatadi.",
|
||||
"Қолданба тапсырмадағы позицияға жеткізетін жүрістерді көрсетеді.",
|
||||
],
|
||||
[
|
||||
"Ask me to play preceding moves",
|
||||
"Спрашивать предыдущие ходы",
|
||||
"Me faire jouer les coups précédents",
|
||||
"Vorherige Züge abfragen",
|
||||
"Pedirme que juegue las jugadas anteriores",
|
||||
"Chiedimi di giocare le mosse precedenti",
|
||||
"Pedir que eu jogue os lances anteriores",
|
||||
"Oldingi yurishlarni o‘zim bajarishimni so‘rash",
|
||||
"Алдыңғы жүрістерді өзім жасауымды сұрау",
|
||||
],
|
||||
[
|
||||
"Correct answers in a row",
|
||||
"Верных ответов подряд",
|
||||
"Bonnes réponses consécutives",
|
||||
"Richtige Antworten in Folge",
|
||||
"Respuestas correctas consecutivas",
|
||||
"Risposte corrette consecutive",
|
||||
"Respostas corretas consecutivas",
|
||||
"Ketma-ket to‘g‘ri javoblar",
|
||||
"Қатарынан дұрыс жауаптар",
|
||||
],
|
||||
[
|
||||
"Ask until this streak is reached. This also sets the maximum acceleration point for adaptive playback.",
|
||||
"Спрашивать ход, пока серия меньше этого числа. При адаптивном показе это также порог максимального ускорения.",
|
||||
"Demander le coup tant que la série est inférieure à ce nombre. Ce seuil détermine aussi l’accélération maximale du défilement adaptatif.",
|
||||
"Den Zug abfragen, solange die Serie kleiner als diese Zahl ist. Dieser Wert bestimmt auch die maximale Beschleunigung bei adaptiver Wiedergabe.",
|
||||
"Preguntar la jugada mientras la racha sea menor que este número. También determina cuándo se alcanza la aceleración máxima de la reproducción adaptativa.",
|
||||
"Chiedere la mossa finché la serie è inferiore a questo numero. Questa soglia determina anche l’accelerazione massima della riproduzione adattiva.",
|
||||
"Pedir o lance enquanto a sequência for menor que este número. Esse limite também determina a aceleração máxima da reprodução adaptativa.",
|
||||
"Ketma-ket javoblar soni shu qiymatga yetguncha yurishni so‘rash. Moslashuvchan namoyishda bu eng yuqori tezlashuv chegarasi ham hisoblanadi.",
|
||||
"Серия осы санға жеткенше жүрісті сұрау. Бейімделетін көрсетілімде бұл ең жоғары жылдамдату шегі де болады.",
|
||||
],
|
||||
[
|
||||
"Review ahead of schedule",
|
||||
"Повторять заранее",
|
||||
"Réviser avant l’échéance",
|
||||
"Vorzeitig wiederholen",
|
||||
"Repasar antes de lo previsto",
|
||||
"Ripassare in anticipo",
|
||||
"Revisar antes do prazo",
|
||||
"Muddatidan oldin takrorlash",
|
||||
"Мерзімінен бұрын қайталау",
|
||||
],
|
||||
[
|
||||
"Days before the due date",
|
||||
"Дней до срока повторения",
|
||||
"Jours avant l’échéance",
|
||||
"Tage vor dem Wiederholungstermin",
|
||||
"Días antes del repaso previsto",
|
||||
"Giorni prima del ripasso previsto",
|
||||
"Dias antes do prazo de revisão",
|
||||
"Takrorlash muddatigacha kunlar",
|
||||
"Қайталау мерзіміне дейінгі күндер",
|
||||
],
|
||||
[
|
||||
"Also ask moves that are already due.",
|
||||
"Также спрашивать ходы, которые уже пора повторить.",
|
||||
"Demander aussi les coups dont la révision est déjà due.",
|
||||
"Auch bereits fällige Züge abfragen.",
|
||||
"Preguntar también las jugadas que ya toca repasar.",
|
||||
"Chiedere anche le mosse già da ripassare.",
|
||||
"Pedir também os lances cuja revisão já está prevista.",
|
||||
"Takrorlash vaqti yetgan yurishlarni ham so‘rash.",
|
||||
"Қайталау уақыты келген жүрістерді де сұрау.",
|
||||
],
|
||||
[
|
||||
"Skip a familiar opening",
|
||||
"Пропуск знакомого начала",
|
||||
"Passer le début familier",
|
||||
"Vertrauten Anfang überspringen",
|
||||
"Omitir el inicio conocido",
|
||||
"Saltare l’inizio conosciuto",
|
||||
"Pular o início conhecido",
|
||||
"Tanish boshlanishni o‘tkazib yuborish",
|
||||
"Таныс басталуды өткізіп жіберу",
|
||||
],
|
||||
[
|
||||
"Skip after this many correct answers in a row",
|
||||
"Верных ответов подряд для пропуска",
|
||||
"Passer après ce nombre de bonnes réponses consécutives",
|
||||
"Nach dieser Anzahl richtiger Antworten in Folge überspringen",
|
||||
"Omitir tras este número de respuestas correctas consecutivas",
|
||||
"Saltare dopo questo numero di risposte corrette consecutive",
|
||||
"Pular após este número de respostas corretas consecutivas",
|
||||
"Shuncha ketma-ket to‘g‘ri javobdan keyin o‘tkazib yuborish",
|
||||
"Осы санға тең дұрыс жауаптар сериясынан кейін өткізу",
|
||||
],
|
||||
[
|
||||
"Each of your opening moves must reach this streak. 0 means always show the opening.",
|
||||
"Каждый свой ход в начале варианта должен достичь этой серии. 0 — всегда показывать начало.",
|
||||
"Chacun de vos coups au début de la variante doit atteindre cette série. 0 signifie toujours montrer le début.",
|
||||
"Jeder eigene Zug am Variantenanfang muss diese Serie erreichen. 0 bedeutet, den Anfang immer zu zeigen.",
|
||||
"Cada jugada propia al inicio de la variante debe alcanzar esta racha. 0 significa mostrar siempre el inicio.",
|
||||
"Ogni propria mossa all’inizio della variante deve raggiungere questa serie. 0 significa mostrare sempre l’inizio.",
|
||||
"Cada lance seu no início da variante deve atingir essa sequência. 0 significa sempre mostrar o início.",
|
||||
"Variant boshidagi har bir yurishingiz shu ketma-ketlikka yetishi kerak. 0 — boshlanishni doim ko‘rsatish.",
|
||||
"Нұсқа басындағы әрбір өз жүрісіңіз осы серияға жетуі керек. 0 — басталуын әрдайым көрсету.",
|
||||
],
|
||||
[
|
||||
"Playback speed",
|
||||
"Скорость показа",
|
||||
"Vitesse de défilement",
|
||||
"Wiedergabegeschwindigkeit",
|
||||
"Velocidad de reproducción",
|
||||
"Velocità di riproduzione",
|
||||
"Velocidade de reprodução",
|
||||
"Namoyish tezligi",
|
||||
"Көрсету жылдамдығы",
|
||||
],
|
||||
[
|
||||
"Speed up familiar moves",
|
||||
"Ускорять знакомые ходы",
|
||||
"Accélérer les coups familiers",
|
||||
"Vertraute Züge beschleunigen",
|
||||
"Acelerar las jugadas conocidas",
|
||||
"Accelerare le mosse conosciute",
|
||||
"Acelerar lances conhecidos",
|
||||
"Tanish yurishlarni tezlashtirish",
|
||||
"Таныс жүрістерді жылдамдату",
|
||||
],
|
||||
[
|
||||
"Base speed multiplier",
|
||||
"Базовый множитель скорости",
|
||||
"Multiplicateur de vitesse de base",
|
||||
"Grundgeschwindigkeitsfaktor",
|
||||
"Multiplicador de velocidad base",
|
||||
"Moltiplicatore della velocità di base",
|
||||
"Multiplicador de velocidade base",
|
||||
"Asosiy tezlik ko‘paytirgichi",
|
||||
"Негізгі жылдамдық көбейткіші",
|
||||
],
|
||||
[
|
||||
"Base animation speed comes from board settings. Familiar moves play up to twice as fast.",
|
||||
"Базовая скорость анимации задаётся в настройках доски. Знакомые ходы показываются до двух раз быстрее.",
|
||||
"La vitesse d’animation de base vient des paramètres de l’échiquier. Les coups familiers défilent jusqu’à deux fois plus vite.",
|
||||
"Die Grundgeschwindigkeit wird in den Bretteinstellungen festgelegt. Vertraute Züge werden bis zu doppelt so schnell gezeigt.",
|
||||
"La velocidad base de animación se define en los ajustes del tablero. Las jugadas conocidas se muestran hasta el doble de rápido.",
|
||||
"La velocità di base dell’animazione è definita nelle impostazioni della scacchiera. Le mosse conosciute vengono mostrate fino al doppio della velocità.",
|
||||
"A velocidade base da animação vem das configurações do tabuleiro. Lances conhecidos são mostrados até duas vezes mais rápido.",
|
||||
"Animatsiyaning asosiy tezligi taxta sozlamalarida belgilanadi. Tanish yurishlar ikki baravargacha tezroq ko‘rsatiladi.",
|
||||
"Анимацияның негізгі жылдамдығы тақта баптауларында беріледі. Таныс жүрістер екі есеге дейін жылдамырақ көрсетіледі.",
|
||||
],
|
||||
[
|
||||
"0 or less uses the minimum speed (0.25×).",
|
||||
"0 и меньше — минимальная скорость (0,25×).",
|
||||
"0 ou moins utilise la vitesse minimale (0,25×).",
|
||||
"0 oder weniger verwendet die Mindestgeschwindigkeit (0,25×).",
|
||||
"0 o menos utiliza la velocidad mínima (0,25×).",
|
||||
"0 o meno usa la velocità minima (0,25×).",
|
||||
"0 ou menos usa a velocidade mínima (0,25×).",
|
||||
"0 yoki undan kichik qiymat — eng past tezlik (0,25×).",
|
||||
"0 немесе одан төмен — ең аз жылдамдық (0,25×).",
|
||||
],
|
||||
[
|
||||
"Learning counters do not use these playback settings.",
|
||||
"Эти параметры показа не меняют критерий «Изучено».",
|
||||
"Ces paramètres de défilement ne changent pas le critère « Appris ».",
|
||||
"Diese Wiedergabeeinstellungen ändern das Kriterium „Gelernt“ nicht.",
|
||||
"Estos ajustes de reproducción no cambian el criterio de «Aprendido».",
|
||||
"Queste impostazioni di riproduzione non modificano il criterio «Appreso».",
|
||||
"Essas configurações de reprodução não alteram o critério de «Aprendido».",
|
||||
"Bu namoyish sozlamalari «O‘rganilgan» mezonini o‘zgartirmaydi.",
|
||||
"Бұл көрсету параметрлері «Үйренілді» өлшемін өзгертпейді.",
|
||||
],
|
||||
[
|
||||
"A move is learnt after 3 correct answers in a row without hints. Only main replies for the selected colour count; shared positions count once. A wrong answer resets the streak.",
|
||||
"Ход изучен после 3 самостоятельных верных ответов подряд. Считаются основные ответы выбранного цвета, общие позиции — один раз. Ошибка сбрасывает серию.",
|
||||
"Un coup est appris après 3 bonnes réponses consécutives sans indice. Seules les réponses principales de la couleur choisie comptent ; les positions communes comptent une seule fois. Une erreur remet la série à zéro.",
|
||||
"Ein Zug gilt nach 3 richtigen Antworten in Folge ohne Hinweise als gelernt. Es zählen nur die Hauptantworten der gewählten Farbe; gemeinsame Stellungen zählen einmal. Eine falsche Antwort setzt die Serie zurück.",
|
||||
"Una jugada se considera aprendida tras 3 respuestas correctas consecutivas sin pistas. Solo cuentan las respuestas principales del color elegido; las posiciones compartidas cuentan una vez. Un error reinicia la racha.",
|
||||
"Una mossa è appresa dopo 3 risposte corrette consecutive senza suggerimenti. Contano solo le risposte principali del colore scelto; le posizioni condivise si contano una volta. Un errore azzera la serie.",
|
||||
"Um lance é aprendido após 3 respostas corretas consecutivas sem dicas. Só contam as respostas principais da cor escolhida; posições compartilhadas contam uma vez. Um erro reinicia a sequência.",
|
||||
"Yurish maslahatsiz ketma-ket 3 ta to‘g‘ri javobdan keyin o‘rganilgan hisoblanadi. Faqat tanlangan rangning asosiy javoblari hisoblanadi; umumiy pozitsiyalar bir marta sanaladi. Xato ketma-ketlikni nolga tushiradi.",
|
||||
"Жүріс кеңессіз қатарынан 3 дұрыс жауаптан кейін үйренілген болып саналады. Таңдалған түстің негізгі жауаптары ғана есептеледі; ортақ позициялар бір рет саналады. Қате серияны нөлге түсіреді.",
|
||||
],
|
||||
[
|
||||
"Nothing is due yet. Choose a review mode to practise now.",
|
||||
"По расписанию пока нечего повторять. Чтобы тренироваться сейчас, выберите режим повторения.",
|
||||
"Aucune révision n’est encore prévue. Choisissez un mode de révision pour vous entraîner maintenant.",
|
||||
"Es ist noch keine Wiederholung fällig. Wählen Sie einen Wiederholungsmodus, um jetzt zu üben.",
|
||||
"Todavía no hay repasos pendientes. Elige un modo de repaso para practicar ahora.",
|
||||
"Non ci sono ancora ripassi in scadenza. Scegli una modalità di ripasso per esercitarti ora.",
|
||||
"Ainda não há revisões pendentes. Escolha um modo de revisão para praticar agora.",
|
||||
"Hozircha takrorlash vaqti kelmagan. Hozir mashq qilish uchun takrorlash rejimini tanlang.",
|
||||
"Әзірге қайталау мерзімі келген жоқ. Қазір жаттығу үшін қайталау режимін таңдаңыз.",
|
||||
],
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -826,7 +826,6 @@ impl LargeView {
|
|||
if let Some((b, work)) = &self.booster {
|
||||
let p = (b.progress() as f32 / (*work).max(1) as f32).min(1.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(egui::Spinner::new().size(14.0));
|
||||
ui.label(
|
||||
RichText::new(trf(
|
||||
"Speeding up search in this database (once)… {p} %",
|
||||
|
|
@ -1838,7 +1837,6 @@ impl LargeView {
|
|||
ui.label(text);
|
||||
}
|
||||
if let Some(p) = progress {
|
||||
ui.add(egui::Spinner::new().size(14.0));
|
||||
ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak());
|
||||
}
|
||||
if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() {
|
||||
|
|
@ -1855,7 +1853,6 @@ impl LargeView {
|
|||
// A database from Lichess and Chess.com: its new games.
|
||||
if let Some(online) = &header.online {
|
||||
if online.busy {
|
||||
ui.add(egui::Spinner::new().size(14.0));
|
||||
ui.label(RichText::new(tr("updating…")).weak());
|
||||
} else if ui
|
||||
.add_enabled(online.enabled, egui::Button::new(tr("⟳ New games")).small())
|
||||
|
|
|
|||
|
|
@ -6,11 +6,9 @@ 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 ROW_HEIGHT: f32 = 32.0;
|
||||
const BODY_TEXT_SIZE: f32 = 14.0;
|
||||
const WIDE_NUMERIC_WIDTHS: [f32; 9] = [56.0, 60.0, 80.0, 64.0, 108.0, 96.0, 88.0, 64.0, 136.0];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct BranchSelection {
|
||||
|
|
@ -38,36 +36,29 @@ pub fn show(
|
|||
*selected = Some(selection_for(&rows[0]));
|
||||
}
|
||||
|
||||
let wide = ui.available_width() >= WIDE_WIDTH;
|
||||
let include_repertoire = include_repertoire_names(rows, names);
|
||||
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;
|
||||
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,
|
||||
);
|
||||
}
|
||||
show_table(
|
||||
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()
|
||||
if let Some(selection) = selected.as_ref()
|
||||
&& let Some(row) = rows.iter().find(|row| selection == &selection_for(row))
|
||||
{
|
||||
ui.separator();
|
||||
|
|
@ -82,15 +73,11 @@ fn selection_for(row: &BranchLearningAnalytics) -> BranchSelection {
|
|||
}
|
||||
}
|
||||
|
||||
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 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(
|
||||
|
|
@ -134,80 +121,7 @@ fn branch_text(
|
|||
}
|
||||
|
||||
#[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 WIDE_NUMERIC_WIDTHS {
|
||||
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(
|
||||
fn show_table(
|
||||
ui: &mut Ui,
|
||||
rows: &[BranchLearningAnalytics],
|
||||
names: &HashMap<RepertoireId, String>,
|
||||
|
|
@ -216,18 +130,19 @@ fn show_narrow(
|
|||
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_narrow")
|
||||
.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().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))
|
||||
.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 ["Branch", "Total", "Due", "Learnt %"]
|
||||
for (index, key) in ["Variation start", "Learnt", "Due now", "Accuracy"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
|
|
@ -246,9 +161,9 @@ fn show_narrow(
|
|||
text_cell(ui, &text, false).on_hover_text(text);
|
||||
});
|
||||
for value in [
|
||||
row.summary.total.to_string(),
|
||||
format!("{} / {}", row.summary.learnt, row.summary.total),
|
||||
row.summary.due.to_string(),
|
||||
format_percent(row.summary.learnt_percent),
|
||||
format_percent(row.summary.accuracy_percent),
|
||||
] {
|
||||
table_row.col(|ui| {
|
||||
text_cell(ui, &value, true);
|
||||
|
|
@ -273,13 +188,13 @@ fn show_details(
|
|||
.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()),
|
||||
(
|
||||
"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)),
|
||||
("Last trained", format_time(row.last_independent_at)),
|
||||
];
|
||||
show_details_rows(ui, &details);
|
||||
}
|
||||
|
|
@ -293,7 +208,7 @@ fn show_details_rows(ui: &mut Ui, details: &[(&'static str, String)]) {
|
|||
.column(Column::exact(label_width).clip(true))
|
||||
.column(Column::remainder().at_least(80.0).clip(true))
|
||||
.body(|body| {
|
||||
body.rows(ROW_HEIGHT * 1.5, details.len(), |mut row| {
|
||||
body.rows(36.0, details.len(), |mut row| {
|
||||
let (label, value) = &details[row.index()];
|
||||
row.col(|ui| {
|
||||
ui.add(
|
||||
|
|
@ -320,16 +235,6 @@ 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};
|
||||
|
|
@ -513,7 +418,7 @@ mod tests {
|
|||
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 names = fixture.names.clone();
|
||||
let shapes = render(
|
||||
&ctx,
|
||||
1200.0,
|
||||
|
|
@ -530,7 +435,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn wide_and_narrow_layouts_stay_in_bounds_in_light_and_dark() {
|
||||
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)] {
|
||||
|
|
@ -551,39 +456,18 @@ mod tests {
|
|||
);
|
||||
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}"
|
||||
);
|
||||
}
|
||||
for key in [
|
||||
"Variation start",
|
||||
"Learnt",
|
||||
"Due now",
|
||||
"Accuracy",
|
||||
"Learnt moves",
|
||||
"Not practised yet",
|
||||
] {
|
||||
assert!(
|
||||
has_translated_text(&shapes, key),
|
||||
"missing header/detail {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -591,32 +475,10 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn wide_headers_fit_accepted_matrix_in_russian_and_german() {
|
||||
fn headers_fit_accepted_matrix_in_russian_and_german() {
|
||||
let cases = [
|
||||
[
|
||||
"Ветка",
|
||||
"Итого",
|
||||
"Новый",
|
||||
"Изучается",
|
||||
"Изучено",
|
||||
"Не подтверждено",
|
||||
"К повторению",
|
||||
"Точность",
|
||||
"Изучено %",
|
||||
"Последняя тренировка",
|
||||
],
|
||||
[
|
||||
"Variante",
|
||||
"Gesamt",
|
||||
"Neu",
|
||||
"Lernen",
|
||||
"Gelernt",
|
||||
"Unsicher",
|
||||
"Fällig",
|
||||
"Genauigkeit",
|
||||
"Gelernt %",
|
||||
"Letztes Training",
|
||||
],
|
||||
["Начало варианта", "Изучено", "Повторить", "Точность"],
|
||||
["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)] {
|
||||
|
|
@ -632,12 +494,15 @@ mod tests {
|
|||
..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 width in WIDE_NUMERIC_WIDTHS {
|
||||
table = table.column(Column::exact(width).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() {
|
||||
|
|
@ -684,7 +549,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_details_are_visible_and_click_selects_the_branch() {
|
||||
fn details_are_visible_and_click_selects_the_branch() {
|
||||
let fixture = fixture();
|
||||
let ctx = egui::Context::default();
|
||||
let mut selected = None;
|
||||
|
|
@ -715,21 +580,13 @@ mod tests {
|
|||
);
|
||||
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",
|
||||
] {
|
||||
for key in ["Learnt moves", "Due now", "Not practised yet", "Accuracy"] {
|
||||
assert!(has_translated_text(&shapes, key), "missing detail {key}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrow_details_keep_long_labels_readable_at_all_widths() {
|
||||
fn details_keep_long_labels_readable_at_all_widths() {
|
||||
let cases: Vec<Vec<(&str, String)>> = vec![
|
||||
vec![
|
||||
("Новый", "2".to_owned()),
|
||||
|
|
@ -801,7 +658,7 @@ mod tests {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn null_accuracy_and_last_training_render_as_dashes() {
|
||||
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;
|
||||
|
|
@ -823,12 +680,65 @@ mod tests {
|
|||
&mut selected,
|
||||
);
|
||||
let dashes = text_occurrences(&shapes, "—");
|
||||
assert!(dashes >= 3, "expected null metrics as dashes: {dashes}");
|
||||
assert!(
|
||||
dashes >= 2,
|
||||
"expected null accuracy in table and details: {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 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]
|
||||
|
|
|
|||
|
|
@ -159,9 +159,9 @@ pub fn sequences(ui: &mut Ui, histograms: &SequenceHistograms) {
|
|||
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),
|
||||
("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());
|
||||
|
|
|
|||
|
|
@ -2,87 +2,95 @@ 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;
|
||||
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();
|
||||
});
|
||||
});
|
||||
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
|
||||
}
|
||||
|
||||
|
|
@ -171,121 +179,26 @@ mod tests {
|
|||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ use crate::settings::Settings;
|
|||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LearningDashboardAction {
|
||||
Close,
|
||||
OpenSettings,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
|
|
@ -60,7 +61,6 @@ struct DashboardView {
|
|||
}
|
||||
|
||||
struct DashboardData {
|
||||
side: LearningSide,
|
||||
as_of: i64,
|
||||
timezone: LocalDatePolicy,
|
||||
summary: Vec<SummaryRow>,
|
||||
|
|
@ -243,65 +243,76 @@ impl LearningDashboardUi {
|
|||
ui.ctx().request_repaint_after(Duration::from_millis(100));
|
||||
}
|
||||
|
||||
ui.set_width(ui.available_width());
|
||||
ui.horizontal(|ui| {
|
||||
ui.heading(tr("Learning dashboard"));
|
||||
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
|
||||
if ui.button(tr("Close")).clicked() {
|
||||
actions.push(LearningDashboardAction::Close);
|
||||
}
|
||||
});
|
||||
egui::Panel::top("learning_dashboard_header").show(ui, |ui| {
|
||||
let back = if ui.available_width() < 600.0 {
|
||||
tr("Back")
|
||||
} else {
|
||||
tr("Back to repertoire")
|
||||
};
|
||||
let (back, settings) =
|
||||
crate::widgets::section_header(ui, &format!("← {back}"), tr("Training statistics"));
|
||||
if back {
|
||||
actions.push(LearningDashboardAction::Close);
|
||||
}
|
||||
if settings {
|
||||
actions.push(LearningDashboardAction::OpenSettings);
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
self.scope_controls(ui);
|
||||
self.scope_line(ui);
|
||||
self.capture_line(ui);
|
||||
self.tabs(ui);
|
||||
ui.separator();
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
ui.add_space(4.0);
|
||||
self.scope_controls(ui);
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("learning_dashboard_scroll")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
if self.loading && self.data.is_none() {
|
||||
loading_body(ui);
|
||||
return;
|
||||
}
|
||||
if let Some(error) = self.error.clone() {
|
||||
error_body(ui, &error);
|
||||
if ui.button(tr("Retry")).clicked() {
|
||||
self.reload();
|
||||
self.tabs(ui);
|
||||
ui.separator();
|
||||
if self.tab == DashboardTab::History {
|
||||
self.capture_line(ui);
|
||||
}
|
||||
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("learning_dashboard_scroll")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
if self.loading && self.data.is_none() {
|
||||
loading_body(ui);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(data) = self.data.as_ref() else {
|
||||
loading_body(ui);
|
||||
return;
|
||||
};
|
||||
let Some(view) = data
|
||||
.views
|
||||
.iter()
|
||||
.find(|view| view.selection == self.selection)
|
||||
else {
|
||||
self.error = Some(tr("The selected scope is no longer available").to_owned());
|
||||
return;
|
||||
};
|
||||
match self.tab {
|
||||
DashboardTab::Summary => show_summary(ui, data, view),
|
||||
DashboardTab::Branches => crate::learning_branches::show(
|
||||
ui,
|
||||
&view.branches,
|
||||
&data.names,
|
||||
&data.labels,
|
||||
&mut self.selected_branch,
|
||||
),
|
||||
DashboardTab::History => show_history(ui, view),
|
||||
DashboardTab::Scheduled => show_scheduled(ui, view),
|
||||
DashboardTab::Sequences => show_sequences(ui, view),
|
||||
DashboardTab::Moves => show_moves(ui, view, &mut self.selected_move),
|
||||
}
|
||||
});
|
||||
if let Some(error) = self.error.clone() {
|
||||
error_body(ui, &error);
|
||||
if ui.button(tr("Retry")).clicked() {
|
||||
self.reload();
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(data) = self.data.as_ref() else {
|
||||
loading_body(ui);
|
||||
return;
|
||||
};
|
||||
let Some(view) = data
|
||||
.views
|
||||
.iter()
|
||||
.find(|view| view.selection == self.selection)
|
||||
else {
|
||||
self.error =
|
||||
Some(tr("The selected scope is no longer available").to_owned());
|
||||
return;
|
||||
};
|
||||
match self.tab {
|
||||
DashboardTab::Summary => show_summary(ui, data, view),
|
||||
DashboardTab::Branches => crate::learning_branches::show(
|
||||
ui,
|
||||
&view.branches,
|
||||
&data.names,
|
||||
&data.labels,
|
||||
&mut self.selected_branch,
|
||||
),
|
||||
DashboardTab::History => show_history(ui, view),
|
||||
DashboardTab::Scheduled => show_scheduled(ui, view),
|
||||
DashboardTab::Sequences => show_sequences(ui, view),
|
||||
DashboardTab::Moves => show_moves(ui, view, &mut self.selected_move),
|
||||
}
|
||||
});
|
||||
});
|
||||
actions
|
||||
}
|
||||
|
||||
|
|
@ -412,15 +423,24 @@ impl LearningDashboardUi {
|
|||
let enabled = !self.loading && !self.snapshot_pending;
|
||||
ui.add_enabled_ui(enabled, |ui| {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(RichText::new(tr("Scope")).weak());
|
||||
ui.label(RichText::new(tr("Repertoire")).weak())
|
||||
.on_hover_text(format!(
|
||||
"{}: {}",
|
||||
tr("Calculated at"),
|
||||
self.data
|
||||
.as_ref()
|
||||
.map_or_else(|| "…".to_owned(), |data| format_time(Some(data.as_of)))
|
||||
));
|
||||
let selected_text = self.selection_label(&self.selection);
|
||||
egui::ComboBox::from_id_salt("learning_dashboard_scope")
|
||||
.selected_text(selected_text)
|
||||
.width(260.0)
|
||||
.truncate()
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(
|
||||
&mut self.selection,
|
||||
ScopeSelection::Global,
|
||||
tr("All repertoires (union)"),
|
||||
tr("All repertoires"),
|
||||
);
|
||||
for repertoire in &self.library.repertoires {
|
||||
ui.selectable_value(
|
||||
|
|
@ -455,24 +475,6 @@ impl LearningDashboardUi {
|
|||
}
|
||||
}
|
||||
|
||||
fn scope_line(&self, ui: &mut Ui) {
|
||||
let (side, as_of) = self.data.as_ref().map_or_else(
|
||||
|| (self.side, "…".to_owned()),
|
||||
|data| (data.side, format_time(Some(data.as_of))),
|
||||
);
|
||||
let text = format!(
|
||||
"{}: {} · {}: {} · {}: {}",
|
||||
tr("Scope"),
|
||||
self.selection_label(&self.selection),
|
||||
tr("Side"),
|
||||
side_label(side),
|
||||
tr("Calculated at"),
|
||||
as_of
|
||||
);
|
||||
ui.add(egui::Label::new(&text).truncate())
|
||||
.on_hover_text(text);
|
||||
}
|
||||
|
||||
fn selected_capture(&self) -> Option<(StatsScope, LocalDatePolicy)> {
|
||||
let data = self.data.as_ref()?;
|
||||
let view = data
|
||||
|
|
@ -483,43 +485,22 @@ impl LearningDashboardUi {
|
|||
}
|
||||
|
||||
fn capture_line(&mut self, ui: &mut Ui) {
|
||||
let capture = self.selected_capture();
|
||||
let width = ui.available_width();
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(width, 30.0),
|
||||
Layout::left_to_right(Align::Center),
|
||||
|ui| {
|
||||
let response = ui
|
||||
.add_enabled(
|
||||
capture.is_some() && !self.snapshot_pending && !self.loading,
|
||||
egui::Button::new(tr("Save statistics to History")),
|
||||
)
|
||||
.on_hover_text(tr(
|
||||
"Save the current numbers for the selected scope and side. PGN and learning progress do not change.",
|
||||
));
|
||||
if response.clicked()
|
||||
&& let Some((scope, timezone)) = capture
|
||||
ui.label(
|
||||
egui::RichText::new(tr("History is saved automatically once a day when viewed."))
|
||||
.weak(),
|
||||
);
|
||||
if let Some(error) = self.snapshot_error.clone() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.colored_label(ui.visuals().error_fg_color, error);
|
||||
if ui
|
||||
.add_enabled(!self.snapshot_pending, egui::Button::new(tr("Retry")))
|
||||
.clicked()
|
||||
&& let Some((scope, timezone)) = self.selected_capture()
|
||||
{
|
||||
self.capture_snapshot(scope, timezone);
|
||||
}
|
||||
if self.snapshot_pending {
|
||||
ui.spinner();
|
||||
}
|
||||
let message = self
|
||||
.snapshot_error
|
||||
.as_ref()
|
||||
.or(self.snapshot_message.as_ref());
|
||||
if let Some(message) = message {
|
||||
let color = if self.snapshot_error.is_some() {
|
||||
ui.visuals().error_fg_color
|
||||
} else {
|
||||
ui.visuals().text_color()
|
||||
};
|
||||
ui.add(egui::Label::new(RichText::new(message).color(color)).truncate())
|
||||
.on_hover_text(message);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_snapshot(&mut self, scope: StatsScope, timezone: LocalDatePolicy) {
|
||||
|
|
@ -542,23 +523,37 @@ impl LearningDashboardUi {
|
|||
fn tabs(&mut self, ui: &mut Ui) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (tab, label) in [
|
||||
(DashboardTab::Summary, tr("Summary")),
|
||||
(DashboardTab::Branches, tr("Branches")),
|
||||
(DashboardTab::History, tr("History")),
|
||||
(DashboardTab::Summary, tr("Overview")),
|
||||
(DashboardTab::History, tr("Progress over time")),
|
||||
(DashboardTab::Scheduled, tr("Scheduled")),
|
||||
(DashboardTab::Sequences, tr("Sequences")),
|
||||
(DashboardTab::Moves, tr("Moves")),
|
||||
] {
|
||||
if ui.selectable_label(self.tab == tab, label).clicked() {
|
||||
self.tab = tab;
|
||||
}
|
||||
}
|
||||
let extra = match self.tab {
|
||||
DashboardTab::Branches => tr("Variants"),
|
||||
DashboardTab::Sequences => tr("Sequences"),
|
||||
_ => tr("More statistics"),
|
||||
};
|
||||
ui.menu_button(extra, |ui| {
|
||||
for (tab, label) in [
|
||||
(DashboardTab::Branches, tr("Variants")),
|
||||
(DashboardTab::Sequences, tr("Sequences")),
|
||||
] {
|
||||
if ui.selectable_label(self.tab == tab, label).clicked() {
|
||||
self.tab = tab;
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn selection_label(&self, selection: &ScopeSelection) -> String {
|
||||
match selection {
|
||||
ScopeSelection::Global => tr("All repertoires (union)").to_owned(),
|
||||
ScopeSelection::Global => tr("All repertoires").to_owned(),
|
||||
ScopeSelection::Repertoire(id) => self
|
||||
.library
|
||||
.repertoire(id)
|
||||
|
|
@ -624,7 +619,6 @@ impl DashboardData {
|
|||
});
|
||||
log_dashboard_global_total_invariant(global_total, &summary);
|
||||
Ok(Self {
|
||||
side,
|
||||
as_of,
|
||||
timezone,
|
||||
summary,
|
||||
|
|
@ -805,143 +799,108 @@ fn error_body(ui: &mut Ui, error: &str) {
|
|||
);
|
||||
}
|
||||
|
||||
const SUMMARY_HEADER_HEIGHT: f32 = 40.0;
|
||||
|
||||
fn summary_number_width(ui: &Ui) -> f32 {
|
||||
let available_width = ui.available_width();
|
||||
if available_width < 700.0 {
|
||||
60.0
|
||||
} else {
|
||||
(available_width / 9.0)
|
||||
.min(108.0)
|
||||
.min((available_width - 80.0 - 8.0 * ui.spacing().item_spacing.x) / 8.0)
|
||||
}
|
||||
}
|
||||
|
||||
fn show_summary(ui: &mut Ui, data: &DashboardData, view: &DashboardView) {
|
||||
let compact = ui.available_width() < 700.0;
|
||||
let number_width = summary_number_width(ui);
|
||||
let headers = [
|
||||
"Name",
|
||||
"Total",
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
"Learnt %",
|
||||
"Confident %",
|
||||
];
|
||||
let mut table = TableBuilder::new(ui)
|
||||
let summary = &view.summary;
|
||||
ui.add_space(8.0);
|
||||
ui.heading(trf(
|
||||
"Learnt {learnt} of {total} moves",
|
||||
&[("learnt", &summary.learnt), ("total", &summary.total)],
|
||||
))
|
||||
.on_hover_text(tr("A move is learnt after 3 correct answers in a row without hints. Only main replies for the selected colour count; shared positions count once. A wrong answer resets the streak."));
|
||||
ui.add_space(8.0);
|
||||
ui.add(
|
||||
egui::ProgressBar::new(summary.learnt_percent.unwrap_or(0.0) as f32 / 100.0)
|
||||
.desired_width(ui.available_width().min(600.0))
|
||||
.text(format_percent(summary.learnt_percent)),
|
||||
);
|
||||
ui.add_space(12.0);
|
||||
egui::Grid::new("learning_overview_counts")
|
||||
.spacing([24.0, 10.0])
|
||||
.show(ui, |ui| {
|
||||
for (label, value) in [
|
||||
("Due now", summary.due),
|
||||
("Not practised yet", summary.unseen),
|
||||
("Still learning", summary.learning),
|
||||
("Long overdue learnt moves", summary.uncertain),
|
||||
] {
|
||||
let response = ui.label(tr(label));
|
||||
if label == "Long overdue learnt moves" {
|
||||
response.on_hover_text(tr("Of the moves already learnt"));
|
||||
}
|
||||
ui.strong(value.to_string());
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.label(tr(
|
||||
"Progress counts your repertoire moves, with shared positions counted once.",
|
||||
));
|
||||
ui.add_space(12.0);
|
||||
egui::CollapsingHeader::new(tr("Learning details")).show(ui, |ui| {
|
||||
egui::Grid::new("learning_overview_details")
|
||||
.spacing([24.0, 8.0])
|
||||
.show(ui, |ui| {
|
||||
for (label, value) in [
|
||||
("Accuracy", format_percent(summary.accuracy_percent)),
|
||||
("Confident %", format_percent(summary.confident_percent)),
|
||||
("Next review", format_time(summary.next_due_at)),
|
||||
] {
|
||||
ui.label(tr(label));
|
||||
ui.label(value);
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.label(tr(
|
||||
"Learnt = Confident + Uncertain · percentages use Total.",
|
||||
));
|
||||
});
|
||||
if view.selection != ScopeSelection::Global {
|
||||
return;
|
||||
}
|
||||
ui.add_space(16.0);
|
||||
ui.strong(tr("All repertoires"));
|
||||
let number_width = (ui.available_width() * 0.14).clamp(80.0, 140.0);
|
||||
TableBuilder::new(ui)
|
||||
.id_salt("learning_dashboard_summary")
|
||||
.striped(true)
|
||||
.vscroll(false)
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(80.0).clip(true));
|
||||
for _ in 1..headers.len() {
|
||||
table = table.column(Column::exact(number_width).clip(true));
|
||||
}
|
||||
table
|
||||
.header(SUMMARY_HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.into_iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
let response = if index == 0 {
|
||||
header_cell(ui, tr(key), false)
|
||||
} else {
|
||||
summary_metric_header(ui, tr(key), compact)
|
||||
};
|
||||
response.on_hover_text(match key {
|
||||
"Total" => tr("Total = Unseen + Learning + Learnt."),
|
||||
"Uncertain" => {
|
||||
tr("Learnt = Confident + Uncertain · percentages use Total.")
|
||||
}
|
||||
_ => tr(key),
|
||||
});
|
||||
});
|
||||
.column(Column::remainder().at_least(160.0).clip(true))
|
||||
.column(Column::exact(number_width))
|
||||
.column(Column::exact(number_width))
|
||||
.column(Column::exact(number_width))
|
||||
.column(Column::exact(number_width))
|
||||
.header(40.0, |mut header| {
|
||||
for (index, label) in ["Repertoire", "Learnt moves", "Learnt %", "Due now", "Not practised yet"].into_iter().enumerate() {
|
||||
header.col(|ui| { header_cell(ui, tr(label), index > 0); });
|
||||
}
|
||||
})
|
||||
.body(|body| {
|
||||
body.rows(24.0, data.summary.len(), |mut row| {
|
||||
let summary_row = &data.summary[row.index()];
|
||||
let summary = &summary_row.summary;
|
||||
let strong = summary_row.id.is_none();
|
||||
body.rows(32.0, data.summary.len(), |mut row| {
|
||||
let item = &data.summary[row.index()];
|
||||
let global = item.id.is_none();
|
||||
row.col(|ui| {
|
||||
let name = if strong {
|
||||
tr("Global total")
|
||||
} else {
|
||||
&summary_row.name
|
||||
};
|
||||
let response = text_cell(ui, name, strong, false);
|
||||
if strong {
|
||||
response.on_hover_text(tr(
|
||||
"Global total counts each shared learning item once; repertoire rows can add up to more.",
|
||||
));
|
||||
} else {
|
||||
response.on_hover_text(&summary_row.name);
|
||||
}
|
||||
text_cell(ui, if global { tr("Total without duplicates") } else { &item.name }, global, false)
|
||||
.on_hover_text(tr("Global total counts each shared learning item once; repertoire rows can add up to more."));
|
||||
});
|
||||
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.learnt_percent),
|
||||
format_percent(summary.confident_percent),
|
||||
];
|
||||
for value in values {
|
||||
row.col(|ui| {
|
||||
text_cell(ui, &value, strong, true);
|
||||
});
|
||||
for text in [format!("{} / {}", item.summary.learnt, item.summary.total), format_percent(item.summary.learnt_percent), item.summary.due.to_string(), item.summary.unseen.to_string()] {
|
||||
row.col(|ui| { text_cell(ui, &text, global, true); });
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
ui.label(format!(
|
||||
"{}: {}",
|
||||
tr("Next due at"),
|
||||
format_time(view.summary.next_due_at)
|
||||
));
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
RichText::new(tr(
|
||||
"Learnt = Confident + Uncertain · percentages use Total.",
|
||||
))
|
||||
.weak(),
|
||||
)
|
||||
.wrap(),
|
||||
);
|
||||
}
|
||||
|
||||
fn show_history(ui: &mut Ui, view: &DashboardView) {
|
||||
if view.history.is_empty() {
|
||||
ui.label(tr(
|
||||
"No snapshots yet. Save statistics to History to record the current scope.",
|
||||
"Progress history will appear after your first daily snapshot.",
|
||||
));
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
RichText::new(tr(
|
||||
"Save the current numbers for the selected scope and side. PGN and learning progress do not change.",
|
||||
))
|
||||
.weak(),
|
||||
)
|
||||
.wrap(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
crate::learning_charts::history(ui, &view.history);
|
||||
ui.add_space(8.0);
|
||||
let number_width = 60.0;
|
||||
let headers = [
|
||||
"Date",
|
||||
"Total",
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
];
|
||||
let number_width = (ui.available_width() * 0.18).clamp(100.0, 160.0);
|
||||
let headers = ["Date", "Learnt moves", "Not practised yet", "Due now"];
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_dashboard_history")
|
||||
.striped(true)
|
||||
|
|
@ -952,7 +911,7 @@ fn show_history(ui: &mut Ui, view: &DashboardView) {
|
|||
table = table.column(Column::exact(number_width));
|
||||
}
|
||||
table
|
||||
.header(28.0, |mut header| {
|
||||
.header(40.0, |mut header| {
|
||||
for (index, key) in headers.into_iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
header_cell(ui, tr(key), index > 0);
|
||||
|
|
@ -969,14 +928,7 @@ fn show_history(ui: &mut Ui, view: &DashboardView) {
|
|||
format_time(Some(snapshot.as_of))
|
||||
));
|
||||
});
|
||||
let values = [
|
||||
snapshot.total,
|
||||
snapshot.unseen,
|
||||
snapshot.learning,
|
||||
snapshot.learnt,
|
||||
snapshot.uncertain,
|
||||
snapshot.due,
|
||||
];
|
||||
let values = [snapshot.learnt, snapshot.unseen, snapshot.due];
|
||||
for value in values {
|
||||
row.col(|ui| {
|
||||
text_cell(ui, &value.to_string(), false, true);
|
||||
|
|
@ -1386,13 +1338,6 @@ fn header_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response {
|
|||
}
|
||||
}
|
||||
|
||||
fn summary_metric_header(ui: &mut Ui, text: &str, compact: bool) -> egui::Response {
|
||||
let text = RichText::new(text)
|
||||
.strong()
|
||||
.size(if compact { 12.0 } else { 14.0 });
|
||||
ui.add(egui::Label::new(text).wrap())
|
||||
}
|
||||
|
||||
fn text_cell(ui: &mut Ui, text: &str, strong: bool, numeric: bool) -> egui::Response {
|
||||
let text = if strong {
|
||||
RichText::new(text).strong()
|
||||
|
|
@ -1401,8 +1346,8 @@ fn text_cell(ui: &mut Ui, text: &str, strong: bool, numeric: bool) -> egui::Resp
|
|||
};
|
||||
if numeric {
|
||||
let size = egui::vec2(ui.available_width(), ui.available_height());
|
||||
ui.allocate_ui_with_layout(size, Layout::left_to_right(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(text).truncate().halign(Align::Max))
|
||||
ui.allocate_ui_with_layout(size, Layout::right_to_left(Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(text).truncate())
|
||||
})
|
||||
.inner
|
||||
} else {
|
||||
|
|
@ -1563,7 +1508,7 @@ mod tests {
|
|||
library,
|
||||
learning_store,
|
||||
selection,
|
||||
side: data.side,
|
||||
side: data.views[0].scope.side,
|
||||
tab: DashboardTab::Summary,
|
||||
data: Some(data),
|
||||
loading: false,
|
||||
|
|
@ -1618,50 +1563,22 @@ mod tests {
|
|||
|
||||
fn assert_narrow_summary(shapes: &[egui::epaint::ClippedShape]) {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0));
|
||||
let mut confident_height = 0.0;
|
||||
for expected in [
|
||||
"Name",
|
||||
"Learnt 1 of 2 moves",
|
||||
"Not practised yet",
|
||||
"Still learning",
|
||||
"Due now",
|
||||
] {
|
||||
assert!(shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == expected)), "missing overview text {expected}");
|
||||
}
|
||||
for excluded in [
|
||||
"Save statistics to History",
|
||||
"Total",
|
||||
"Unseen",
|
||||
"Learning",
|
||||
"Learnt",
|
||||
"Uncertain",
|
||||
"Due",
|
||||
"Learnt %",
|
||||
"Confident %",
|
||||
"Global total",
|
||||
] {
|
||||
let (rect, clip) = 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,
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_else(|| panic!("missing full summary header {expected}"));
|
||||
assert!(
|
||||
rect.min.x >= clip.min.x - 0.1 && rect.max.x <= clip.max.x + 0.1,
|
||||
"clipped summary header {expected}: {rect:?} {clip:?}"
|
||||
);
|
||||
if expected != "Name" {
|
||||
assert!(
|
||||
rect.width() <= 60.1,
|
||||
"numeric header {expected} exceeds 60 px: {rect:?}"
|
||||
);
|
||||
}
|
||||
if expected == "Confident %" {
|
||||
confident_height = rect.height();
|
||||
}
|
||||
assert!(!shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == excluded)), "unexpected technical or unrelated text {excluded}");
|
||||
}
|
||||
assert!(
|
||||
confident_height > 20.0,
|
||||
"Confident % should wrap onto two lines"
|
||||
);
|
||||
for clipped in shapes {
|
||||
if let egui::Shape::Text(text) = &clipped.shape {
|
||||
let rect = egui::Rect::from_min_size(text.pos, text.galley.size());
|
||||
|
|
@ -1757,7 +1674,7 @@ mod tests {
|
|||
let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap();
|
||||
|
||||
assert_eq!(GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.get()), 1);
|
||||
assert_eq!(dashboard.side, LearningSide::White);
|
||||
assert_eq!(dashboard.views[0].scope.side, LearningSide::White);
|
||||
assert_eq!(dashboard.as_of, BASE);
|
||||
assert_eq!(dashboard.timezone, LocalDatePolicy::UTC);
|
||||
assert_eq!(dashboard.summary.len(), 1);
|
||||
|
|
@ -1962,7 +1879,7 @@ mod tests {
|
|||
|
||||
assert_eq!(after, before);
|
||||
assert!(output.shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Global total")
|
||||
matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Learnt 0 of 2 moves")
|
||||
}));
|
||||
assert!(!output.shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == "Loading learning statistics…")
|
||||
|
|
@ -1972,143 +1889,6 @@ mod tests {
|
|||
assert_eq!(store.load().unwrap().snapshots.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepted_summary_headers_fit_full_russian_and_german_words() {
|
||||
let cases = [
|
||||
[
|
||||
"Название",
|
||||
"Итого",
|
||||
"Новый",
|
||||
"Изучается",
|
||||
"Изучено",
|
||||
"Не подтверждено",
|
||||
"К повторению",
|
||||
"Изучено %",
|
||||
"Надёжно изучено",
|
||||
],
|
||||
[
|
||||
"Name",
|
||||
"Gesamt",
|
||||
"Neu",
|
||||
"Lernen",
|
||||
"Gelernt",
|
||||
"Unsicher",
|
||||
"Fällig",
|
||||
"Gelernt %",
|
||||
"Bestätigt %",
|
||||
],
|
||||
];
|
||||
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 mut expected_number_width = 0.0;
|
||||
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| {
|
||||
expected_number_width = summary_number_width(ui);
|
||||
let number_width = expected_number_width;
|
||||
let mut table = TableBuilder::new(ui)
|
||||
.id_salt("learning_dashboard_summary_header_test")
|
||||
.cell_layout(Layout::left_to_right(Align::Center))
|
||||
.column(Column::remainder().at_least(80.0).clip(true));
|
||||
for _ in 1..headers.len() {
|
||||
table = table.column(Column::exact(number_width).clip(true));
|
||||
}
|
||||
table.header(SUMMARY_HEADER_HEIGHT, |mut header| {
|
||||
for (index, key) in headers.iter().enumerate() {
|
||||
header.col(|ui| {
|
||||
if index == 0 {
|
||||
header_cell(ui, tr(key), false)
|
||||
} else {
|
||||
summary_metric_header(ui, tr(key), false)
|
||||
}
|
||||
.on_hover_text(tr(key));
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
let shapes = output.shapes.clone();
|
||||
output.drop_without_applying_deltas();
|
||||
for clipped in &shapes {
|
||||
let bounds = clipped.shape.visual_bounding_rect();
|
||||
if bounds.is_finite() && bounds.is_positive() {
|
||||
assert!(
|
||||
bounds.min.x >= -0.1
|
||||
&& bounds.min.y >= -0.1
|
||||
&& bounds.max.x <= width + 0.1
|
||||
&& bounds.max.y <= height + 0.1,
|
||||
"summary shape outside {width}x{height}: {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
for (index, &expected) in headers.iter().enumerate() {
|
||||
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 summary header {expected} at {width}x{height}")
|
||||
});
|
||||
assert!(lines <= 2, "summary header wraps too much: {expected}");
|
||||
assert!(
|
||||
text_lines_have_complete_words(&shapes, expected),
|
||||
"summary header has a one-character fragment: {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 summary header {expected}: {rect:?} {clip:?}"
|
||||
);
|
||||
assert!(clip.height() >= SUMMARY_HEADER_HEIGHT);
|
||||
if index == 0 {
|
||||
assert!(clip.width() >= 80.0);
|
||||
} else {
|
||||
assert!(
|
||||
(clip.width() - expected_number_width).abs() < 0.1,
|
||||
"numeric width at {width}: {clip:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text_lines_have_complete_words(
|
||||
shapes: &[egui::epaint::ClippedShape],
|
||||
expected: &str,
|
||||
) -> bool {
|
||||
shapes.iter().any(|clipped| match &clipped.shape {
|
||||
egui::Shape::Text(text) if text.galley.text().replace('\n', " ") == expected => text
|
||||
.galley
|
||||
.text()
|
||||
.lines()
|
||||
.all(|line| line.chars().count() > 1),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_tab_renders_at_both_window_sizes() {
|
||||
let dir = TestDir::new("layout");
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -121,6 +121,13 @@ fn button_w(ui: &Ui, text: &str) -> f32 {
|
|||
+ ui.spacing().item_spacing.x
|
||||
}
|
||||
|
||||
// Toolbar contents change as background probes finish and the window narrows.
|
||||
// Keep action IDs independent of the preceding widgets: egui buttons resolve
|
||||
// their visual state from the previous frame's response before being allocated.
|
||||
fn shelf_button(ui: &mut Ui, id: &str, label: impl Into<egui::WidgetText>) -> egui::Response {
|
||||
ui.push_id(id, |ui| ui.button(label)).inner
|
||||
}
|
||||
|
||||
/// A PGN file whose beginning is in a legacy (single-byte) encoding: it takes games only
|
||||
/// through a UTF-8 copy. For a file not read yet (its card's menu).
|
||||
fn legacy_pgn(path: &Path) -> bool {
|
||||
|
|
@ -172,7 +179,7 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 {
|
|||
0.0
|
||||
}
|
||||
+ if training {
|
||||
button_w(ui, tr("Opening training"))
|
||||
button_w(ui, tr("Opening training (α version)"))
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
|
|
@ -246,7 +253,8 @@ pub struct Library {
|
|||
/// Database whose import notes are shown.
|
||||
notes_open: Option<PathBuf>,
|
||||
pub selected_db: Option<PathBuf>,
|
||||
/// Lichess or Chess.com answered at start (the online games are offered).
|
||||
/// Network probe availability for updating an existing online database.
|
||||
/// The main toolbar is always available according to platform capabilities.
|
||||
pub online: bool,
|
||||
/// Online databases being downloaded or updated.
|
||||
pub online_busy: Vec<PathBuf>,
|
||||
|
|
@ -774,9 +782,12 @@ impl Library {
|
|||
self.select_db(&p, ui.ctx());
|
||||
}
|
||||
self.groups(ui, true, icons, actions);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
self.app_buttons(ui, icons, actions);
|
||||
});
|
||||
ui.scope_builder(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("shelf_app_actions")
|
||||
.layout(egui::Layout::right_to_left(egui::Align::Center)),
|
||||
|ui| self.app_buttons(ui, icons, actions),
|
||||
);
|
||||
});
|
||||
// The game put aside: a strip under the line.
|
||||
if let Some(card) = &self.aside {
|
||||
|
|
@ -789,12 +800,7 @@ impl Library {
|
|||
/// "⚙ Settings" and the newer version (right to left): the program's corner, the
|
||||
/// same as on the game screen. Icons only, with the names in the tooltips.
|
||||
fn app_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec<LibraryAction>) {
|
||||
let label = |full: &'static str, icon: &'static str| if icons { icon } else { full };
|
||||
if ui
|
||||
.button(label(tr("⚙ Settings"), "⚙"))
|
||||
.on_hover_text(shelf_hint(icons, tr("⚙ Settings"), "Ctrl+,"))
|
||||
.clicked()
|
||||
{
|
||||
if crate::widgets::settings_button(ui, icons).clicked() {
|
||||
actions.push(LibraryAction::OpenSettings);
|
||||
}
|
||||
#[cfg(not(web))]
|
||||
|
|
@ -822,8 +828,7 @@ impl Library {
|
|||
} else {
|
||||
tr("🗐 Preparations")
|
||||
};
|
||||
if ui
|
||||
.button(label)
|
||||
if shelf_button(ui, "preparations", label)
|
||||
.on_hover_text(shelf_hint(
|
||||
icons,
|
||||
tr("🗐 Preparations"),
|
||||
|
|
@ -839,7 +844,7 @@ impl Library {
|
|||
if !crate::platform::CAPS.prep {
|
||||
ui.separator();
|
||||
}
|
||||
if ui.button(tr("Opening training")).clicked() {
|
||||
if shelf_button(ui, "opening_training", tr("Opening training (α version)")).clicked() {
|
||||
actions.push(LibraryAction::OpeningTraining);
|
||||
}
|
||||
}
|
||||
|
|
@ -848,8 +853,7 @@ impl Library {
|
|||
/// "♞ Play": a game against Maia, a group of its own.
|
||||
fn play_button(&self, ui: &mut Ui, icons: bool, actions: &mut Vec<LibraryAction>) {
|
||||
let label = if icons { "♞" } else { tr("♞ Play") };
|
||||
if ui
|
||||
.button(label)
|
||||
if shelf_button(ui, "play", label)
|
||||
.on_hover_text(shelf_hint(
|
||||
icons,
|
||||
tr("♞ Play"),
|
||||
|
|
@ -865,8 +869,7 @@ impl Library {
|
|||
fn game_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec<LibraryAction>) {
|
||||
let label = |full: &'static str, icon: &'static str| if icons { icon } else { full };
|
||||
let hint = |full: &str, hint: &str| shelf_hint(icons, full, hint);
|
||||
if ui
|
||||
.button(label(tr("♟ New game"), "♟"))
|
||||
if shelf_button(ui, "new_game", label(tr("♟ New game"), "♟"))
|
||||
.on_hover_text(hint(
|
||||
tr("♟ New game"),
|
||||
tr("Empty board in the starting position (Ctrl+N)"),
|
||||
|
|
@ -875,8 +878,7 @@ impl Library {
|
|||
{
|
||||
actions.push(LibraryAction::NewGame);
|
||||
}
|
||||
if ui
|
||||
.button(label(tr("📋 Paste PGN"), "📋"))
|
||||
if shelf_button(ui, "paste_pgn", label(tr("📋 Paste PGN"), "📋"))
|
||||
.on_hover_text(hint(
|
||||
tr("📋 Paste PGN"),
|
||||
tr("Open a game from the clipboard"),
|
||||
|
|
@ -922,9 +924,12 @@ impl Library {
|
|||
ui.add_space(16.0 - ui.spacing().item_spacing.x);
|
||||
}
|
||||
self.groups(ui, folded, icons, actions);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
self.app_buttons(ui, icons, actions);
|
||||
});
|
||||
ui.scope_builder(
|
||||
egui::UiBuilder::new()
|
||||
.id_salt("shelf_app_actions")
|
||||
.layout(egui::Layout::right_to_left(egui::Align::Center)),
|
||||
|ui| self.app_buttons(ui, icons, actions),
|
||||
);
|
||||
});
|
||||
let card = self.aside.take();
|
||||
let card_w = card.as_ref().map_or(0.0, |c| c.width(ui));
|
||||
|
|
@ -963,12 +968,9 @@ impl Library {
|
|||
|
||||
/// The width of `shelf_actions`.
|
||||
fn shelf_actions_w(&self, ui: &Ui, folded: bool) -> f32 {
|
||||
let online = self.online_running.map_or(0.0, |n| {
|
||||
14.0 + ui.spacing().item_spacing.x + button_w(ui, &crate::large_db::grouped(n))
|
||||
});
|
||||
let buttons = if folded {
|
||||
if folded {
|
||||
button_w(ui, "+ ▾")
|
||||
+ if self.online {
|
||||
+ if crate::platform::CAPS.online_games {
|
||||
button_w(ui, "🌐")
|
||||
} else {
|
||||
0.0
|
||||
|
|
@ -976,17 +978,17 @@ impl Library {
|
|||
} else {
|
||||
button_w(ui, tr("+ Add database"))
|
||||
+ button_w(ui, tr("✚ New database"))
|
||||
+ if self.online {
|
||||
+ if crate::platform::CAPS.online_games {
|
||||
button_w(ui, &format!("🌐 {}", tr("Online games")))
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
};
|
||||
buttons + if self.online { online } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// «+ Add database · ✚ New database · 🌐 Online games», or folded: «+ ▾» (a menu of
|
||||
/// the first two) and «🌐»; a download under way shows its count beside the globe.
|
||||
/// the first two) and «🌐». Download progress belongs in the tooltip/dialog so
|
||||
/// background work never moves the toolbar's other actions.
|
||||
fn shelf_actions(&self, ui: &mut Ui, folded: bool, actions: &mut Vec<LibraryAction>) {
|
||||
let add_hint = tr("Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)");
|
||||
let new_hint = tr("An empty PGN file for your own games (Ctrl+Shift+N)");
|
||||
|
|
@ -994,43 +996,43 @@ impl Library {
|
|||
"Download any player's games by nickname into a database: yours, a pupil's, an opponent's",
|
||||
);
|
||||
if folded {
|
||||
ui.menu_button("+ ▾", |ui| {
|
||||
if ui
|
||||
.button(tr("Add database…"))
|
||||
.on_hover_text(add_hint)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::AddDatabases);
|
||||
ui.close();
|
||||
}
|
||||
if crate::platform::CAPS.own_databases
|
||||
&& ui
|
||||
.button(tr("New database…"))
|
||||
.on_hover_text(new_hint)
|
||||
ui.push_id("database_menu", |ui| {
|
||||
ui.menu_button("+ ▾", |ui| {
|
||||
if ui
|
||||
.button(tr("Add database…"))
|
||||
.on_hover_text(add_hint)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::NewDatabase);
|
||||
ui.close();
|
||||
}
|
||||
{
|
||||
actions.push(LibraryAction::AddDatabases);
|
||||
ui.close();
|
||||
}
|
||||
if crate::platform::CAPS.own_databases
|
||||
&& ui
|
||||
.button(tr("New database…"))
|
||||
.on_hover_text(new_hint)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::NewDatabase);
|
||||
ui.close();
|
||||
}
|
||||
})
|
||||
});
|
||||
} else {
|
||||
if ui
|
||||
.button(tr("+ Add database"))
|
||||
if shelf_button(ui, "add_database", tr("+ Add database"))
|
||||
.on_hover_text(add_hint)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::AddDatabases);
|
||||
}
|
||||
if crate::platform::CAPS.own_databases
|
||||
&& ui
|
||||
.button(tr("✚ New database"))
|
||||
&& shelf_button(ui, "new_database", tr("✚ New database"))
|
||||
.on_hover_text(new_hint)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(LibraryAction::NewDatabase);
|
||||
}
|
||||
}
|
||||
if self.online {
|
||||
if crate::platform::CAPS.online_games {
|
||||
let label = if folded {
|
||||
"🌐".to_owned()
|
||||
} else {
|
||||
|
|
@ -1040,21 +1042,27 @@ impl Library {
|
|||
Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]),
|
||||
None => online_hint.to_owned(),
|
||||
};
|
||||
if ui.button(label).on_hover_text(hint).clicked() {
|
||||
if shelf_button(ui, "online_games", label)
|
||||
.on_hover_text(hint)
|
||||
.clicked()
|
||||
{
|
||||
#[cfg(not(web))]
|
||||
actions.push(LibraryAction::OnlineGames);
|
||||
}
|
||||
if let Some(n) = self.online_running {
|
||||
ui.add(egui::Spinner::new().size(14.0));
|
||||
ui.label(RichText::new(crate::large_db::grouped(n)).weak());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The empty shelf's invitation: the three actions as large cards, centred.
|
||||
fn action_cards(&self, ui: &mut Ui, actions: &mut Vec<LibraryAction>) {
|
||||
let (add_w, new_w, online_w) = side_card_widths(ui);
|
||||
let total = add_w + new_w + if self.online { online_w + 8.0 } else { 0.0 } + 8.0;
|
||||
let total = add_w
|
||||
+ new_w
|
||||
+ if crate::platform::CAPS.online_games {
|
||||
online_w + 8.0
|
||||
} else {
|
||||
0.0
|
||||
}
|
||||
+ 8.0;
|
||||
let card = |ui: &mut Ui, w: f32, title: &str, below: Option<&str>| {
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(w, 64.0), Sense::click());
|
||||
let visuals = ui.style().interact(&resp);
|
||||
|
|
@ -1106,7 +1114,7 @@ impl Library {
|
|||
{
|
||||
actions.push(LibraryAction::NewDatabase);
|
||||
}
|
||||
if self.online
|
||||
if crate::platform::CAPS.online_games
|
||||
&& card(
|
||||
ui,
|
||||
online_w,
|
||||
|
|
@ -1537,3 +1545,223 @@ fn import_error(e: &ImportError) -> String {
|
|||
e => e.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(web)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn toolbar_frame(
|
||||
library: &mut Library,
|
||||
ctx: &egui::Context,
|
||||
width: f32,
|
||||
events: Vec<egui::Event>,
|
||||
) -> (Vec<(String, egui::Rect, egui::Color32)>, Vec<LibraryAction>) {
|
||||
toolbar_frame_at_size(library, ctx, vec2(width, 900.0), events)
|
||||
}
|
||||
|
||||
fn toolbar_frame_at_size(
|
||||
library: &mut Library,
|
||||
ctx: &egui::Context,
|
||||
size: egui::Vec2,
|
||||
events: Vec<egui::Event>,
|
||||
) -> (Vec<(String, egui::Rect, egui::Color32)>, Vec<LibraryAction>) {
|
||||
let mut actions = Vec::new();
|
||||
let mut output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
let databases = library.slots.keys().cloned().collect::<Vec<_>>();
|
||||
actions = library.show(ui, &databases, &Settings::default());
|
||||
},
|
||||
);
|
||||
output.textures_delta.clear();
|
||||
let text = output
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| {
|
||||
if let egui::Shape::Text(shape) = &clipped.shape
|
||||
&& shape.pos.y < 40.0
|
||||
{
|
||||
Some((
|
||||
shape.galley.text().to_owned(),
|
||||
egui::Rect::from_min_size(shape.pos, shape.galley.size()),
|
||||
shape.fallback_color,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
output.drop_without_applying_deltas();
|
||||
(text, actions)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_download_progress_keeps_toolbar_geometry_and_style_stable() {
|
||||
for height in [590.0, 900.0] {
|
||||
for width in [640.0, 960.0, 1100.0, 1400.0, 1920.0] {
|
||||
let ctx = egui::Context::default();
|
||||
crate::assets::install(&ctx);
|
||||
let mut library = Library::new(&ctx);
|
||||
let (pending, _) =
|
||||
toolbar_frame_at_size(&mut library, &ctx, vec2(width, height), vec![]);
|
||||
library.online = true;
|
||||
library.online_running = Some(100_000);
|
||||
let (ready, _) =
|
||||
toolbar_frame_at_size(&mut library, &ctx, vec2(width, height), vec![]);
|
||||
assert_eq!(
|
||||
pending, ready,
|
||||
"toolbar changed when background progress arrived at width {width}"
|
||||
);
|
||||
assert!(
|
||||
ready.iter().any(|(label, _, _)| label == "🌐"
|
||||
|| label == &format!("🌐 {}", tr("Online games")))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_and_update_badge_never_reuse_a_separator_as_button_style() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::assets::install(&ctx);
|
||||
let mut library = Library::new(&ctx);
|
||||
for (width, update) in [
|
||||
(1400.0, None),
|
||||
(640.0, None),
|
||||
(960.0, Some("⬆ Update 2.2.0")),
|
||||
(1920.0, Some("⬆ Update 2.2.0")),
|
||||
(1100.0, None),
|
||||
(640.0, None),
|
||||
(1400.0, None),
|
||||
] {
|
||||
library.update = update.map(str::to_owned);
|
||||
let (first, _) = toolbar_frame(&mut library, &ctx, width, vec![]);
|
||||
let (settled, _) = toolbar_frame(&mut library, &ctx, width, vec![]);
|
||||
assert_eq!(
|
||||
first, settled,
|
||||
"first resized frame had a stale response/style at {width}"
|
||||
);
|
||||
for (label, rect, color) in first {
|
||||
assert!(
|
||||
rect.left() >= 0.0 && rect.right() <= width,
|
||||
"{label}: {rect:?}"
|
||||
);
|
||||
if label != tr("Databases") && !label.starts_with('⬆') {
|
||||
assert_eq!(
|
||||
color,
|
||||
ctx.style_of(egui::Theme::Dark)
|
||||
.visuals
|
||||
.widgets
|
||||
.inactive
|
||||
.fg_stroke
|
||||
.color,
|
||||
"false noninteractive style for {label}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toolbar_actions_are_available_while_the_database_loads_and_afterwards() {
|
||||
let ctx = egui::Context::default();
|
||||
crate::assets::install(&ctx);
|
||||
let mut library = Library::new(&ctx);
|
||||
let path = PathBuf::from("/tmp/chesspenguin-toolbar-regression.pgn");
|
||||
let (_tx, rx) = channel();
|
||||
library.slots.insert(
|
||||
path.clone(),
|
||||
Slot::Loading {
|
||||
progress: Arc::new(Mutex::new(ScanProgress {
|
||||
bytes_done: 0,
|
||||
bytes_total: 100,
|
||||
games: 0,
|
||||
})),
|
||||
cancel: Arc::new(AtomicBool::new(false)),
|
||||
rx,
|
||||
},
|
||||
);
|
||||
library.selected_db = Some(path.clone());
|
||||
let (loading, _) = toolbar_frame(&mut library, &ctx, 1400.0, vec![]);
|
||||
for ready in [false, true] {
|
||||
if ready {
|
||||
let opened = chess_import::open_bytes(
|
||||
"toolbar.pgn",
|
||||
b"1. e4 e5 *".to_vec(),
|
||||
&mut |_| {},
|
||||
&AtomicBool::new(false),
|
||||
)
|
||||
.unwrap();
|
||||
library
|
||||
.large
|
||||
.insert(path.clone(), LargeView::for_database(&opened.db, false));
|
||||
library
|
||||
.slots
|
||||
.insert(path.clone(), Slot::Ready(Arc::new(opened.db)));
|
||||
library.online = true;
|
||||
library.online_running = Some(1_000_000);
|
||||
}
|
||||
let (texts, _) = toolbar_frame(
|
||||
&mut library,
|
||||
&ctx,
|
||||
1400.0,
|
||||
vec![egui::Event::PointerMoved(egui::pos2(-100.0, -100.0))],
|
||||
);
|
||||
assert_eq!(loading, texts, "database completion changed the toolbar");
|
||||
for (label, expected) in [
|
||||
(tr("+ Add database").to_owned(), LibraryAction::AddDatabases),
|
||||
(tr("✚ New database").to_owned(), LibraryAction::NewDatabase),
|
||||
(
|
||||
format!("🌐 {}", tr("Online games")),
|
||||
LibraryAction::OnlineGames,
|
||||
),
|
||||
(tr("♟ New game").to_owned(), LibraryAction::NewGame),
|
||||
(tr("📋 Paste PGN").to_owned(), LibraryAction::PastePgn),
|
||||
(tr("♞ Play").to_owned(), LibraryAction::Play),
|
||||
(tr("🗐 Preparations").to_owned(), LibraryAction::Preparations),
|
||||
(
|
||||
tr("Opening training (α version)").to_owned(),
|
||||
LibraryAction::OpeningTraining,
|
||||
),
|
||||
(tr("⚙ Settings").to_owned(), LibraryAction::OpenSettings),
|
||||
] {
|
||||
let pos = texts
|
||||
.iter()
|
||||
.find(|(text, _, _)| text == &label)
|
||||
.unwrap()
|
||||
.1
|
||||
.center();
|
||||
let button = |pressed| egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
};
|
||||
toolbar_frame(
|
||||
&mut library,
|
||||
&ctx,
|
||||
1400.0,
|
||||
vec![egui::Event::PointerMoved(pos), button(true)],
|
||||
);
|
||||
let (_, actions) = toolbar_frame(&mut library, &ctx, 1400.0, vec![button(false)]);
|
||||
assert!(
|
||||
actions.iter().any(|action| std::mem::discriminant(action)
|
||||
== std::mem::discriminant(&expected)),
|
||||
"{label} did not activate, ready={ready}"
|
||||
);
|
||||
}
|
||||
// egui reads the previous response for styling: let the final hover
|
||||
// leave before comparing the next data state.
|
||||
toolbar_frame(
|
||||
&mut library,
|
||||
&ctx,
|
||||
1400.0,
|
||||
vec![egui::Event::PointerMoved(egui::pos2(-100.0, -100.0))],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -85,7 +85,11 @@ impl Probe {
|
|||
|
||||
pub fn poll(&mut self) {
|
||||
if let Some(rx) = &self.job
|
||||
&& let Ok(a) = rx.try_recv()
|
||||
&& let Some(a) = match rx.try_recv() {
|
||||
Ok(a) => Some(a),
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => None,
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => Some([false; 2]),
|
||||
}
|
||||
{
|
||||
// A platform that answered once stays offered for the session (a later
|
||||
// failure shows as an error in the window).
|
||||
|
|
@ -109,7 +113,68 @@ impl Probe {
|
|||
self.available.iter().any(|a| *a)
|
||||
}
|
||||
|
||||
pub fn pending(&self) -> bool {
|
||||
self.job.is_some()
|
||||
}
|
||||
|
||||
/// An explicit retry from the online-games dialog, without duplicate jobs.
|
||||
pub fn retry(&mut self) {
|
||||
if !self.pending() {
|
||||
self.spawn();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pending_for_test(
|
||||
ctx: &egui::Context,
|
||||
) -> (Self, std::sync::mpsc::Sender<[bool; 2]>) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
(
|
||||
Self {
|
||||
job: Some(rx),
|
||||
available: [false; 2],
|
||||
last: None,
|
||||
ctx: ctx.clone(),
|
||||
},
|
||||
tx,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn has(&self, p: Platform) -> bool {
|
||||
self.available[p.index()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(web)))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn probe_distinguishes_pending_unavailable_ready_and_disconnected() {
|
||||
let ctx = egui::Context::default();
|
||||
let (mut probe, tx) = Probe::pending_for_test(&ctx);
|
||||
assert!(probe.pending());
|
||||
assert!(!probe.any());
|
||||
probe.retry(); // An in-flight request is kept, never duplicated.
|
||||
tx.send([false, false]).unwrap();
|
||||
probe.poll();
|
||||
assert!(!probe.pending());
|
||||
assert!(!probe.any());
|
||||
|
||||
let (mut probe, tx) = Probe::pending_for_test(&ctx);
|
||||
tx.send([true, false]).unwrap();
|
||||
probe.poll();
|
||||
assert!(!probe.pending());
|
||||
assert!(probe.has(Platform::Lichess));
|
||||
assert!(!probe.has(Platform::ChessCom));
|
||||
|
||||
let (mut probe, tx) = Probe::pending_for_test(&ctx);
|
||||
drop(tx);
|
||||
probe.poll();
|
||||
assert!(
|
||||
!probe.pending(),
|
||||
"a failed worker must not leave a perpetual check"
|
||||
);
|
||||
assert!(!probe.any());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -274,7 +274,8 @@ impl OnlineDialog {
|
|||
}
|
||||
|
||||
/// Collects finished work; the window itself when open.
|
||||
pub fn show(&mut self, ctx: &egui::Context, probe: &Probe) -> Vec<OnlineEvent> {
|
||||
pub fn show(&mut self, ctx: &egui::Context, probe: &mut Probe) -> Vec<OnlineEvent> {
|
||||
probe.poll();
|
||||
let mut events = Vec::new();
|
||||
if let Some(l) = &self.lookup
|
||||
&& let Some(r) = l.poll()
|
||||
|
|
@ -354,7 +355,7 @@ impl OnlineDialog {
|
|||
events
|
||||
}
|
||||
|
||||
fn body(&mut self, ui: &mut Ui, probe: &Probe, events: &mut Vec<OnlineEvent>) {
|
||||
fn body(&mut self, ui: &mut Ui, probe: &mut Probe, events: &mut Vec<OnlineEvent>) {
|
||||
ui.label(
|
||||
RichText::new(tr(
|
||||
"Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.",
|
||||
|
|
@ -362,6 +363,22 @@ impl OnlineDialog {
|
|||
.weak(),
|
||||
);
|
||||
ui.add_space(6.0);
|
||||
if !probe.any() {
|
||||
if probe.pending() {
|
||||
ui.add(egui::Label::new(tr("Checking access to Lichess and Chess.com…")).wrap());
|
||||
} else {
|
||||
ui.add(
|
||||
egui::Label::new(tr(
|
||||
"Couldn't connect. Check your internet connection and try again.",
|
||||
))
|
||||
.wrap(),
|
||||
);
|
||||
if ui.button(tr("Retry")).clicked() {
|
||||
probe.retry();
|
||||
}
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
let both = probe.has(Platform::Lichess) && probe.has(Platform::ChessCom);
|
||||
let mut enter = false;
|
||||
ui.horizontal(|ui| {
|
||||
|
|
@ -693,3 +710,74 @@ impl OnlineDialog {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rendered_text(dialog: &mut OnlineDialog, probe: &mut Probe) -> Vec<String> {
|
||||
let ctx = egui::Context::default();
|
||||
let mut text = Vec::new();
|
||||
for frame in 0..2 {
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(960.0, 900.0),
|
||||
)),
|
||||
time: Some(f64::from(frame)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
dialog.body(ui, probe, &mut Vec::new());
|
||||
});
|
||||
},
|
||||
);
|
||||
text = output
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) => Some(t.galley.text().to_owned()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_online_entry_explains_probe_state_and_only_offers_ready_platforms() {
|
||||
let ctx = egui::Context::default();
|
||||
let (mut probe, tx) = Probe::pending_for_test(&ctx);
|
||||
let mut dialog = OnlineDialog::default();
|
||||
dialog.open();
|
||||
dialog.nick = "SomePlayer".to_owned();
|
||||
let text = rendered_text(&mut dialog, &mut probe);
|
||||
assert!(
|
||||
text.iter()
|
||||
.any(|t| t == tr("Checking access to Lichess and Chess.com…"))
|
||||
);
|
||||
assert!(!text.iter().any(|t| t == "Lichess" || t == "Chess.com"));
|
||||
tx.send([false, false]).unwrap();
|
||||
probe.poll();
|
||||
let text = rendered_text(&mut dialog, &mut probe);
|
||||
assert!(text.iter().any(|t| t == tr("Couldn't connect. Check your internet connection and try again.")));
|
||||
assert!(text.iter().any(|t| t == tr("Retry")));
|
||||
assert_eq!(dialog.nick, "SomePlayer");
|
||||
|
||||
let (mut probe, tx) = Probe::pending_for_test(&ctx);
|
||||
tx.send([true, false]).unwrap();
|
||||
probe.poll();
|
||||
let text = rendered_text(&mut dialog, &mut probe);
|
||||
assert!(text.iter().any(|t| t == "Lichess"));
|
||||
assert!(!text.iter().any(|t| t == "Chess.com"));
|
||||
assert!(
|
||||
!text
|
||||
.iter()
|
||||
.any(|t| t == tr("Checking access to Lichess and Chess.com…"))
|
||||
);
|
||||
assert_eq!(dialog.nick, "SomePlayer");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,9 @@ use serde::{Deserialize, Serialize};
|
|||
|
||||
use crate::prep_ui::ColorChoice;
|
||||
|
||||
/// Version of the eligibility rules used for the saved error counters.
|
||||
pub const ERROR_SELECTION_VERSION: u32 = 1;
|
||||
|
||||
/// What the list of preparations knows of one.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct SavedPrep {
|
||||
|
|
@ -34,6 +37,14 @@ pub struct SavedPrep {
|
|||
pub errors: ErrorCounts,
|
||||
/// The errors were searched (else the counts mean nothing).
|
||||
pub evaluated: bool,
|
||||
#[serde(default)]
|
||||
pub error_selection_version: u32,
|
||||
}
|
||||
|
||||
impl SavedPrep {
|
||||
pub fn errors_current(&self) -> bool {
|
||||
self.error_selection_version == ERROR_SELECTION_VERSION
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder of the saved preparations.
|
||||
|
|
@ -111,7 +122,11 @@ pub fn get(dir: &Path, id: &str) -> Option<SavedPrep> {
|
|||
|
||||
/// Its report, if it can be read.
|
||||
pub fn report(dir: &Path, id: &str) -> Option<PrepReport> {
|
||||
serde_json::from_slice(&std::fs::read(report_path(dir, id)).ok()?).ok()
|
||||
let mut report: PrepReport =
|
||||
serde_json::from_slice(&std::fs::read(report_path(dir, id)).ok()?).ok()?;
|
||||
// Stored evaluations remain useful when the rules for selecting errors change.
|
||||
report.refresh();
|
||||
Some(report)
|
||||
}
|
||||
|
||||
/// Keeps `meta` and `report` as the preparation of their player and database (the
|
||||
|
|
@ -170,9 +185,27 @@ mod tests {
|
|||
games: 3,
|
||||
errors: ErrorCounts::default(),
|
||||
evaluated: false,
|
||||
error_selection_version: ERROR_SELECTION_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_error_counts_are_not_marked_current() {
|
||||
let current = meta("/db/a.pgn", [7], "Target", 10);
|
||||
assert!(current.errors_current());
|
||||
let mut json = serde_json::to_value(¤t).expect("metadata");
|
||||
json.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("error_selection_version");
|
||||
let legacy: SavedPrep = serde_json::from_value(json).expect("legacy metadata");
|
||||
assert!(!legacy.errors_current());
|
||||
let future = SavedPrep {
|
||||
error_selection_version: ERROR_SELECTION_VERSION + 1,
|
||||
..current
|
||||
};
|
||||
assert!(!future.errors_current());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_listed_replaced_renamed_and_deleted() {
|
||||
let dir = std::env::temp_dir().join(format!("cp-prep-saved-{}", std::process::id()));
|
||||
|
|
@ -227,6 +260,71 @@ mod tests {
|
|||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn saved_report_rejudges_stale_errors_without_losing_evaluations() {
|
||||
let dir = std::env::temp_dir().join(format!("cp-prep-rejudge-{}", std::process::id()));
|
||||
let mut stale: PrepReport = serde_json::from_str(REPORT).expect("report");
|
||||
stale.search = game_review::SEARCH_VERSION;
|
||||
stale.games.push(prep::GameInfo {
|
||||
index: 0,
|
||||
white: true,
|
||||
opponent: "Other".into(),
|
||||
opponent_elo: 0,
|
||||
date: String::new(),
|
||||
outcome: prep::Outcome::Unknown,
|
||||
ucis: vec!["e2e4".into(), "e7e5".into(), "g1f3".into()],
|
||||
sans: vec!["e4".into(), "e5".into(), "Nf3".into()],
|
||||
keys: vec![1, 2, 3, 4],
|
||||
opening: None,
|
||||
named: None,
|
||||
book: None,
|
||||
});
|
||||
stale.white.games = vec![0];
|
||||
for (key, cp, best) in [
|
||||
(1, 0, "e2e4"),
|
||||
(2, 0, "c7c5"),
|
||||
(3, 150, "f1c4"),
|
||||
(4, 0, "b8c6"),
|
||||
] {
|
||||
stale.evals.insert(
|
||||
key,
|
||||
prep::PositionEval {
|
||||
nodes: 1000,
|
||||
eval: prep::Eval::Cp(cp),
|
||||
pv: vec![best.into()],
|
||||
depth: 10,
|
||||
},
|
||||
);
|
||||
}
|
||||
// This cached Nf3 error followed Black's earlier error, so it no longer
|
||||
// belongs in preparation despite its evaluations being fully cached.
|
||||
stale.white.errors.push(prep::OpeningError {
|
||||
game: 0,
|
||||
ply: 2,
|
||||
key: 3,
|
||||
uci: "g1f3".into(),
|
||||
san: "Nf3".into(),
|
||||
best_uci: "f1c4".into(),
|
||||
best_san: "Bc4".into(),
|
||||
judgement: prep::Judgement::Mistake,
|
||||
before: prep::Eval::Cp(150),
|
||||
after: prep::Eval::Cp(0),
|
||||
opening: None,
|
||||
});
|
||||
stale.white.counts.mistakes = 1;
|
||||
let metadata = meta("/db/stale.pgn", [7], "Target", 10);
|
||||
save(&dir, &metadata, &stale).expect("save stale report");
|
||||
let key = id(&metadata.path, &metadata.names);
|
||||
let stored = std::fs::read(report_path(&dir, &key)).expect("stored bytes");
|
||||
let loaded = super::report(&dir, &key).expect("load saved report");
|
||||
assert!(loaded.white.errors.is_empty());
|
||||
assert_eq!(loaded.white.counts.total(), 0);
|
||||
assert_eq!(loaded.evals, stale.evals);
|
||||
assert_eq!(loaded.games, stale.games);
|
||||
assert_eq!(std::fs::read(report_path(&dir, &key)).unwrap(), stored);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn started_preparation_is_listed_before_its_report_exists() {
|
||||
let dir = std::env::temp_dir().join(format!("cp-prep-meta-{}", std::process::id()));
|
||||
|
|
|
|||
|
|
@ -968,7 +968,9 @@ impl PrepList {
|
|||
)
|
||||
.format("%d.%m.%Y")
|
||||
.to_string();
|
||||
let errors = if item.evaluated {
|
||||
let errors = if item.evaluated && !item.errors_current() {
|
||||
String::new()
|
||||
} else if item.evaluated {
|
||||
let e = &item.errors;
|
||||
trf(
|
||||
"errors: ?? {b} · ? {m} · ?! {i}",
|
||||
|
|
@ -983,8 +985,12 @@ impl PrepList {
|
|||
};
|
||||
let path = item.path.display().to_string();
|
||||
if found {
|
||||
let line =
|
||||
format!("{errors} · {}", trf("saved {date}", &[("date", &when)]));
|
||||
let saved = trf("saved {date}", &[("date", &when)]);
|
||||
let line = if errors.is_empty() {
|
||||
saved
|
||||
} else {
|
||||
format!("{errors} · {saved}")
|
||||
};
|
||||
ui.add(egui::Label::new(RichText::new(line).small().weak()).truncate());
|
||||
} else {
|
||||
ui.add(
|
||||
|
|
@ -1735,7 +1741,9 @@ impl PrepScreen {
|
|||
// A saved report missing on disk (a crash between the writes) is restored
|
||||
// from the cache the same way.
|
||||
let restore = saved.is_some() && !had_saved_report && screen.report.is_some();
|
||||
if screen.saved && (saved.is_none() || restore) {
|
||||
let rejudged =
|
||||
saved.as_ref().is_some_and(|s| !s.errors_current()) && screen.report.is_some();
|
||||
if screen.saved && (saved.is_none() || restore || rejudged) {
|
||||
let result = if screen.report.is_some() {
|
||||
screen.keep()
|
||||
} else {
|
||||
|
|
@ -2417,6 +2425,7 @@ impl PrepScreen {
|
|||
games,
|
||||
errors,
|
||||
evaluated,
|
||||
error_selection_version: crate::prep_saved::ERROR_SELECTION_VERSION,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ use crate::settings::Settings;
|
|||
#[derive(Debug)]
|
||||
pub enum RepertoireEditorAction {
|
||||
Close,
|
||||
OpenSettings,
|
||||
Cancel,
|
||||
Applied {
|
||||
repertoire_id: RepertoireId,
|
||||
|
|
@ -71,46 +72,42 @@ impl RepertoireEditorUi {
|
|||
) -> Vec<RepertoireEditorAction> {
|
||||
let mut actions = Vec::new();
|
||||
let mut commands = Vec::new();
|
||||
self.show_header(ui, &mut commands);
|
||||
egui::Panel::top("repertoire_editor_header").show(ui, |ui| {
|
||||
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 width = available.width();
|
||||
let height = available.height();
|
||||
if width < 900.0 && height > width {
|
||||
let panel_height = (height * 0.52).clamp(340.0, 520.0);
|
||||
let board_rect = egui::Rect::from_min_max(
|
||||
available.min,
|
||||
egui::pos2(available.right(), board_bottom.min(available.bottom())),
|
||||
egui::pos2(available.right(), available.bottom() - panel_height),
|
||||
);
|
||||
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);
|
||||
egui::CentralPanel::default().show(ui, |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);
|
||||
egui::Frame::side_top_panel(ui.style())
|
||||
.show(ui, |ui| 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);
|
||||
});
|
||||
egui::Panel::right("repertoire_workspace_side")
|
||||
.resizable(true)
|
||||
.default_size((width * 0.42).clamp(420.0, 560.0))
|
||||
.size_range(360.0..=(width - 220.0).max(360.0))
|
||||
.show(ui, |ui| self.show_panel(ui, &mut commands));
|
||||
egui::CentralPanel::default().show(ui, |ui| self.show_board(ui, settings));
|
||||
}
|
||||
for command in commands {
|
||||
match command {
|
||||
EditorCommand::Close => actions.push(RepertoireEditorAction::Close),
|
||||
EditorCommand::OpenSettings => actions.push(RepertoireEditorAction::OpenSettings),
|
||||
EditorCommand::Cancel => {
|
||||
self.cancel();
|
||||
actions.push(RepertoireEditorAction::Cancel);
|
||||
|
|
@ -154,24 +151,39 @@ impl RepertoireEditorUi {
|
|||
}
|
||||
|
||||
fn show_header(&self, ui: &mut Ui, commands: &mut Vec<EditorCommand>) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button(tr("Close")).clicked() {
|
||||
let compact = ui.available_width() < 600.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(26.0);
|
||||
if ui
|
||||
.button(format!("← {}", tr("Back to repertoire")))
|
||||
.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();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::widgets::settings_button(ui, compact).clicked() {
|
||||
commands.push(EditorCommand::OpenSettings);
|
||||
}
|
||||
ui.separator();
|
||||
ui.add_enabled_ui(self.has_unsaved(), |ui| {
|
||||
if ui.button(tr("Save")).clicked() {
|
||||
commands.push(EditorCommand::Save);
|
||||
}
|
||||
});
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
commands.push(EditorCommand::Cancel);
|
||||
}
|
||||
if let Some(repertoire) = self.draft.repertoire(&self.repertoire_id) {
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(&repertoire.name).heading()).truncate(),
|
||||
)
|
||||
.on_hover_text(&repertoire.name);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
|
||||
fn show_board(&mut self, ui: &mut Ui, settings: &Settings) {
|
||||
|
|
@ -232,6 +244,19 @@ impl RepertoireEditorUi {
|
|||
}
|
||||
|
||||
fn show_panel(&mut self, ui: &mut Ui, commands: &mut Vec<EditorCommand>) {
|
||||
let tree_height = (ui.available_height() * 0.55).max(160.0);
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), tree_height),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_editor_tree")
|
||||
.max_height(tree_height)
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| self.show_tree(ui, commands));
|
||||
},
|
||||
);
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
|
|
@ -245,24 +270,38 @@ impl RepertoireEditorUi {
|
|||
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"));
|
||||
});
|
||||
let mut unlimited = repertoire.max_plies == u32::MAX;
|
||||
if ui.checkbox(&mut unlimited, tr("No depth limit")).changed() {
|
||||
commands.push(EditorCommand::SetDepth(if unlimited {
|
||||
u32::MAX
|
||||
} else {
|
||||
20
|
||||
}));
|
||||
}
|
||||
if !unlimited {
|
||||
let mut depth = if repertoire.max_plies == u32::MAX {
|
||||
20
|
||||
} else {
|
||||
repertoire.max_plies
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Depth"));
|
||||
if ui
|
||||
.add(egui::DragValue::new(&mut depth).range(0..=u32::MAX - 1))
|
||||
.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);
|
||||
egui::CollapsingHeader::new(tr("Move analytics"))
|
||||
.id_salt("repertoire_editor_analytics")
|
||||
.show(ui, |ui| self.show_analytics(ui));
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -329,11 +368,7 @@ impl RepertoireEditorUi {
|
|||
ui.strong(tr("PGN tree"));
|
||||
let root = self.tree.root();
|
||||
if ui
|
||||
.add(
|
||||
egui::Button::new(tr("Initial position"))
|
||||
.selected(self.selected == root)
|
||||
.truncate(),
|
||||
)
|
||||
.add(egui::Button::selectable(self.selected == root, tr("Initial position")).truncate())
|
||||
.clicked()
|
||||
{
|
||||
commands.push(EditorCommand::Select(root));
|
||||
|
|
@ -368,9 +403,10 @@ impl RepertoireEditorUi {
|
|||
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)
|
||||
.add_sized(
|
||||
[ui.available_width(), 24.0],
|
||||
egui::Button::selectable(self.selected == row.node, "")
|
||||
.left_text(label)
|
||||
.truncate(),
|
||||
)
|
||||
.clicked()
|
||||
|
|
@ -382,7 +418,6 @@ impl RepertoireEditorUi {
|
|||
}
|
||||
|
||||
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;
|
||||
|
|
@ -563,6 +598,7 @@ impl RepertoireEditorUi {
|
|||
#[derive(Clone, Copy)]
|
||||
enum EditorCommand {
|
||||
Close,
|
||||
OpenSettings,
|
||||
Cancel,
|
||||
Save,
|
||||
Select(NodeId),
|
||||
|
|
@ -768,6 +804,51 @@ mod tests {
|
|||
editor.tree.game().children(editor.tree.root())[index]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_controls_hide_unlimited_sentinel_and_keep_odd_half_moves() {
|
||||
let (library, id) = library();
|
||||
let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap();
|
||||
for depth in [u32::MAX, 7] {
|
||||
editor
|
||||
.draft
|
||||
.repertoire_mut(&id)
|
||||
.unwrap()
|
||||
.set_max_plies(depth);
|
||||
let ctx = egui::Context::default();
|
||||
let mut commands = Vec::new();
|
||||
let output = ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(420.0, 600.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| editor.show_panel(ui, &mut commands),
|
||||
);
|
||||
let texts: Vec<_> = output
|
||||
.shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| {
|
||||
if let egui::Shape::Text(shape) = &clipped.shape {
|
||||
Some(shape.galley.text().to_owned())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert!(texts.iter().any(|text| text == "No depth limit"));
|
||||
assert!(!texts.iter().any(|text| text.contains("4294967295")));
|
||||
if depth == 7 {
|
||||
assert!(texts.iter().any(|text| text == "7"));
|
||||
assert!(texts.iter().any(|text| text == "plies"));
|
||||
}
|
||||
assert!(commands.is_empty());
|
||||
assert_eq!(editor.draft.repertoire(&id).unwrap().max_plies, depth);
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn main_answer_assignment_is_validated_and_clear_restores_pgn_default() {
|
||||
let (library, id) = library();
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ use trainer::repertoire::{
|
|||
};
|
||||
|
||||
use crate::board::{BoardState, BoardView};
|
||||
use crate::i18n::tr;
|
||||
use crate::i18n::{tr, trf};
|
||||
use crate::learning_dashboard::{LearningDashboardAction, LearningDashboardUi};
|
||||
use crate::learning_training::{LearningTrainingAction as TrainingAction, LearningTrainingUi};
|
||||
use crate::repertoire_editor::{RepertoireEditorAction, RepertoireEditorUi};
|
||||
|
|
@ -50,7 +50,6 @@ struct LibraryRow {
|
|||
}
|
||||
|
||||
const OPENING_LINES: usize = 5;
|
||||
const ACTION_BUTTON_WIDTH: f32 = 120.0;
|
||||
const ROW_VERTICAL_PADDING: f32 = 8.0;
|
||||
const ROW_BOTTOM_PADDING: f32 = 4.0;
|
||||
const TITLE_HEIGHT: f32 = 24.0;
|
||||
|
|
@ -145,6 +144,7 @@ struct TestLayout {
|
|||
table: Option<egui::Rect>,
|
||||
reset_review: Option<egui::Rect>,
|
||||
editor: Option<egui::Rect>,
|
||||
action_buttons: [Option<egui::Rect>; 3],
|
||||
}
|
||||
|
||||
pub struct RepertoireUi {
|
||||
|
|
@ -156,6 +156,8 @@ pub struct RepertoireUi {
|
|||
learning_error: Option<String>,
|
||||
error: Option<String>,
|
||||
selected: Option<RepertoireId>,
|
||||
initial_selection_pending: bool,
|
||||
parameters_open: bool,
|
||||
scroll_to_selected: bool,
|
||||
tree: Option<Arc<RepertoireTree>>,
|
||||
trees: HashMap<RepertoireId, Arc<RepertoireTree>>,
|
||||
|
|
@ -219,6 +221,8 @@ impl RepertoireUi {
|
|||
learning_error,
|
||||
error: None,
|
||||
selected,
|
||||
initial_selection_pending: true,
|
||||
parameters_open: false,
|
||||
scroll_to_selected: true,
|
||||
tree: None,
|
||||
trees: HashMap::new(),
|
||||
|
|
@ -315,8 +319,9 @@ impl RepertoireUi {
|
|||
self.editor = None;
|
||||
self.editor_id = None;
|
||||
}
|
||||
fn handle_editor_action(&mut self, action: RepertoireEditorAction) {
|
||||
fn handle_editor_action(&mut self, action: RepertoireEditorAction) -> Option<RepertoireAction> {
|
||||
match action {
|
||||
RepertoireEditorAction::OpenSettings => return Some(RepertoireAction::OpenSettings),
|
||||
RepertoireEditorAction::Close | RepertoireEditorAction::Cancel => self.close_editor(),
|
||||
RepertoireEditorAction::Applied {
|
||||
repertoire_id,
|
||||
|
|
@ -334,6 +339,7 @@ impl RepertoireUi {
|
|||
}
|
||||
RepertoireEditorAction::Error(error) => self.error = Some(error),
|
||||
}
|
||||
None
|
||||
}
|
||||
pub fn open_library(&mut self) {
|
||||
self.preparing = false;
|
||||
|
|
@ -368,6 +374,7 @@ impl RepertoireUi {
|
|||
});
|
||||
}
|
||||
fn select(&mut self, id: RepertoireId, settings: &Settings) {
|
||||
self.initial_selection_pending = false;
|
||||
if self
|
||||
.editor
|
||||
.as_ref()
|
||||
|
|
@ -823,6 +830,12 @@ impl RepertoireUi {
|
|||
}
|
||||
}
|
||||
fn poll(&mut self, settings: &mut Settings) {
|
||||
if self.initial_selection_pending {
|
||||
self.initial_selection_pending = false;
|
||||
if let Some(id) = self.selected.clone() {
|
||||
self.select(id, settings);
|
||||
}
|
||||
}
|
||||
while let Ok(event) = self.rx.try_recv() {
|
||||
match event {
|
||||
Event::Aggregated(key, result) => {
|
||||
|
|
@ -969,6 +982,7 @@ impl RepertoireUi {
|
|||
self.training_visible = false;
|
||||
self.scroll_to_selected = true;
|
||||
}
|
||||
TrainingAction::OpenSettings => actions.push(RepertoireAction::OpenSettings),
|
||||
TrainingAction::Sound(sound) => actions.push(RepertoireAction::Sound(sound)),
|
||||
TrainingAction::Toast(text) => actions.push(RepertoireAction::Toast(text)),
|
||||
}
|
||||
|
|
@ -976,7 +990,6 @@ impl RepertoireUi {
|
|||
return actions;
|
||||
}
|
||||
if self.editor.is_some() {
|
||||
self.errors(ui);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.editor = Some(ui.available_rect_before_wrap());
|
||||
|
|
@ -984,7 +997,7 @@ impl RepertoireUi {
|
|||
let mut editor = self.editor.take().expect("checked repertoire editor");
|
||||
let emitted = editor.show(ui, settings, &self.library_store);
|
||||
for action in emitted {
|
||||
self.handle_editor_action(action);
|
||||
actions.extend(self.handle_editor_action(action));
|
||||
}
|
||||
if self.editor_id.is_some() {
|
||||
self.editor = Some(editor);
|
||||
|
|
@ -993,9 +1006,11 @@ impl RepertoireUi {
|
|||
}
|
||||
if self.dashboard.is_some() {
|
||||
let mut dashboard = self.dashboard.take().expect("checked learning dashboard");
|
||||
let close = dashboard
|
||||
.show(ui, settings)
|
||||
.contains(&LearningDashboardAction::Close);
|
||||
let emitted = dashboard.show(ui, settings);
|
||||
let close = emitted.contains(&LearningDashboardAction::Close);
|
||||
if emitted.contains(&LearningDashboardAction::OpenSettings) {
|
||||
actions.push(RepertoireAction::OpenSettings);
|
||||
}
|
||||
if close {
|
||||
self.reload_learning();
|
||||
} else {
|
||||
|
|
@ -1011,27 +1026,23 @@ impl RepertoireUi {
|
|||
actions.push(RepertoireAction::Close);
|
||||
}
|
||||
egui::Panel::top("repertoire_header").show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
if ui
|
||||
.button(if self.return_to_game.is_some() {
|
||||
tr("← To game")
|
||||
} else {
|
||||
tr("← Databases")
|
||||
})
|
||||
.clicked()
|
||||
{
|
||||
actions.push(RepertoireAction::Close);
|
||||
}
|
||||
ui.heading(tr("Opening training"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("⚙").on_hover_text(tr("Settings")).clicked() {
|
||||
actions.push(RepertoireAction::OpenSettings);
|
||||
}
|
||||
});
|
||||
});
|
||||
let back = if self.return_to_game.is_some() {
|
||||
tr("← To game")
|
||||
} else {
|
||||
tr("← Databases")
|
||||
};
|
||||
let (back, settings) =
|
||||
crate::widgets::section_header(ui, back, tr("Opening training (α version)"));
|
||||
if back {
|
||||
actions.push(RepertoireAction::Close);
|
||||
}
|
||||
if settings {
|
||||
actions.push(RepertoireAction::OpenSettings);
|
||||
}
|
||||
});
|
||||
self.show_workspace(ui, settings, &mut actions);
|
||||
self.show_add(ui, &mut actions);
|
||||
self.parameters_window(ui.ctx(), settings, &mut actions);
|
||||
actions
|
||||
}
|
||||
fn errors(&mut self, ui: &mut Ui) {
|
||||
|
|
@ -1124,20 +1135,29 @@ impl RepertoireUi {
|
|||
}
|
||||
fn show_library(&mut self, ui: &mut Ui, settings: &Settings) {
|
||||
self.errors(ui);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui.button(tr("+ Create")).clicked() {
|
||||
self.edit_name = Some((None, String::new()));
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
self.cancel.is_none() && self.library_error.is_none(),
|
||||
egui::Button::new(tr("Import PGN…")),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.pick_import(None, ui.ctx());
|
||||
}
|
||||
});
|
||||
egui::Panel::bottom("repertoire_library_footer")
|
||||
.resizable(false)
|
||||
.exact_size(44.0)
|
||||
.show(ui, |ui| {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
if ui
|
||||
.add_sized([120.0, 28.0], egui::Button::new(tr("+ Create")))
|
||||
.clicked()
|
||||
{
|
||||
self.edit_name = Some((None, String::new()));
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
self.cancel.is_none() && self.library_error.is_none(),
|
||||
egui::Button::new(tr("Import PGN…")).min_size(egui::vec2(120.0, 28.0)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.pick_import(None, ui.ctx());
|
||||
}
|
||||
});
|
||||
});
|
||||
self.name_editor(ui, settings);
|
||||
if self.import.is_some() {
|
||||
self.import_preview(ui, settings);
|
||||
|
|
@ -1196,6 +1216,7 @@ impl RepertoireUi {
|
|||
let mut clicked = None;
|
||||
let mut import = None;
|
||||
let mut export = None;
|
||||
let mut edit = None;
|
||||
ui.add_space(8.0);
|
||||
let compact = ui.available_width() < 480.0;
|
||||
ui.style_mut().interaction.selectable_labels = false;
|
||||
|
|
@ -1323,6 +1344,16 @@ impl RepertoireUi {
|
|||
});
|
||||
row.col(|ui| {
|
||||
ui.menu_button("⋯", |ui| {
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.has_unsaved() && !self.preparing,
|
||||
egui::Button::new(tr("Edit")),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
edit = Some(r.id.clone());
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tr("Rename")).clicked() {
|
||||
self.edit_name = Some((Some(r.id.clone()), r.name.clone()));
|
||||
ui.close();
|
||||
|
|
@ -1357,6 +1388,10 @@ impl RepertoireUi {
|
|||
if let Some(id) = clicked {
|
||||
self.select(id, settings);
|
||||
}
|
||||
if let Some(id) = edit {
|
||||
self.select(id, settings);
|
||||
self.open_editor();
|
||||
}
|
||||
if let Some(id) = import {
|
||||
self.pick_import(Some(id), ui.ctx());
|
||||
}
|
||||
|
|
@ -1489,251 +1524,263 @@ impl RepertoireUi {
|
|||
.as_ref()
|
||||
.and_then(|id| self.library.repertoire(id).cloned())
|
||||
.map(|r| (r.id.clone(), r));
|
||||
let selected_height = (ui.available_height() * 0.48).clamp(180.0, 520.0);
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_selected_scroll")
|
||||
.max_height(selected_height)
|
||||
.auto_shrink([false, true])
|
||||
.show(ui, |ui| {
|
||||
if let Some((id, r)) = selected {
|
||||
egui::Frame::new()
|
||||
.fill(ui.visuals().faint_bg_color)
|
||||
.corner_radius(6.0)
|
||||
.inner_margin(egui::Margin::symmetric(10, 8))
|
||||
.show(ui, |ui| {
|
||||
ui.add_enabled_ui(!self.preparing, |ui| {
|
||||
let previous_side = self.side;
|
||||
let previous_queue = self.queue;
|
||||
let previous_priority = self.priority;
|
||||
ui.horizontal(|ui| {
|
||||
ui.add(
|
||||
egui::Label::new(RichText::new(&r.name).heading())
|
||||
.truncate(),
|
||||
)
|
||||
.on_hover_text(&r.name);
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.has_unsaved(),
|
||||
egui::Button::new(tr("Edit")),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.open_editor();
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
egui::Grid::new("repertoire_selected_controls")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 6.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(tr("Color"));
|
||||
ui.horizontal(|ui| {
|
||||
for side in [LearningSide::White, LearningSide::Black] {
|
||||
ui.selectable_value(
|
||||
&mut self.side,
|
||||
side,
|
||||
learning_side_label(side),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Mode"));
|
||||
egui::ComboBox::from_id_salt("repertoire_learning_mode")
|
||||
.selected_text(queue_mode_label(self.queue))
|
||||
.width(220.0)
|
||||
.truncate()
|
||||
.show_ui(ui, |ui| {
|
||||
for queue in [
|
||||
QueueMode::SpacedRepetition,
|
||||
QueueMode::ReviewInOrder,
|
||||
QueueMode::LeastRecent,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut self.queue,
|
||||
queue,
|
||||
queue_mode_label(queue),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
if self.queue != QueueMode::SpacedRepetition {
|
||||
ui.label(tr("Learning priority"));
|
||||
egui::ComboBox::from_id_salt(
|
||||
"repertoire_learning_priority",
|
||||
)
|
||||
.selected_text(learning_priority_label(self.priority))
|
||||
.width(220.0)
|
||||
.truncate()
|
||||
.show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
for priority in [
|
||||
LearningPriority::DepthFirst,
|
||||
LearningPriority::BreadthOverDepth,
|
||||
LearningPriority::MainLinesFirst,
|
||||
LearningPriority::CommonPositionsFirst,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut self.priority,
|
||||
priority,
|
||||
learning_priority_label(priority),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
ui.end_row();
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Variants"));
|
||||
if let Some(count) = self.variant_counts.get(&id) {
|
||||
ui.label(count.to_string());
|
||||
} else {
|
||||
ui.add(egui::Spinner::new().size(16.0));
|
||||
ui.ctx().request_repaint_after(
|
||||
std::time::Duration::from_millis(100),
|
||||
);
|
||||
}
|
||||
});
|
||||
let aggregate = self
|
||||
.selected_aggregate()
|
||||
.map(|scoped| scoped.summary.clone());
|
||||
let resume = self.queue == QueueMode::SpacedRepetition
|
||||
&& self.has_unfinished_review_snapshot();
|
||||
let kind = aggregate
|
||||
.as_ref()
|
||||
.map_or(StartKind::Unavailable, |summary| {
|
||||
self.selected_start_kind(summary)
|
||||
});
|
||||
let ready = kind != StartKind::Unavailable
|
||||
&& !self.preparing
|
||||
&& self.learning_error.is_none()
|
||||
&& self.library_error.is_none();
|
||||
let cta = match (self.queue, kind) {
|
||||
(QueueMode::SpacedRepetition, StartKind::Review)
|
||||
if resume =>
|
||||
{
|
||||
tr("Continue").to_owned()
|
||||
}
|
||||
(QueueMode::SpacedRepetition, StartKind::Review) => {
|
||||
format!(
|
||||
"{} · {}",
|
||||
tr("Start training"),
|
||||
aggregate
|
||||
.as_ref()
|
||||
.map_or(0, |summary| summary.due)
|
||||
)
|
||||
}
|
||||
(
|
||||
QueueMode::SpacedRepetition,
|
||||
StartKind::IntroduceNew,
|
||||
) => tr("Introduce new moves").to_owned(),
|
||||
_ => tr("Start training").to_owned(),
|
||||
};
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
ui.add_enabled_ui(ready, |ui| {
|
||||
if crate::widgets::primary_wide(
|
||||
ui,
|
||||
&cta,
|
||||
ACTION_BUTTON_WIDTH,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.start(settings);
|
||||
if self.preparing {
|
||||
actions.push(
|
||||
RepertoireAction::SettingsChanged,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
ui.end_row();
|
||||
});
|
||||
if self.queue == QueueMode::ReviewInOrder {
|
||||
ui.horizontal(|ui| {
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.reset_review =
|
||||
Some(ui.max_rect());
|
||||
}
|
||||
let enabled = self.has_review_snapshot()
|
||||
&& !self.review_reset_pending
|
||||
&& !self.has_unsaved();
|
||||
if ui
|
||||
.add_enabled(
|
||||
enabled,
|
||||
egui::Button::new(tr("Reset Review Order"))
|
||||
.min_size(egui::vec2(
|
||||
ACTION_BUTTON_WIDTH,
|
||||
26.0,
|
||||
)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.reset_review_cursor();
|
||||
}
|
||||
if self.review_reset_pending {
|
||||
ui.add(egui::Spinner::new().size(16.0));
|
||||
ui.ctx().request_repaint_after(
|
||||
std::time::Duration::from_millis(100),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
let mut context_policy = settings
|
||||
.repertoire_context_policies
|
||||
.get(id.as_str())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
if crate::learning_context_controls::show(ui, &mut context_policy) {
|
||||
settings
|
||||
.repertoire_context_policies
|
||||
.insert(id.to_string(), context_policy);
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
ui.add_space(6.0);
|
||||
let preferences_changed = previous_side != self.side
|
||||
|| previous_queue != self.queue
|
||||
|| previous_priority != self.priority;
|
||||
if previous_side != self.side || previous_queue != self.queue {
|
||||
settings.repertoire_modes.insert(
|
||||
id.to_string(),
|
||||
(training_mode(self.side), self.queue),
|
||||
);
|
||||
}
|
||||
if previous_priority != self.priority {
|
||||
settings
|
||||
.repertoire_priorities
|
||||
.insert(id.to_string(), self.priority);
|
||||
}
|
||||
if preferences_changed {
|
||||
self.close_editor();
|
||||
self.invalidate_reset_jobs();
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
ui.separator();
|
||||
self.statistics_panel(ui);
|
||||
});
|
||||
if let Some((id, r)) = selected {
|
||||
ui.add_enabled_ui(!self.preparing, |ui| {
|
||||
let previous_side = self.side;
|
||||
let previous_queue = self.queue;
|
||||
let previous_priority = self.priority;
|
||||
ui.add(egui::Label::new(RichText::new(&r.name).heading()).truncate())
|
||||
.on_hover_text(&r.name);
|
||||
ui.add_space(6.0);
|
||||
egui::Grid::new("repertoire_selected_controls")
|
||||
.num_columns(2)
|
||||
.spacing([12.0, 6.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(tr("Color"));
|
||||
ui.horizontal(|ui| {
|
||||
for side in [LearningSide::White, LearningSide::Black] {
|
||||
ui.selectable_value(
|
||||
&mut self.side,
|
||||
side,
|
||||
learning_side_label(side),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
ui.label(tr("Mode"));
|
||||
egui::ComboBox::from_id_salt("repertoire_learning_mode")
|
||||
.selected_text(queue_mode_label(self.queue))
|
||||
.width(220.0)
|
||||
.truncate()
|
||||
.show_ui(ui, |ui| {
|
||||
for queue in [
|
||||
QueueMode::SpacedRepetition,
|
||||
QueueMode::ReviewInOrder,
|
||||
QueueMode::LeastRecent,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut self.queue,
|
||||
queue,
|
||||
queue_mode_label(queue),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
let aggregate = self
|
||||
.selected_aggregate()
|
||||
.map(|scoped| scoped.summary.clone());
|
||||
let resume = self.queue == QueueMode::SpacedRepetition
|
||||
&& self.has_unfinished_review_snapshot();
|
||||
let kind = aggregate
|
||||
.as_ref()
|
||||
.map_or(StartKind::Unavailable, |summary| {
|
||||
self.selected_start_kind(summary)
|
||||
});
|
||||
let ready = kind != StartKind::Unavailable
|
||||
&& !self.preparing
|
||||
&& self.learning_error.is_none()
|
||||
&& self.library_error.is_none();
|
||||
let cta = match (self.queue, kind) {
|
||||
(QueueMode::SpacedRepetition, StartKind::Review) if resume => tr("Continue"),
|
||||
_ => tr("Train"),
|
||||
};
|
||||
self.statistics_panel(ui);
|
||||
if r.max_plies != u32::MAX {
|
||||
ui.label(RichText::new(tr("Training scope: selected part")).weak());
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
let button_width = (ui.available_width() - 16.0) / 3.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 8.0;
|
||||
ui.add_enabled_ui(ready, |ui| {
|
||||
let response = crate::widgets::primary_wide(ui, cta, button_width);
|
||||
let response = if kind == StartKind::Unavailable
|
||||
&& aggregate.as_ref().is_some_and(|s| s.total > 0)
|
||||
&& self.learning_error.is_none()
|
||||
&& self.library_error.is_none()
|
||||
{
|
||||
response.on_disabled_hover_text(tr(
|
||||
"Nothing is due yet. Choose a review mode to practise now.",
|
||||
))
|
||||
} else {
|
||||
response
|
||||
};
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.action_buttons[0] = Some(response.rect);
|
||||
}
|
||||
if response.clicked() {
|
||||
self.start(settings);
|
||||
if self.preparing {
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
}
|
||||
});
|
||||
let parameters = ui.add(
|
||||
egui::Button::new(tr("Parameters"))
|
||||
.min_size(egui::vec2(button_width, 30.0)),
|
||||
);
|
||||
if parameters.clicked() {
|
||||
self.parameters_open = true;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.action_buttons[1] = Some(parameters.rect);
|
||||
}
|
||||
let response = ui.add_enabled(
|
||||
!self.has_unsaved() && !self.preparing,
|
||||
egui::Button::new(tr("Statistics"))
|
||||
.min_size(egui::vec2(button_width, 30.0)),
|
||||
);
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.action_buttons[2] = Some(response.rect);
|
||||
}
|
||||
if response.clicked() {
|
||||
self.open_dashboard();
|
||||
}
|
||||
});
|
||||
self.shared_reset_panel(ui);
|
||||
let preferences_changed = previous_side != self.side
|
||||
|| previous_queue != self.queue
|
||||
|| previous_priority != self.priority;
|
||||
if previous_side != self.side || previous_queue != self.queue {
|
||||
settings
|
||||
.repertoire_modes
|
||||
.insert(id.to_string(), (training_mode(self.side), self.queue));
|
||||
}
|
||||
if previous_priority != self.priority {
|
||||
settings
|
||||
.repertoire_priorities
|
||||
.insert(id.to_string(), self.priority);
|
||||
}
|
||||
if preferences_changed {
|
||||
self.close_editor();
|
||||
self.invalidate_reset_jobs();
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
self.show_library(ui, settings);
|
||||
}
|
||||
fn parameters_window(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
settings: &mut Settings,
|
||||
actions: &mut Vec<RepertoireAction>,
|
||||
) {
|
||||
if !self.parameters_open {
|
||||
return;
|
||||
}
|
||||
let Some(id) = self.selected.clone() else {
|
||||
self.parameters_open = false;
|
||||
return;
|
||||
};
|
||||
let name = self
|
||||
.library
|
||||
.repertoire(&id)
|
||||
.map(|r| r.name.clone())
|
||||
.unwrap_or_default();
|
||||
let aggregate = self.selected_aggregate().map(|a| a.summary.clone());
|
||||
let previous_priority = self.priority;
|
||||
let mut close = false;
|
||||
let modal = egui::Modal::new(egui::Id::new("repertoire_parameters")).show(ctx, |ui| {
|
||||
ui.set_width((ctx.content_rect().width() - 40.0).clamp(240.0, 440.0));
|
||||
ui.heading(tr("Training parameters"));
|
||||
ui.add(egui::Label::new(egui::RichText::new(&name).strong()).truncate())
|
||||
.on_hover_text(&name);
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
egui::RichText::new(tr("Changes apply to new sessions. Continuing a saved session keeps its previous settings.")).weak(),
|
||||
)
|
||||
.wrap(),
|
||||
);
|
||||
ui.separator();
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt("repertoire_parameters_scroll")
|
||||
.max_height((ctx.content_rect().height() - 200.0).max(100.0))
|
||||
.auto_shrink([false, true])
|
||||
.show(ui, |ui| {
|
||||
if self.queue != QueueMode::SpacedRepetition {
|
||||
ui.label(tr("Learning priority"));
|
||||
egui::ComboBox::from_id_salt("repertoire_learning_priority")
|
||||
.selected_text(learning_priority_label(self.priority))
|
||||
.width(280.0)
|
||||
.truncate()
|
||||
.show_ui(ui, |ui| {
|
||||
for priority in [
|
||||
LearningPriority::DepthFirst,
|
||||
LearningPriority::BreadthOverDepth,
|
||||
LearningPriority::MainLinesFirst,
|
||||
LearningPriority::CommonPositionsFirst,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut self.priority,
|
||||
priority,
|
||||
learning_priority_label(priority),
|
||||
);
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
let mut context_policy = settings
|
||||
.repertoire_context_policies
|
||||
.get(id.as_str())
|
||||
.copied()
|
||||
.unwrap_or_default();
|
||||
if crate::learning_context_controls::show(ui, &mut context_policy) {
|
||||
settings
|
||||
.repertoire_context_policies
|
||||
.insert(id.to_string(), context_policy);
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
ui.separator();
|
||||
if self.queue == QueueMode::ReviewInOrder {
|
||||
let enabled = self.has_review_snapshot()
|
||||
&& !self.review_reset_pending
|
||||
&& !self.has_unsaved();
|
||||
let response =
|
||||
ui.add_enabled(enabled, egui::Button::new(tr("Reset Review Order")));
|
||||
#[cfg(test)]
|
||||
{
|
||||
self.debug_layout.reset_review = Some(response.rect);
|
||||
}
|
||||
if response.clicked() {
|
||||
self.reset_review_cursor();
|
||||
}
|
||||
}
|
||||
let enabled = aggregate.as_ref().is_some_and(|summary| summary.total > 0)
|
||||
&& !self.has_unsaved()
|
||||
&& !self.preparing;
|
||||
if ui
|
||||
.add_enabled(enabled, egui::Button::new(tr("Reset learning progress…")))
|
||||
.clicked()
|
||||
&& let Some(scope) =
|
||||
self.selected_aggregate().map(|scoped| scoped.scope.clone())
|
||||
{
|
||||
self.begin_shared_reset(scope);
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
close |= ui.button(tr("Close")).clicked();
|
||||
});
|
||||
});
|
||||
if self.priority != previous_priority {
|
||||
settings
|
||||
.repertoire_priorities
|
||||
.insert(id.to_string(), self.priority);
|
||||
self.invalidate_reset_jobs();
|
||||
actions.push(RepertoireAction::SettingsChanged);
|
||||
}
|
||||
if close || modal.should_close() {
|
||||
self.parameters_open = false;
|
||||
}
|
||||
}
|
||||
fn current_aggregate_key(&self) -> Option<AggregateKey> {
|
||||
Some(AggregateKey {
|
||||
id: self.selected.clone()?,
|
||||
|
|
@ -1823,106 +1870,38 @@ impl RepertoireUi {
|
|||
});
|
||||
}
|
||||
fn statistics_panel(&mut self, ui: &mut Ui) {
|
||||
let aggregate = self
|
||||
let summary = self
|
||||
.selected_aggregate()
|
||||
.map(|scoped| (scoped.scope.clone(), scoped.summary.clone()));
|
||||
let summary = aggregate.as_ref().map(|(_, summary)| summary);
|
||||
.map(|scoped| scoped.summary.clone());
|
||||
if summary.as_ref().is_some_and(|summary| summary.total == 0) {
|
||||
ui.strong(tr("No moves to train"));
|
||||
ui.label(tr("Add variations in the editor or import PGN"));
|
||||
return;
|
||||
}
|
||||
let count = |metric: fn(&LearningAggregate) -> usize| {
|
||||
summary.map_or_else(|| "…".to_owned(), |summary| metric(summary).to_string())
|
||||
summary
|
||||
.as_ref()
|
||||
.map_or_else(|| "…".to_owned(), |summary| metric(summary).to_string())
|
||||
};
|
||||
let percent = |metric: fn(&LearningAggregate) -> Option<f64>| {
|
||||
summary.map_or_else(|| "…".to_owned(), |summary| format_percent(metric(summary)))
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
ui.strong(tr("Statistics"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let enabled = summary.is_some_and(|summary| summary.total > 0)
|
||||
&& !self.has_unsaved()
|
||||
&& !self.preparing;
|
||||
if ui
|
||||
.add_enabled(
|
||||
enabled,
|
||||
egui::Button::new(tr("Reset"))
|
||||
.min_size(egui::vec2(ACTION_BUTTON_WIDTH, 26.0)),
|
||||
)
|
||||
.clicked()
|
||||
&& let Some((scope, _)) = aggregate.clone()
|
||||
{
|
||||
self.begin_shared_reset(scope);
|
||||
}
|
||||
if ui
|
||||
.add_enabled(
|
||||
!self.has_unsaved() && !self.preparing,
|
||||
egui::Button::new(tr("Details"))
|
||||
.min_size(egui::vec2(ACTION_BUTTON_WIDTH, 26.0)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.open_dashboard();
|
||||
}
|
||||
});
|
||||
});
|
||||
self.shared_reset_panel(ui);
|
||||
ui.add(
|
||||
egui::Label::new(format!(
|
||||
"{} · {}",
|
||||
tr("Scope: whole repertoire"),
|
||||
learning_side_label(self.side)
|
||||
))
|
||||
.truncate(),
|
||||
);
|
||||
ui.label(format!(
|
||||
"{}: {}",
|
||||
tr("Calculated at"),
|
||||
aggregate.as_ref().map_or_else(
|
||||
|| "…".to_owned(),
|
||||
|(scope, _)| format_time(Some(scope.as_of))
|
||||
)
|
||||
ui.strong(trf(
|
||||
"Learnt {learnt} of {total} moves",
|
||||
&[
|
||||
("learnt", &count(|summary| summary.learnt)),
|
||||
("total", &count(|summary| summary.total)),
|
||||
],
|
||||
))
|
||||
.on_hover_text(tr("A move is learnt after 3 correct answers in a row without hints. Only main replies for the selected colour count; shared positions count once. A wrong answer resets the streak."));
|
||||
ui.label(trf(
|
||||
"Unseen: {unseen} · Due now: {due}",
|
||||
&[
|
||||
("unseen", &count(|summary| summary.unseen)),
|
||||
("due", &count(|summary| summary.due)),
|
||||
],
|
||||
));
|
||||
if summary.is_none() {
|
||||
ui.ctx()
|
||||
.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
egui::Grid::new("repertoire_statistics")
|
||||
.num_columns(4)
|
||||
.spacing([10.0, 4.0])
|
||||
.show(ui, |ui| {
|
||||
ui.label(RichText::new(tr("Total")).weak());
|
||||
ui.label(count(|summary| summary.total));
|
||||
ui.label(RichText::new(tr("Unseen")).weak());
|
||||
ui.label(count(|summary| summary.unseen));
|
||||
ui.end_row();
|
||||
ui.label(RichText::new(tr("Learning")).weak());
|
||||
ui.label(count(|summary| summary.learning));
|
||||
ui.label(RichText::new(tr("Learnt")).weak());
|
||||
ui.label(count(|summary| summary.learnt));
|
||||
ui.end_row();
|
||||
ui.label(RichText::new(tr("Uncertain")).weak());
|
||||
ui.label(count(|summary| summary.uncertain));
|
||||
ui.label(RichText::new(tr("Due")).weak());
|
||||
ui.label(count(|summary| summary.due));
|
||||
ui.end_row();
|
||||
ui.label(RichText::new(tr("Learnt %")).weak());
|
||||
ui.label(percent(|summary| summary.learnt_percent));
|
||||
ui.label(RichText::new(tr("Confident %")).weak());
|
||||
ui.label(percent(|summary| summary.confident_percent));
|
||||
ui.end_row();
|
||||
ui.label(RichText::new(tr("Next review")).weak());
|
||||
ui.label(summary.map_or_else(
|
||||
|| "…".to_owned(),
|
||||
|summary| format_time(summary.next_due_at),
|
||||
));
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
RichText::new(tr(
|
||||
"Learnt = Confident + Uncertain · percentages use Total.",
|
||||
))
|
||||
.weak(),
|
||||
)
|
||||
.wrap(),
|
||||
);
|
||||
}
|
||||
fn shared_reset_panel(&mut self, ui: &mut Ui) {
|
||||
let Some(state) = &self.shared_reset else {
|
||||
|
|
@ -2256,7 +2235,7 @@ fn mode_start_kind(queue: QueueMode, summary: &LearningAggregate) -> StartKind {
|
|||
}
|
||||
fn queue_mode_label(queue: QueueMode) -> &'static str {
|
||||
tr(match queue {
|
||||
QueueMode::Practice | QueueMode::SpacedRepetition => "Review individual moves",
|
||||
QueueMode::Practice | QueueMode::SpacedRepetition => "On schedule",
|
||||
QueueMode::ReviewInOrder => "Review in order",
|
||||
QueueMode::LeastRecent => "Least recent and unseen first",
|
||||
})
|
||||
|
|
@ -2281,9 +2260,6 @@ fn learning_side_label(side: LearningSide) -> &'static str {
|
|||
LearningSide::Black => "Black",
|
||||
})
|
||||
}
|
||||
fn format_percent(value: Option<f64>) -> String {
|
||||
value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %"))
|
||||
}
|
||||
fn opening_labels(tree: &RepertoireTree) -> Vec<OpeningLabel> {
|
||||
let mut labels = BTreeSet::new();
|
||||
let start = tree.game().start().position();
|
||||
|
|
@ -2378,16 +2354,6 @@ fn stores() -> (LibraryStore, LearningStore) {
|
|||
)
|
||||
}
|
||||
|
||||
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)]
|
||||
#[path = "repertoire_ui_tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -151,6 +151,38 @@ fn click_events(position: egui::Pos2) -> Vec<egui::Event> {
|
|||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_entry_restores_selected_preferences_and_starts_without_reselecting() {
|
||||
let mut f = Fixture::new();
|
||||
f.settings.repertoire_modes.insert(
|
||||
f.id.to_string(),
|
||||
(TrainingMode::Black, QueueMode::ReviewInOrder),
|
||||
);
|
||||
f.settings
|
||||
.repertoire_priorities
|
||||
.insert(f.id.to_string(), LearningPriority::BreadthOverDepth);
|
||||
f.ui = RepertoireUi::with_stores(f.ui.library_store.clone(), f.ui.learning_store.clone());
|
||||
assert_eq!(f.ui.selected.as_ref(), Some(&f.id));
|
||||
let ctx = egui::Context::default();
|
||||
// Production entry: show(), without the debug_open/select hooks.
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.0, Vec::new());
|
||||
assert_eq!(f.ui.side, LearningSide::Black);
|
||||
assert_eq!(f.ui.queue, QueueMode::ReviewInOrder);
|
||||
assert_eq!(f.ui.priority, LearningPriority::BreadthOverDepth);
|
||||
f.aggregate();
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 1.0, Vec::new());
|
||||
let train = f.ui.debug_layout.action_buttons[0].unwrap().center();
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 2.0, click_events(train));
|
||||
assert!(
|
||||
f.ui.preparing,
|
||||
"the selected repertoire starts on the first click"
|
||||
);
|
||||
while f.ui.preparing {
|
||||
f.deliver(f.completed_job());
|
||||
}
|
||||
assert!(f.ui.training_visible);
|
||||
}
|
||||
|
||||
fn text_click_position(shapes: &[egui::epaint::ClippedShape], text: &str) -> egui::Pos2 {
|
||||
shapes
|
||||
.iter()
|
||||
|
|
@ -178,7 +210,7 @@ fn dashboard_close_reloads_learning_and_preserves_repertoire_selection() {
|
|||
f.ui.side = LearningSide::Black;
|
||||
let ctx = egui::Context::default();
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.0, Vec::new());
|
||||
let details = text_click_position(&shapes, "Details");
|
||||
let details = text_click_position(&shapes, "Statistics");
|
||||
|
||||
let (actions, _) =
|
||||
render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 1.0, click_events(details));
|
||||
|
|
@ -214,7 +246,7 @@ fn dashboard_close_reloads_learning_and_preserves_repertoire_selection() {
|
|||
.unwrap();
|
||||
let (actions, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 2.0, Vec::new());
|
||||
assert!(actions.is_empty());
|
||||
let close = text_click_position(&shapes, "Close");
|
||||
let close = text_click_position(&shapes, "← Back to repertoire");
|
||||
f.ui.scroll_to_selected = false;
|
||||
|
||||
let (actions, _) =
|
||||
|
|
@ -265,7 +297,7 @@ fn dashboard_close_reloads_learning_and_preserves_repertoire_selection() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn compact_statistics_names_total_and_explains_percentages() {
|
||||
fn compact_statistics_shows_actionable_counts() {
|
||||
let mut f = Fixture::new();
|
||||
f.aggregate();
|
||||
let ctx = egui::Context::default();
|
||||
|
|
@ -284,10 +316,8 @@ fn compact_statistics_names_total_and_explains_percentages() {
|
|||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().replace('\n', " ") == expected)
|
||||
})
|
||||
};
|
||||
assert!(has_text("Total"));
|
||||
assert!(has_text(
|
||||
"Learnt = Confident + Uncertain · percentages use Total."
|
||||
));
|
||||
assert!(has_text("Learnt 0 of 1 moves"));
|
||||
assert!(has_text("Unseen: 1 · Due now: 0"));
|
||||
output.drop_without_applying_deltas();
|
||||
}
|
||||
|
||||
|
|
@ -330,10 +360,10 @@ fn dashboard_uses_the_full_workspace_at_both_window_sizes() {
|
|||
},
|
||||
);
|
||||
let dashboard_visible = output.shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Learning dashboard")
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Training statistics")
|
||||
});
|
||||
let repertoire_header_visible = output.shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Opening training")
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Opening training (α version)")
|
||||
});
|
||||
output.drop_without_applying_deltas();
|
||||
|
||||
|
|
@ -442,7 +472,7 @@ fn applied_editor_library_is_adopted_without_a_second_save() {
|
|||
let expected = applied.clone();
|
||||
let generation = f.ui.index_generation;
|
||||
|
||||
f.ui.handle_editor_action(RepertoireEditorAction::Applied {
|
||||
let _ = f.ui.handle_editor_action(RepertoireEditorAction::Applied {
|
||||
repertoire_id: f.id.clone(),
|
||||
library: applied,
|
||||
});
|
||||
|
|
@ -464,7 +494,7 @@ fn cancelling_editor_does_not_change_library_bytes() {
|
|||
let before = std::fs::read(f.ui.library_store.path()).unwrap();
|
||||
let library = f.ui.library.clone();
|
||||
|
||||
f.ui.handle_editor_action(RepertoireEditorAction::Cancel);
|
||||
let _ = f.ui.handle_editor_action(RepertoireEditorAction::Cancel);
|
||||
|
||||
assert!(f.ui.editor.is_none());
|
||||
assert_eq!(
|
||||
|
|
@ -585,7 +615,7 @@ fn stale_applied_is_ignored_after_changing_repertoire() {
|
|||
stale.repertoire_mut(&f.id).unwrap().set_max_plies(3);
|
||||
f.ui.select(second.clone(), &f.settings);
|
||||
|
||||
f.ui.handle_editor_action(RepertoireEditorAction::Applied {
|
||||
let _ = f.ui.handle_editor_action(RepertoireEditorAction::Applied {
|
||||
repertoire_id: f.id.clone(),
|
||||
library: stale,
|
||||
});
|
||||
|
|
@ -1229,39 +1259,25 @@ fn review_order_reset_changes_only_the_cycle_cursor() {
|
|||
#[test]
|
||||
fn review_reset_controls_keep_statistics_and_library_visible() {
|
||||
let mut f = Fixture::new();
|
||||
let mut settings = f.settings.clone();
|
||||
let mut actions = Vec::new();
|
||||
{
|
||||
let mut run = |queue| {
|
||||
f.ui.queue = queue;
|
||||
f.ui.debug_layout.reset_review = None;
|
||||
let ctx = egui::Context::default();
|
||||
ctx.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(640.0, 480.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
f.ui.show_workspace(ui, &mut settings, &mut actions);
|
||||
});
|
||||
},
|
||||
)
|
||||
.drop_without_applying_deltas();
|
||||
let table = f.ui.debug_layout.table.expect("library table");
|
||||
assert!(
|
||||
table.top() < 480.0,
|
||||
"table is outside the viewport: {table:?}"
|
||||
);
|
||||
assert!(table.height() > 0.0);
|
||||
f.ui.debug_layout.reset_review.is_some()
|
||||
};
|
||||
|
||||
assert!(run(QueueMode::ReviewInOrder));
|
||||
assert!(!run(QueueMode::LeastRecent));
|
||||
for queue in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] {
|
||||
f.ui.queue = queue;
|
||||
f.ui.parameters_open = false;
|
||||
f.ui.debug_layout.reset_review = None;
|
||||
let ctx = egui::Context::default();
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.0, Vec::new());
|
||||
let parameters = text_click_position(&shapes, "Parameters");
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.1, click_events(parameters));
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.2, Vec::new());
|
||||
let table = f.ui.debug_layout.table.expect("library table");
|
||||
assert!(
|
||||
table.top() < 600.0,
|
||||
"table is outside the viewport: {table:?}"
|
||||
);
|
||||
assert!(table.height() > 0.0);
|
||||
assert_eq!(
|
||||
f.ui.debug_layout.reset_review.is_some(),
|
||||
queue == QueueMode::ReviewInOrder
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1294,7 +1310,6 @@ fn due_start_has_priority_and_there_is_no_hidden_early_or_empty_start() {
|
|||
start_kind(&LearningAggregate::default()),
|
||||
StartKind::Unavailable
|
||||
);
|
||||
assert_eq!(format_percent(None), "—");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -1628,6 +1643,18 @@ fn training_scope_uses_repertoire_depth_and_custom_context_policy() {
|
|||
assert_eq!(scoped.scope.max_depth, Some(2));
|
||||
assert_eq!(scoped.summary.total, 1);
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.0, Vec::new());
|
||||
assert!(shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text() == "Learnt 0 of 1 moves")
|
||||
}));
|
||||
assert!(!shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().contains("Depth") || shape.galley.text().contains("4294967295"))
|
||||
}));
|
||||
assert!(!shapes.iter().any(|clipped| {
|
||||
matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().contains("Scope: whole repertoire"))
|
||||
}));
|
||||
|
||||
f.start();
|
||||
f.deliver(f.completed_job());
|
||||
|
||||
|
|
@ -1645,10 +1672,10 @@ fn context_control_changes_are_saved_from_the_workspace() {
|
|||
let mut f = Fixture::new();
|
||||
let ctx = egui::Context::default();
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.0, Vec::new());
|
||||
let header = text_click_position(&shapes, "Context and move speed");
|
||||
let (_, shapes) =
|
||||
render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 1.0, click_events(header));
|
||||
let fixed = text_click_position(&shapes, "Use fixed piece movement speed");
|
||||
let settings = text_click_position(&shapes, "Parameters");
|
||||
render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.1, click_events(settings));
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 0.2, Vec::new());
|
||||
let fixed = text_click_position(&shapes, "Speed up familiar moves");
|
||||
|
||||
let (actions, _) =
|
||||
render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 2.0, click_events(fixed));
|
||||
|
|
@ -1665,3 +1692,36 @@ fn context_control_changes_are_saved_from_the_workspace() {
|
|||
.unwrap();
|
||||
assert!(!policy.use_fixed_piece_speed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preparation_actions_share_one_size_and_row() {
|
||||
let mut f = Fixture::new();
|
||||
f.aggregate();
|
||||
for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] {
|
||||
let ctx = egui::Context::default();
|
||||
render_repertoire_frame(&mut f, &ctx, width, height, 0.0, Vec::new());
|
||||
let buttons = f.ui.debug_layout.action_buttons.map(Option::unwrap);
|
||||
for button in buttons {
|
||||
assert_eq!(button.size(), buttons[0].size());
|
||||
assert_eq!(button.top(), buttons[0].top());
|
||||
assert_eq!(button.height(), 30.0);
|
||||
assert!(button.right() <= width);
|
||||
}
|
||||
assert!(buttons[0].right() < buttons[1].left());
|
||||
assert!(buttons[1].right() < buttons[2].left());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repertoire_row_menu_opens_editor() {
|
||||
let mut f = Fixture::new();
|
||||
let ctx = egui::Context::default();
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.0, Vec::new());
|
||||
let menu = text_click_position(&shapes, "⋯");
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.1, click_events(menu));
|
||||
let (_, shapes) = render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.2, Vec::new());
|
||||
let edit = text_click_position(&shapes, "Edit");
|
||||
render_repertoire_frame(&mut f, &ctx, 960.0, 600.0, 0.3, click_events(edit));
|
||||
assert_eq!(f.ui.editor_id.as_ref(), Some(&f.id));
|
||||
assert!(f.ui.editor.is_some());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,33 @@
|
|||
|
||||
use egui::{Color32, Sense, Stroke, Ui, vec2};
|
||||
|
||||
/// The application's settings action, shared by screen headers.
|
||||
pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response {
|
||||
let tr = crate::i18n::tr;
|
||||
ui.button(if compact { "⚙" } else { tr("⚙ Settings") })
|
||||
.on_hover_text(format!("{} (Ctrl+,)", tr("Settings")))
|
||||
}
|
||||
|
||||
/// A section header: reserve global actions before laying out a long title.
|
||||
/// Returns (back, settings).
|
||||
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;
|
||||
ui.horizontal(|ui| {
|
||||
ui.set_min_height(26.0);
|
||||
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::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(title).heading()).truncate())
|
||||
.on_hover_text(title);
|
||||
});
|
||||
});
|
||||
});
|
||||
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