From bd72aeacf8fbed101c411057c0f116ef2c7d354c Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Thu, 26 Nov 2026 16:38:16 +0300 Subject: [PATCH 01/31] docs: opening trainer v2 research, audit, concept and spec --- .../opening-trainer-concept-2026-11-26.md | 67 ++ .../opening-trainer-ui-audit-2026-11-26.md | 140 ++++ docs/design/opening-trainer-v2-spec.md | 470 +++++++++++++ .../opening-trainer-code-audit-2026-11-26.md | 617 ++++++++++++++++++ .../opening-trainer-rethink-2026-11-26.md | 537 +++++++++++++++ 5 files changed, 1831 insertions(+) create mode 100644 docs/design/opening-trainer-concept-2026-11-26.md create mode 100644 docs/design/opening-trainer-ui-audit-2026-11-26.md create mode 100644 docs/design/opening-trainer-v2-spec.md create mode 100644 docs/research/opening-trainer-code-audit-2026-11-26.md create mode 100644 docs/research/opening-trainer-rethink-2026-11-26.md diff --git a/docs/design/opening-trainer-concept-2026-11-26.md b/docs/design/opening-trainer-concept-2026-11-26.md new file mode 100644 index 0000000..dcfd6ab --- /dev/null +++ b/docs/design/opening-trainer-concept-2026-11-26.md @@ -0,0 +1,67 @@ +# Тренировка дебюта: новая концепция (2026-11-26) + +Статус: решение оркестратора по поручению владельца («проработай сам: проще, понятнее, +функционально; другие разделы не трогать»). Основания: `docs/research/opening-trainer-rethink-2026-11-26.md` +(аналитик), `docs/research/opening-trainer-code-audit-2026-11-26.md` (разработчик), +`docs/design/opening-trainer-ui-audit-2026-11-26.md` (дизайнер), руководство и форум ChessTempo +(корпус: `target/qa-opening-rethink/chesstempo-corpus/`). + +## Идея в одной фразе + +Репертуар — это PGN-дерево за один цвет; кнопка «Тренироваться» проводит по линиям от начала, +спрашивает только те свои ходы, которые пора повторить или которые новые, и заканчивает занятие +понятным итогом. Всё остальное — во втором плане или удалено. + +## Сценарий + +1. «Тренировка дебюта» → один экран: слева доска (геометрия экрана партии), справа таблица + репертуаров (стиль таблицы библиотеки) и карточка выбранного. +2. Пусто → текст и две кнопки: «Импорт PGN…», «Новый репертуар». Ещё путь — «Добавить в репертуар…» + из экрана партии (уже есть, не меняется). +3. Карточка: название · «Играю белыми/чёрными» · «Сегодня: N повторить · M новых» · + «Выучено X из Y ходов» с полосой · основная кнопка **Тренироваться**. +4. Занятие: программа проигрывает ходы соперника и уже уверенно известные свои ходы с анимацией, + останавливается на спрашиваемом ходе. Одна строка состояния сверху: что делать сейчас и «Осталось N». + - **Новый ход:** показан стрелкой и подписью «Новый ход — сыграйте его»; комментарий PGN виден. + - **Повторение:** «Ваш ход» без стрелки. + - **Верно:** короткое «Верно», комментарий к ходу, дальше. + - **Неверно:** фигура возвращается, «Правильно: Сb5» + стрелка, пользователь играет его; ход + вернётся в этом же занятии. + - «Подсказка» (H) — показать ход; засчитывается как показанный, а не как верный. +5. Конец: «Готово. Верно 14, ошибок 2. Следующее повторение — завтра» и кнопки «К репертуару» / + «Ещё 10 новых» (если есть). +6. Меню строки `⋯`: «Повторить всё подряд» (обзор перед турниром, линия за линией), «Просмотр + вариантов» (дерево ходов: выбрать ход → «Тренировать эту ветку», «Не тренировать»/«Тренировать»), + переименовать, сменить цвет, экспорт PGN, сброс прогресса (с подтверждением), удалить. + +## Уточнения по UI-аудиту дизайнера (приняты) + +- Состояние занятия («Новый ход», «Ваш ход», «Неверно…», «Осталось N») живёт в карточке правой + панели, как статус партии в игре с компьютером, а не строкой над доской. +- Цвет репертуара спрашивается при импорте/создании (сейчас чёрный PGN открывается как «Белые», `op-04`). +- Меню `⋯` действует только на свою строку; вёрстка таблицы в узкой панели проверяется на 960×600. + +## Решения по открытым вопросам + +| Вопрос | Решение | Почему | +| --- | --- | --- | +| Единица тренировки | Ход (SRS по `(FEN4, UCI)`), подача — линией от начала | ядро ChessTempo; линия даёт контекст, который владелец просил 02–03.11 | +| Единица прогресса | Ходы | честно отражает модель; варианты пересекаются | +| Порция новых | 10 за занятие, кнопка «Ещё 10 новых» | ясный конец занятия; без настройки | +| Режимы, порядки, 6 параметров контекста, окно параметров | Удалить из UI | главный источник прошлых отказов; типы в Settings остаются, чтобы не сбросить настройки | +| Дашборд, графики, вкладки, отчёт Branches/Lines, Uncertain/Resistant | Удалить из UI | заменяются тремя числами карточки; данные на диске не трогаются | +| Режим «за оба цвета» | Удалить из UI | у репертуара один цвет; старые «Both» открываются как белые/выбор цвета при первом запуске | +| Лимит глубины `max_plies` | Снимать при загрузке (как 03.11 сняли старые лимиты) | пользователь его не выбирал; PGN не меняется | +| Незавершённые сессии 2.x | Не возобновлять, начинать новое занятие | все ответы уже записаны; прогресс не теряется | +| Редактирование ходов на доске | Не в этом этапе | новая функция; добавление идёт через PGN и «Добавить в репертуар…» | +| Несколько своих ответов (2.3.0) | Сохранить | уже выпущено | +| Пометки PGN и временные стрелки | Сохранить | выпущено/в работе, полезно | + +## Границы + +- База — `main` (2.3.0), отдельный worktree. Рабочее дерево ветки `feature/opening-repertoire-training` + с незакоммиченными временными стрелками не трогается; при интеграции стрелки переносятся. +- Меняются только файлы раздела в `apps/desktop/src` и минимальные дополнения ядра + `crates/trainer/src/repertoire` (смешанная очередь «к повторению + N новых», возврат ошибки в том же + занятии). Формат файлов, Settings-типы, `app.rs`, библиотека, экран партии, доска, Android — без изменений. +- Мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) удаляется отдельной задачей после приёмки. diff --git a/docs/design/opening-trainer-ui-audit-2026-11-26.md b/docs/design/opening-trainer-ui-audit-2026-11-26.md new file mode 100644 index 0000000..fafba24 --- /dev/null +++ b/docs/design/opening-trainer-ui-audit-2026-11-26.md @@ -0,0 +1,140 @@ +# Тренировка дебюта: аудит интерфейса по реальным снимкам (2026-11-26) + +Статус: аудит дизайнера, **не макет**. Исходный код и другие документы не менялись. +Отчёты аналитика и разработчика (`docs/research/opening-trainer-*-2026-11-26.md`) не пересказываются. + +## 0. Как снималось и что не снято + +- Снимки: `target/qa-opening-rethink/shots/`, все 1400×900, тёмная тема, русский, масштаб 1. +- Версии: **[2.2.0+]** — рабочее дерево (`f425e3a` + незакоммиченные правки); **[2.3.0]** — `main` @ `ddc8361`, + worktree `/tmp/opencode/cp-main`, цель сборки `/tmp/opencode/cp-main-target`. + - [2.2.0+]: `ref-01…06`, `op-01…10`, `op-12`. + - [2.3.0]: `op-11`, `op-13`, `op-20…28`, `op-30…43`, `op-50`. +- Изоляция: отдельные `HOME`/`XDG_*` в `/tmp/opencode/qa/prof-*`; настоящие данные пользователя не изменялись. + Окно — вложенный Xwayland `:7`, ввод XTEST, старт состояний dev-хуками `CP_*`. Данные — два своих PGN с + вариантами, импортированные через интерфейс. +- **Не снято** (обрыв бюджета и ограничения стенда): 960×600; конец занятия; сброс прогресса; модальное + «Добавить в репертуар» из партии; автопоказ подводящих ходов; кадр «верно» сразу после ответа (стенд + задерживает события ввода — длительности пауз тоже не измерялись); HiDPI; светлая тема. + `op-28` (вкладка «Серии») снят, но не просмотрен. По этим состояниям выводов ниже нет. + +## 1. Подсчёты (по снимкам) + +| Что | Сколько | Снимки | +| --- | --- | --- | +| Экраны раздела | 4: рабочая область, задание, статистика, «редактор» | `op-06`, `op-30`, `op-22`, `op-50` | +| Вкладки статистики | 6 (4 видимых + 2 в меню «Дополнительно») + 2 селектора | `op-22…27` | +| Окна и вставные формы | модальное «Параметры» (8 элементов управления, 9 абзацев пояснений); вставные формы импорта, имени, удаления; меню строки (5 пунктов); список режимов (3) | `op-09`, `op-02`, `op-11`, `op-10`, `op-08`, `op-07` | +| Элементы управления на стартовом экране (2 репертуара) | 14: назад, настройки, цвет ×2, режим, 3 кнопки, 2 строки, 2 меню `…`, «Создать», «Импорт» + 3 строки счётчиков | `op-06` | +| Элементы управления в задании | 4: назад, настройки, «Подсказка», переворот | `op-30` | +| Шагов до первого хода | 2 клика, только если нужный репертуар первый по алфавиту и цвет угадан; иначе 4 (строка, цвет). С нуля: импорт → файл → «Добавить» → ожидание → цвет → «Тренироваться» = 5–6 | `op-01…06`, `op-30` | + +## 2. Главные проблемы + +1. **Задание не говорит, какой ход нужен.** Первый же вопрос по ни разу не виденному ходу: «Ваш ход: сыграйте + ход из репертуара» — без показа (`op-30`, 2.3.0). Подтверждает вывод разработчика «новый ход спрашивается + без предварительного показа». Наказание следует сразу: «Ошибка» (`op-31`). +2. **Тексты обратной связи — язык модели, не человека.** «Повторите показанный ход; это не будет + самостоятельным успехом» (`op-31`, причём ход в этот момент ещё не показан — стрелка появляется позже, + `op-33`), «Ход повторён после ошибки. Самостоятельный ответ не засчитан» (`op-34`), «Ответ с подсказкой + не считается самостоятельным» (`op-36`). Название правильного хода текстом не пишется нигде. +3. **Блок состояния меняет высоту и вид**: одна строка (`op-30`) → две строки с красной рамкой (`op-31`) → + две строки без рамки (`op-33`). Правая панель при этом на 85 % пустая: 700 px ниже блока не используются. +4. **Нет прогресса занятия.** «Заданий: 2 из 51» (`op-38`) — это счёт от всего репертуара; сколько осталось + сегодня и где конец, не видно. Под заголовком — служебное «По расписанию · Белые». +5. **Цвет не свойство репертуара.** Репертуар за чёрных после импорта открыт с «Цвет: Белые» и предлагает + учить ходы белых (`op-04`: 8 ходов; на 2.3.0 — 17, `op-11`). Пользователь обязан помнить и переключать. +6. **Скрытый лимит глубины подтверждён.** Оба импортированных репертуара получили `max_plies = 20` + (проверено в `repertoires.json` изолированного профиля); на экране это только бледная строка + «Тренировка: часть репертуара» (`op-06`), а само число видно лишь в «редакторе»: «Глубина 20 полуходов» + (`op-50`). +7. **«Редактор» («Изменить») не редактирует ходы** — подтверждено: плоский список одной главной линии без + вариантов, чекбокс глубины и «Аналитика хода» (`op-50`). Варианты, которые видны в библиотеке (4), здесь + не найти. +8. **Вставные формы вместо диалогов, список прыгает.** Импорт (`op-02`, `op-05`), имя (`op-11`, `op-13`), + удаление (`op-10`) вставляются над таблицей и сдвигают её на 22–88 px; положение формы зависит от того, + выбран ли репертуар (y=145 в `op-02`, y=323 в `op-05`). Эталоны для того же используют модальные окна. +9. **Действие строки не привязано к объекту.** Меню `…` строки white открывается при выбранном black + (`op-08`); вопрос «Удалить репертуар?» не называет имя (`op-10`); поле переименования white стоит над + списком при подсвеченном black (`op-11`). Риск удалить не то. +10. **Мигание при выборе и возврате.** На секунду и более счётчики превращаются в «Изучено … из … ходов», + три кнопки гаснут (`op-12`, `op-42`), затем кнопка меняет подпись на «Продолжить» (`op-43`). После + импорта форма остаётся на экране, пока строка крутит индикатор (`op-03`) — владелец просил без спиннеров. +11. **Строка таблицы — 158 px.** Пять строк ECO-названий на английском на репертуар; на экран входит 3–4 + репертуара (`op-06`). В библиотеке строка 27 px (`ref-01`). Имя берётся из имени файла («white»), а не + из `Event` PGN. +12. **Три режима и окно параметров на пути к запуску** (`op-07`, `op-09`): «По расписанию / Подряд / Сначала + новые и давние», «Верных ответов подряд», «Дней до срока повторения», «Пропуск знакомого начала … 100». + Окно при открытии дорастает на строку «Сбросить прогресс…» (наблюдалось на двух кадрах подряд; сохранён + только итоговый `op-09`). +13. **Статистика — отдельное приложение.** Пустые полноэкранные листы (`op-20`, `op-22`), повторный выбор + репертуара и стороны, термины «Элементы», «Введено в обучение», «Отсрочка до потери подтверждения», + «Надёжно изучено %», «Изучено = надёжно изучено + неподтверждено» (`op-22`, `op-24`, `op-25`). + «Ходы» — список SAN без номера и линии, с повторами «Bb3» (`op-25`); «Варианты» — список префиксов + «1. d4», «1. d4 1… d5», а не вариантов (`op-27`); «Динамика» показывает 0/51/0, когда в обзоре уже 2 к + повторению, ось «0–0», дата ISO (`op-23`). Две вкладки спрятаны в кнопку, похожую на вкладку (`op-26`). +14. **Счётчики расходятся по словам и смыслу.** «Не изучались: 47 · Пора повторить: 2» (`op-43`) против + «Ещё не изучали 47 / В процессе изучения 4 / Пора повторить 2» (`op-22`) после трёх сыгранных ходов; + в задании тот же объект назван «Заданий». +15. **Несогласованность с эталонами.** Доска прижата к левому краю (x=8…832, `op-06`), на экране партии она + по центру своей области (x=54…886, `ref-02`); шапка однострочная 30 px с «← Базы» против двухстрочной + 52 px с «⬅ Библиотека» (`ref-02`, `ref-04`); правая панель 560 px против 460 px; главная и второстепенные + кнопки одной высоты и ширины в ряд (`op-06`), в эталонах главная одна и справа внизу (`ref-03`, `ref-05`). + Доска стартового экрана ничего не показывает — выбор репертуара её не меняет (`op-04`, `op-06`). + +## 3. Паттерны эталонов для переиспользования + +Номера строк — по рабочему дереву [2.2.0+]; на `main` сверить. + +| Паттерн | Где видно | Код | +| --- | --- | --- | +| Шапка раздела: кнопка назад, разделитель, заголовок, «Настройки» справа | `ref-06`, `op-06` | `widgets.rs:14` `section_header`, `widgets.rs:6` `settings_button` | +| Шапка партии: две строки (заголовок + бледная подпись), бейдж справа от заголовка | `ref-02`, `ref-04` | `game_view.rs:952` `header` | +| Геометрия «доска + правая панель 460 px», доска по центру области | `ref-02`, `ref-04` | `game_view.rs:1217` `board_area`, `game_view.rs:1467` `side_panel` | +| Карточка состояния в правой панели (имя, подпись «ваш ход/ждёт», активная — с заливкой) | `ref-04` | `game_view.rs:3432` `clock_card` | +| Нижняя полоса значков 30×30 под панелью, действие («Прервать») отдельной строкой | `ref-02`, `ref-04` | `widgets.rs:127` `icon_button` | +| Главная кнопка: заливка цвета выделения, жирный текст, высота 30; одна на экран/диалог | `ref-03`, `ref-06` | `widgets.rs:112` `primary`, `widgets.rs:117` `primary_wide` (ширина не скачет при смене подписи) | +| Диалог: `egui::Modal`, заголовок, секции с жирным подзаголовком, бледные пояснения, «Отмена» + главная справа внизу | `ref-03`, `ref-05` | `play.rs:1256`, `prep_ui.rs:534`, `own_db.rs:143` | +| Подтверждение опасного действия — модальное, с именем объекта | — (по коду) | `own_db.rs:806`, `app.rs:2196` | +| Сегментный выбор из 2–3 значений плашками (Белые / Случайно / Чёрные) | `ref-03` | `play.rs:1256` и ниже (там же сетка контролей) | +| Таблица: строка 27 px, чередование фона, сортируемые заголовки, выделение заливкой | `ref-01`, `ref-06` | `large_db.rs:2106`, `prep_ui.rs:4052` (`TableBuilder`), `widgets.rs:64` `sort_header` | +| Пустое состояние: бледный текст по центру + одна главная кнопка | `ref-06` | `prep_ui.rs:4761` | +| Вкладки-плашки над содержимым панели | `ref-02`, `ref-06` | `game_view.rs:221` (`side_tab`), `prep_ui.rs:1703` | +| Строка-сводка бледным под заголовком («PGN, кодировка UTF-8 · 100 партий») | `ref-01` | `library.rs:1466` `header` | +| Типографика: заголовок `heading`, основной текст 14, пояснения `weak()`, предупреждение оранжевым | `ref-03`, `ref-06` | `docs/design/design-system.md` | + +## 4. Предварительные принципы нового раздела + +1. Два экрана: «репертуары» и «занятие». Статистика и «редактор» как отдельные экраны исчезают. +2. Занятие повторяет экран игры с компьютером: та же шапка, доска по центру, панель 460 px, карточка + состояния фиксированной высоты, полоса значков снизу. Ничего нового не изобретать. +3. Блок «что делать сейчас» — одного размера во всех состояниях; текст называет ход («Правильно: Сb5»), + цвет рамки не единственный признак ошибки. +4. Новый ход сначала показан (стрелка + подпись), потом спрашивается. +5. В занятии виден остаток («Осталось N»), а не доля всего репертуара. +6. Цвет задаётся один раз при создании или импорте и хранится в репертуаре; на пути к запуску — одна кнопка. +7. Все вопросы и формы (импорт, имя, удаление, сброс) — `egui::Modal` с именем объекта. Список никогда не + сдвигается. +8. Строка репертуара — одна, 27 px: имя, цвет, «повторить сегодня», «выучено X из Y». ECO-названия — в + карточке выбранного или в подсказке. +9. Одни и те же слова для одних и тех же чисел на всех экранах; ни одного из терминов п. 2.2 и 2.13. +10. Никаких переходных «…» и гаснущих кнопок: до готовности данных показывается прежнее значение. + +## 5. Замечания к концепции (`opening-trainer-concept-2026-11-26.md`) + +- **«Одна строка состояния сверху»** — на эталоне игры состояние живёт в карточке правой панели + (`ref-04`), а не над доской. Предлагаю карточку в панели; иначе доска занятия сместится относительно + экрана партии. +- **«Таблица в стиле библиотеки» + карточка выбранного** — в панели 460 px таблица библиотеки с 4 колонками + не поместится без обрезания; нужна проверка прототипом на 960×600 (панель там уже). Число колонок — не + больше трёх. +- **Меню `⋯` из семи пунктов** прячет две функции («Повторить всё подряд», «Просмотр вариантов»), а + остальные — служебные. Меню должно действовать на выбранную строку и только на неё (сейчас это нарушено, + `op-08`); «Просмотр вариантов» лучше дать видимой второстепенной кнопкой карточки. +- **«Сменить цвет» в меню** — нужен и момент первого выбора: импорт сейчас молча ставит «Белые» (`op-04`). + Определять по PGN или спрашивать в диалоге импорта. +- **Конец занятия: две кнопки** — главная одна («К репертуару» или «Ещё 10 новых» — решить), вторая обычная. +- **Доска на экране репертуаров** сейчас декоративна (`op-06`). Либо она показывает позицию выбранного + варианта, либо её стоит обосновать заново. +- **Снятие `max_plies` при загрузке** увеличит «Y» у существующих репертуаров — в карточке это не должно + выглядеть как потеря прогресса. diff --git a/docs/design/opening-trainer-v2-spec.md b/docs/design/opening-trainer-v2-spec.md new file mode 100644 index 0000000..c41177b --- /dev/null +++ b/docs/design/opening-trainer-v2-spec.md @@ -0,0 +1,470 @@ +# Тренировка дебюта v2: спецификация интерфейса (2026-11-26) + +Основание: `opening-trainer-concept-2026-11-26.md` (продуктовые решения не пересматриваются), +`opening-trainer-ui-audit-2026-11-26.md` (снимки `ref-*`, `op-*`). Номера строк — по этому worktree +(`feature/opening-trainer-v2`, 2.3.0). Тексты: EN — ключ `tr("…")`, RU — строка `i18n.rs`; остальные +четыре языка — по образцу. Размеры в pt при масштабе 1. + +Задача раздела одной фразой: **выбрать репертуар и одной кнопкой начать занятие, в котором в каждый момент +написано, что делать, и виден конец**. + +Три экрана: **Репертуары** (§2–3), **Занятие** (§4–6), **Варианты** (§6.3). Диалоги — §7. Других экранов, +окон и вкладок нет. + +## 1. Компоновка (общая для трёх экранов) + +Все три экрана используют один каркас. Переход между ними не меняет ни прямоугольник доски, ни ширину панели. + +| Область | 1400×900 | 960×600 | Как сделать | +| --- | --- | --- | --- | +| Шапка | высота 52 (y 0…52) | 52 | Две строки, как у партии (`ref-02`, `ref-04`): строка 1 — кнопка «назад», разделитель, заголовок `heading` с обрезкой, справа `settings_button`; строка 2 — бледная подпись с обрезкой. `GameView::header` (`game_view.rs:952`) закрыт и связан с партией, поэтому: **новая** функция `widgets::section_header_sub(ui, back, title, subtitle) -> (bool, bool)` рядом с `section_header` (`widgets.rs:14`), повторяющая отступы `game_view.rs:958` (`add_space(4)`) и строку подписи `game_view.rs:1151`. Существующие функции не менять. | +| Правая панель | ширина 460 (x 940…1400) | 384 | `egui::Panel::right("opening_side")`, один id на все три экрана. Формула партии, `game_view.rs:788–800`: `default_size((width*0.4).clamp(260.0, 460.0).min(room))`, `room = (width - board - 24).clamp(least, most)`, `resizable(true)`, `size_range(least..=most)`, `least = 320` (как `REF_MIN`, `game_view.rs:5001`), `most = (width - 220 - 24).max(least)`. После — `widgets::check_panel` (`widgets.rs:36`). | +| Доска | квадрат 832, x 54…886, y 60…892 | квадрат 532, x 22…554, y 60…592 | `CentralPanel`; квадрат по центру области, формула `game_view.rs:1250–1253`. Виджет `BoardView::show` (`board.rs:169`, `:194`) с настройками доски пользователя. Полосы оценки нет. | +| Узкое/высокое окно | — | — | Правило партии `game_view.rs:761–763`: если `board_stack >= 1.25 * board_side` — доска сверху, панель снизу высотой ≥ 300 (`STACK_BOTTOM_MIN`). Текущее собственное правило `learning_training.rs:1530` (`width < 900 && height > width`) удалить. | + +Внутренние поля панели: стандартные egui (как у партии), между блоками 6. Никаких новых цветов, рамок и +шрифтов: заливка выделения — `visuals.selection.bg_fill`, рамки — `widgets.noninteractive.bg_stroke`, +ошибка — `visuals.error_fg_color`, предупреждение — `visuals.warn_fg_color`. + +Общие компоненты: + +| Нужно | Брать | +| --- | --- | +| Главная кнопка (одна на экран/диалог) | `widgets::primary_wide` (`widgets.rs:117`), высота 30, фиксированная ширина | +| Обычная кнопка | `ui.button`, в ряду с главной — `min_size(vec2(0, 30))` | +| Значки нижней полосы 28 pt | замыкание `icon` из `play_toolbar` (`game_view.rs:3563–3564`), переворот — `game_view.rs:3582` | +| Карточка состояния | рамка `clock_card` (`game_view.rs:3451–3463`): `inner_margin(10, 6)`, радиус 4, обводка 1; активная — заливка `sel.bg_fill.gamma_multiply(0.35)`; ошибка — обводка 1.5 `error_fg_color` | +| Плашки выбора из двух значений | замыкание `choice` (`play.rs:1283–1289`): `Button::selectable(..).frame_when_inactive(true)` | +| Заголовок секции диалога | `play.rs:1280` (`strong().size(15.0)`) | +| Диалог | `egui::Modal`, `ui.set_width(460.0)`, `ui.heading`, как `game_view.rs:3261–3263`; вопрос с опасным действием — как `app.rs:2196`, `own_db.rs:806` | +| Таблица | `TableBuilder`, настройки `large_db.rs:2106–2111`, заголовок 26 (`:2146`), строка 24 (`:2160`) | +| Пустое состояние | `prep_ui.rs:4760` (бледный текст по центру + одна `primary`) | +| Дерево ходов | `Notation` (`notation.rs:13`, `show` — `:189`) с `read_only: true` | + +## 2. Экран «Репертуары»: таблица + +Шапка: назад «⬅ Library / ⬅ Библиотека»; заголовок «Opening training / Тренировка дебюта» (пометку +«(α version)» сохранить до решения владельца — одна строка `repertoire_ui.rs:1035`); подпись +«{n} repertoires / Репертуаров: {n}», при пустом списке подписи нет. + +Панель сверху вниз: карточка выбранного (§3, фиксированная высота 166) · поле поиска (только если +репертуаров > 8, высота 24, подсказка «Search / Поиск») · таблица (всё оставшееся, прокрутка) · полоса +сообщения (высота 20, всегда зарезервирована, §7.6) · нижний ряд (высота 30): «Import PGN… / Импорт PGN…», +«New repertoire / Новый репертуар» — обычные кнопки одинаковой ширины 150. + +Колонки (ширина панели 384 → на название остаётся ≥ 150): + +| Колонка | Ширина | Содержимое | +| --- | --- | --- | +| «Name / Название» | остаток, обрезка «…», полный текст в подсказке | имя репертуара | +| (без заголовка) | 22 | король цвета: ♔ / ♚; подсказка «You play White / Вы играете белыми» (… Black / чёрными) | +| «Today / Сегодня» | 58, вправо | `повторить + новые` одним числом; 0 → «—» бледно. Подсказка: «{n} to review, {m} new / Повторить: {n}, новых: {m}» | +| «Learned / Выучено» | 70, вправо | «34/120»; пустой репертуар → «—» | +| (без заголовка) | 26 | кнопка `⋯` | + +- Строка 24, чередование фона, выделение — заливка выделения на всю строку (как библиотека, `ref-01`). + Порядок — по имени, без сортировки по клику. +- Клик — выбрать (карточка и доска обновляются). Двойной клик или Enter — то же, что главная кнопка карточки. + ↑/↓ — соседняя строка, выбранная строка прокручивается в видимую область. +- Пока строка считается в фоне, в «Сегодня» и «Выучено» — прежние значения; если их ещё не было — «…». + Индикаторов вращения нет. +- Доска экрана: позиция **после общего начала репертуара** (последний ход до первого разветвления), с + подсветкой последнего хода, перевёрнута для чёрных; ввода нет. Пустой репертуар и пустой список — + начальная позиция. + +Меню `⋯` (также правый клик по строке). Открытие меню **выбирает эту строку**; все пункты действуют на неё. + +| № | EN | RU | Примечание | +| --- | --- | --- | --- | +| 1 | Train | Тренироваться | = главная кнопка; недоступно, если ходов нет | +| 2 | Review all lines | Повторить всё подряд | §6.1 | +| 3 | Lines… | Варианты… | §6.3 | +| — | | | разделитель | +| 4 | Rename… | Переименовать… | §7.3 | +| 5 | Play as Black / Play as White | Играть чёрными / Играть белыми | показан противоположный текущему; §7.4 | +| 6 | Add PGN to this repertoire… | Добавить PGN в этот репертуар… | §7.1 | +| 7 | Export PGN… | Экспорт PGN… | системный диалог, как сейчас (`repertoire_ui.rs:799`) | +| — | | | разделитель | +| 8 | Reset progress… | Сбросить прогресс… | §7.5 | +| 9 | Delete… | Удалить… | §7.5 | + +Пустой список: карточки и таблицы нет; по центру панели (вертикально тоже) — +заголовок «No repertoires yet / Репертуаров пока нет», бледный текст «A repertoire is your opening moves as a +PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…”. / +Репертуар — это ваши дебютные ходы в PGN с вариантами. Импортируйте файл или откройте любую партию, +выберите ход и нажмите «Добавить в репертуар…».», под ним `primary` «Import PGN… / Импорт PGN…» и обычная +«New repertoire / Новый репертуар». Нижний ряд в этом состоянии скрыт (кнопки не дублируются). + +## 3. Карточка выбранного репертуара + +Рамка как у `clock_card` без заливки, высота 166 во всех состояниях (строки не появляются и не исчезают — +пустая строка остаётся пустой). + +| Строка | Высота | Содержимое | +| --- | --- | --- | +| 1 | 26 | имя (`heading`, обрезка) · справа бледно «♔ You play White / ♔ Вы играете белыми» (♚ … Black / чёрными) | +| 2 | 22 | **сегодня** (strong 15), тексты ниже | +| 3 | 8 + 20 | полоса прогресса высотой 8 во всю ширину: сегмент «выучено» — цвет выделения, сегмент «учится» — тот же цвет с `gamma_multiply(0.45)`, остаток — фон поля; под ней «Learned {x} of {y} moves / Выучено {x} из {y} ходов», справа бледно «{k} in progress / учится: {k}» (скрыто при k = 0) | +| 4 | 20 | бледная строка пояснения (тексты ниже) | +| 5 | 30 | главная кнопка (ширина 170) · «Lines / Варианты» (ширина 110) · место третьей кнопки (ширина 150) | + +Определения чисел (из ядра, без новых понятий): `y` — свои ходы репертуара за его цвет; `x` — ходы со +статусом ядра «изучено»; `k` — ходы, которые уже спрашивали, но ещё не «изучено»; «повторить» — ходы со +сроком сегодня или раньше; «новых» — `min(10, ещё не показанные)`. + +Состояния (строка 2 · строка 4 · кнопки): + +| Состояние | Строка 2 (EN / RU) | Строка 4 (EN / RU) | Главная | Третья кнопка | +| --- | --- | --- | --- | --- | +| Есть повторения (и, возможно, новые) | «Today: {n} to review · {m} new» / «Сегодня: {n} повторить · {m} новых» (часть с нулём опускается) | «About {t} min» / «Примерно {t} мин» (20 с на ход, округление вверх; < 1 мин не показывать) | **Train / Тренироваться** | — | +| Повторять нечего, есть новые | «Today: {m} new moves» / «Сегодня: {m} новых ходов» | «Nothing to review today» / «Повторять сегодня нечего» | **Learn {m} new / Учить {m} новых** | «Review all lines / Повторить всё подряд» | +| Всё показано, до повторения есть время | «Done for today» / «На сегодня всё» | «Next review: {when} · {n} moves» / «Следующее повторение: {when} · ходов: {n}» | **Review all lines / Повторить всё подряд** | — | +| Всё выучено и повторений в расписании нет (теоретически) | «Done for today» / «На сегодня всё» | пусто | **Review all lines / Повторить всё подряд** | — | +| Репертуар пустой | «No moves yet» / «Ходов пока нет» | «Add a PGN, or use “Add to repertoire…” in any game» / «Добавьте PGN или нажмите «Добавить в репертуар…» в любой партии» | **Add PGN… / Добавить PGN…** | — | +| В репертуаре нет ходов за выбранный цвет | «No moves for White here» / «Здесь нет ходов за белых» (… Black / чёрных) | «This PGN may be a repertoire for the other colour» / «Возможно, это репертуар за другой цвет» | **Play as Black / Играть чёрными** (или белыми) | — | +| Индексация в фоне, прежние числа есть | прежние значения | прежняя строка | прежняя, доступна | прежняя | +| Индексация в фоне, чисел ещё не было | «Counting moves…» / «Считаем ходы…» | пусто | **Train / Тренироваться**, недоступна, подсказка «Counting moves… / Считаем ходы…» | — | +| Ошибка чтения репертуара | «Cannot read this repertoire» / «Не удалось прочитать репертуар» (цвет предупреждения) | текст ошибки с обрезкой, полный в подсказке | **Try again / Повторить** | — | + +`{when}`: «today at 18:40 / сегодня в 18:40», «tomorrow / завтра», «in {d} days / через {d} дн.», далее дата +в формате библиотеки (`ДД.ММ.ГГГГ`). + +Тупиков нет: в любом состоянии главная кнопка что-то делает; «Повторить всё подряд» всегда есть в меню `⋯`. +Кнопка «Варианты» недоступна только у пустого репертуара. Подпись главной кнопки меняется только при смене +состояния данных; ширина фиксирована. + +## 4. Экран «Занятие» + +### 4.1. Шапка и панель + +Шапка: назад «⬅ Repertoires / ⬅ Репертуары» (при ширине < 600 — «⬅»); заголовок — имя репертуара; подпись — +вид занятия: «Training · you play White / Тренировка · вы играете белыми» (см. §6 для других видов). + +Панель сверху вниз, **все высоты постоянны**: + +| Блок | Высота | Содержимое | +| --- | --- | --- | +| A. Карточка состояния | 64 | слева две строки: заголовок (strong 15) и указание (обычный 13, обрезка; полный текст в подсказке); справа счётчик: число моноширинным 24 и под ним бледная подпись 11. Рамка и заливка по §1 | +| B. Дебют | 20 | бледно, обрезка: «C84 · Ruy Lopez: Closed» — код и название текущей позиции из той же базы названий, что сейчас в библиотеке (`repertoire_ui.rs:1297`); если позиция вне базы — последнее известное название; до первого хода пусто | +| C. Путь | 20 | бледно, одна строка, обрезка **слева** («… 4. Ba4 Nf6 5. O-O Be7»): ходы до текущей позиции в нотации приложения (`san::show`). Спрашиваемый ход в строку не входит, пока не сыгран. Клики не обрабатываются | +| D. Комментарий | остаток, прокрутка внутри | заголовок-ход (strong): номер, ход, значок NAG цветом `notation::assessment_text_color` (`notation.rs:709`); ниже текст комментария PGN (`notation::comment_text`, `notation.rs:748`). Правила — §4.4. Пусто — пустая область, без «нет комментария» | +| E. Действия | 30 | слева обычная «Hint (H) / Подсказка (H)» шириной 150; справа место главной кнопки шириной 170 (обычно пусто) | +| F. Полоса | 28 + разделитель | значок переворота с подсказкой «Flip board (F) / Перевернуть доску (F)»; справа «× Finish / × Закончить» (как «× Прервать», `ref-04`) | + +Доска: стрелки и кружки PGN, значок-бейдж хода — как в 2.3.0 (`learning_training.rs:1206–1265`), временные +стрелки пользователя сохраняются. Стрелка-подсказка — существующая зелёная (`op-33`, `op-36`). + +### 4.2. Машина состояний + +Счётчик в обычном занятии: число = сколько вопросов осталось в этом занятии (включая возвращённые ошибки), +подпись «left / осталось». Число уменьшается только после верного самостоятельного ответа или сыгранного +нового хода; при ошибке не меняется (ход вернётся). + +| Состояние | Когда | Заголовок EN / RU | Указание EN / RU | Рамка | Доска, кнопки | +| --- | --- | --- | --- | --- | --- | +| S0 Подготовка | до первого кадра занятия, только если дольше 300 мс | Preparing… / Готовим занятие… | — | обычная | ввод закрыт; счётчик «—» | +| S1 Подвод | программа проигрывает ходы до вопроса (ходы соперника и уверенно известные свои) | Watch / Смотрите | Moves up to your next question / Ходы до вашего следующего вопроса | обычная | ввод закрыт; «Подсказка» недоступна; главная справа: «Skip (Enter) / Пропустить (Enter)» — обычная кнопка, сразу ставит позицию вопроса | +| S2 Новый ход | ход ни разу не показывали | New move / Новый ход | Play {san} — it is shown by the arrow / Сыграйте {san} — он показан стрелкой | активная заливка | стрелка сразу; комментарий хода виден (§4.4); «Подсказка» недоступна | +| S3 Ваш ход | повторение | Your move / Ваш ход | Play the move from your repertoire / Сыграйте ход из репертуара | активная заливка | стрелки нет; «Подсказка» доступна | +| S3a Ваш ход, ответов несколько | в позиции несколько своих ходов (2.3.0) | Your move / Ваш ход | Play {san}'s alternative: one more move here / Здесь есть ещё один ваш ход, не {san} | активная заливка | показывается, когда спрашивается не первый из ответов; уже сыгранные перечисляются через запятую | +| S4 Верно | верный самостоятельный ответ | Correct / Верно | {n}. {san} | обычная, заголовок цветом оценки «хороший ход» (`notation::assessment_text_color` для `!`) | 600 мс после анимации, затем S1/S2/S3 следующего вопроса или S8; ввод закрыт | +| S5 Неверно | сыгран не тот ход | Not this move / Не тот ход | Correct: {san}. Play it / Правильно: {san}. Сыграйте его | обводка 1.5 `error_fg_color` | фигура возвращается (существующая анимация), сразу стрелка верного хода; ждём ход пользователя; «Подсказка» недоступна. Другой неверный ход — состояние остаётся, фигура возвращается | +| S5a Ход есть в репертуаре, но спрашивается другой | сыгран другой свой ход этой позиции | This one is in your repertoire too / Этот ход тоже есть в репертуаре | Now the other one: play {san} / Сейчас нужен другой: сыграйте {san} | обычная | ошибкой **не считается**; стрелка на нужный ход | +| S6 После показа | сыгран ход, показанный в S5 или S7 | Got it / Запомним | {n}. {san} will come back in this session / {n}. {san} вернётся в этом занятии | обычная | 600 мс, далее следующий вопрос | +| S7 Подсказка | нажата «Подсказка» в S3 | Hint / Подсказка | Play {san}. It will come back in this session / Сыграйте {san}. Ход вернётся в этом занятии | обычная | стрелка; после хода — S6 | +| S9 Ошибка записи | ответ не сохранился | Could not save your answer / Не удалось сохранить ответ | текст ошибки, обрезка, полный в подсказке | обводка 1.5 `error_fg_color` | ввод закрыт; в E: главная «Try again / Повторить», слева вместо «Подсказки» — «Finish / Закончить» | +| S8 Итог | вопросы кончились | §5 | | | | + +Обычное сохранение ответа не показывается никак (решение 05.11). Доска после отпускания фигуры сразу +показывает сыгранный ход (поведение 2.2.0 сохраняется). + +Все `{san}` — в нотации приложения (буквы фигур по настройке языка), с номером хода там, где указано `{n}.`. + +### 4.3. Клавиши и выход + +| Клавиша | Действие | Сверка | +| --- | --- | --- | +| H | подсказка (S3) | как сейчас, `learning_training.rs:1136` | +| F | перевернуть доску | как в партии и игре, `game_view.rs:3583` | +| Enter, Space | S1 — пропустить подвод; S8 — «К репертуару»; S9 — «Повторить» | Enter на итоге уже есть, `learning_training.rs:1142` | +| N | S8 — «Ещё 10 новых» | новая, только на итоге | +| Esc, Ctrl+W | закончить занятие и вернуться к репертуарам | как сейчас, `:1130–1131`; Ctrl+W — «в библиотеку» у партии | +| Ctrl+, | общие настройки, занятие не сбрасывается | решение 05.11 | + +Клавиши не действуют, пока открыт модальный диалог или поле ввода (правило `game_view.rs:4776–4783`). +Удаляются: Space/P — пауза автопоказа, Esc — отмена автопоказа (`:1124–1128`), L и Shift+A (`:1138–1139`). + +Выход посреди занятия (Esc, Ctrl+W, «⬅ Репертуары», «× Закончить»): **без вопроса**, сразу на экран +«Репертуары» — каждый ответ уже записан, терять нечего; текущий неотвеченный вопрос не засчитывается. +Если запись в процессе — выход после её завершения (как сейчас, Esc ждёт `!board.is_busy()`). Если +отвечен хотя бы один вопрос, вместо мгновенного выхода показывается итог §5 с заголовком «Session stopped / +Занятие прервано» — человек видит, что сделанное сохранено. Незаконченное занятие не возобновляется +(концепция): кнопка карточки начинает новое. + +### 4.4. Комментарии и значки PGN + +- Значок NAG хода (`!`, `?`, `!?` …) пишется рядом с ходом в блоке D и в указании S4/S6; бейдж на доске — как + в 2.3.0. +- В блоке D всегда комментарий **последнего хода на доске**; у хода соперника — его комментарий (он + объясняет позицию вопроса). +- Комментарий **спрашиваемого** хода в S3 не показывается (он подсказывает ответ). Он появляется в S2 + (сразу), в S5 и S7 (вместе со стрелкой), в S4/S6 (после хода) и остаётся до следующего комментария, с + заголовком-ходом, чтобы было видно, к чему он относится. +- Комментарий перед первым ходом партии PGN показывается в начале подвода. +- Перевод комментариев и их редактирование — нет (не этот этап). + +## 5. Итог занятия (S8) + +Доска остаётся на последней позиции, ввода нет. Панель: блоки A–C и F на местах и тех же высот; блок D +занят итогом; блок E — кнопки. + +- A: заголовок «Session complete / Занятие окончено» (при досрочном выходе — «Session stopped / Занятие + прервано»), указание «Everything is saved / Всё сохранено»; счётчик «0», при досрочном — остаток. +- D, строки по 22, подпись слева, число справа (колонка 60): + - «Correct first time / Верно с первого раза» — {a} + - «Mistakes / Ошибок» — {b} + - «Hints / Подсказок» — {h} (строка скрыта при 0) + - «New moves learned / Новых ходов» — {m} (скрыта при 0) + - разделитель + - «Next review / Следующее повторение» — {when} (§3); если что-то осталось на сегодня — «today, {n} more / + сегодня, ещё {n}» + - если были ошибки — подзаголовок «Moves to remember / Что запомнить» и до 8 строк «{n}. {san}» с путём + бледно («после 2… Nc6»: «after {path} / после {path}»); больше 8 — «and {k} more / и ещё {k}». +- E: главная справа — **«To repertoires (Enter) / К репертуарам (Enter)»**; слева обычная «10 more new (N) / + Ещё 10 новых (N)» (число — сколько реально осталось, максимум 10; скрыта, если новых нет или вид занятия — + §6). + +## 6. Другие виды занятия и экран «Варианты» + +### 6.1. «Повторить всё подряд» + +Тот же экран и те же состояния. Отличия: + +- подпись шапки: «Review all lines · you play White / Повторение подряд · вы играете белыми»; +- счётчик карточки A: число «{k}/{n}», подпись «line / вариант»; `n` — число вариантов (листьев дерева с + учётом выключенных веток), `k` — текущий; +- спрашивается **каждый** свой ход варианта, уверенно известные не пропускаются; ход, которого ещё не + показывали, идёт как S2; +- между вариантами S1 с заголовком «Next line / Следующий вариант» и указанием «{k} of {n} / {k} из {n}»; + общее начало с предыдущим вариантом не проигрывается заново (поведение 05.11 сохраняется); +- ошибочный ход повторяется сразу (S5→S6) и в этом занятии не возвращается; +- ответы записываются в расписание, как в обычном занятии; +- итог: первая строка «Lines reviewed / Пройдено вариантов» — {k} из {n}; кнопки «Ещё 10 новых» нет. + +### 6.2. «Тренировать эту ветку» + +Как §6.1, но только варианты, проходящие через выбранный ход. Подпись шапки: +«Branch: {path} / Ветка: {path}» (путь с обрезкой слева). Назад и «× Закончить» возвращают на экран +«Варианты» с тем же выбранным ходом; Enter на итоге — туда же («To lines / К вариантам»). + +### 6.3. Экран «Варианты» + +Задача: посмотреть, что в репертуаре, и выбрать, что тренировать. Ходы не редактируются. + +Шапка: назад «⬅ Repertoires / ⬅ Репертуары»; заголовок — имя; подпись «Lines · {n} lines · {y} your moves / +Варианты · вариантов: {n} · ваших ходов: {y}». + +Панель: + +| Блок | Высота | Содержимое | +| --- | --- | --- | +| Дебют | 20 | как блок B занятия, для выбранной позиции | +| Дерево | остаток, прокрутка | `Notation { game: &дерево репертуара, cursor: выбранный ход, scroll_to_cursor: true при смене хода с клавиатуры, read_only: true, marks/preview/translations/editor/dim_until/mistakes: None }` (`notation.rs:13–33`). Клик — `NotationResponse::clicked` (`:37`). Комментарии и NAG рисует сам компонент | +| Выбранный ход | 92 | рамка как у карточки; строка 1 — путь до хода (strong, обрезка слева); строка 2 бледно — «Below: {n} lines · {y} your moves · learned {x} / Дальше: вариантов {n} · ваших ходов {y} · выучено {x}»; у выключенной ветки строка 2 — «Not trained / Не тренируется» цветом предупреждения; строка 3 — кнопки: главная «Train this branch / Тренировать эту ветку» (170), обычная «Don't train / Не тренировать» ↔ «Train again / Снова тренировать» (170) | +| Полоса | 28 | `⏮ ◀ ▶ ⏭` и переворот — как `play_toolbar` (`game_view.rs:3567–3583`) | + +- Доска: позиция выбранного хода, подсветка последнего хода, стрелки/кружки PGN; перевёрнута для чёрных; + ввода нет. +- Ничего не выбрано (начало): строка 1 — «Start position / Начальная позиция», главная — + «Review all lines / Повторить всё подряд», вторая кнопка скрыта. +- «Не тренировать» выключает ветку от выбранного хода (существующие `disabled_prefixes`), действует сразу, + отменяется той же кнопкой; числа карточки пересчитываются в фоне. У хода соперника и у своего хода + действует одинаково. +- Клавиши как у партии: ←/→ ход, ↑/↓ соседний вариант, Home/End, F — переворот, Enter — главная кнопка, + Esc/Ctrl+W — назад. +- **Отметка выключенных веток в дереве.** `Notation` не умеет приглушать поддерево (`dim_until` — только + главная линия по номеру полухода). Нужна аддитивная правка `notation.rs`: поле + `muted: Option<&HashSet>` по образцу `mistakes` (`:32`) — ходы из множества рисуются `weak` и + зачёркнутыми. Это выход за границу «только файлы раздела»; до согласования оркестратора — без отметки в + дереве, состояние видно только в блоке выбранного хода. + +## 7. Диалоги + +Все — `egui::Modal`, ширина 460, `heading`, кнопки справа внизу: «Cancel / Отмена», затем главная. Enter — +главная (кроме опасных, где Enter = «Отмена»), Esc — отмена. Таблица под диалогом не сдвигается. + +### 7.1. Импорт PGN + +Сначала системный выбор файла (`rfd`, как `repertoire_ui.rs:753`), затем диалог «Import PGN / Импорт PGN»: + +- «Name / Название» — поле (до 120 знаков); по умолчанию — тег `Event` первой партии, если он не пустой и не + «?», иначе имя файла без расширения. +- «You play / Вы играете» — две плашки `choice` шириной 222, высотой 34: «♔ White / ♔ Белыми», «♚ Black / + ♚ Чёрными». Предвыбор: цвет, у которого в дереве меньше позиций с несколькими ходами (свои ходы обычно + единственные); при равенстве — белые. Под плашками бледно: «Chosen from the PGN — check it / Выбрано по + PGN — проверьте». +- Сводка бледно: «{g} games · {v} lines · {y} your moves / Партий: {g} · вариантов: {v} · ваших ходов: {y}» + — `y` пересчитывается при смене цвета. +- Предупреждения (цвет предупреждения, до 3 строк, остальное — «and {k} more / и ещё {k}»): нераспознанные + ходы, партии без ходов. +- Кнопки: «Cancel / Отмена», главная «Import / Импортировать» (недоступна при пустом имени или `y = 0`; + подсказка «No moves for this colour / Нет ходов за этот цвет»). +- Пока файл читается: вместо сводки «Reading the file… / Читаем файл…», главная недоступна. +- После импорта диалог закрывается, новый репертуар выбран. + +«Добавить PGN в этот репертуар…»: заголовок «Add PGN to “{name}” / Добавить PGN в «{name}»», без полей имени +и цвета; сводка «{m} new moves · {v} new lines / Новых ходов: {m} · новых вариантов: {v}»; при `m = 0` — +«Nothing new in this file / В файле нет новых ходов», главная недоступна. Главная — «Add / Добавить». + +Окно «Добавить в репертуар…» из партии (`repertoire_ui.rs:1987`) остаётся как есть; при создании нового +репертуара в нём добавляются те же плашки цвета (предвыбор — сторона, чей ход выбран в партии). + +### 7.2. Новый репертуар + +«New repertoire / Новый репертуар»: поле названия, плашки цвета (предвыбор — белые), бледно: «Moves are added +from a PGN file or with “Add to repertoire…” in any game. / Ходы добавляются из PGN-файла или кнопкой +«Добавить в репертуар…» в любой партии.» Главная — «Create / Создать». Ошибка имени (пустое, занято) — +строка цветом предупреждения под полем, место под неё зарезервировано. + +### 7.3. Переименование + +«Rename repertoire / Переименовать репертуар»: поле с текущим именем, выделенным целиком; главная — +«Save / Сохранить»; та же строка ошибки. + +### 7.4. Смена цвета + +«Play “{name}” as Black? / Играть «{name}» чёрными?» (или белыми). Текст: «You will be asked Black's moves: +{y}. Progress for White is kept and comes back if you switch again. / Спрашиваться будут ходы чёрных: {y}. +Прогресс за белых сохранится и вернётся, если переключить обратно.» Главная — «Switch / Переключить». + +### 7.5. Сброс прогресса и удаление + +Опасные: главной (залитой) кнопки нет, обе кнопки обычные, фокус и Enter — на «Отмена» (образец +`app.rs:2196`). + +**Сброс.** Заголовок: «Reset progress of “{name}”? / Сбросить прогресс «{name}»?» + +- «All {y} moves of this repertoire become new again: answers and review dates are erased. / Все ходы этого + репертуара ({y}) снова станут новыми: ответы и сроки повторений будут стёрты.» +- «The moves themselves and PGN files do not change. / Сами ходы и PGN-файлы не меняются.» +- Если есть общие позиции (существующий расчёт `impact`, `repertoire_ui.rs:1906–1940`), цветом + предупреждения: «{s} of these moves are also in: {names}. They become new there too. / Из них {s} + встречаются также в: {names}. Там они тоже станут новыми.» +- Кнопки: «Cancel / Отмена», «Reset / Сбросить». Флажок «I understand…» (`:1950`) убрать — его заменяет + точный текст. + +**Удаление.** Заголовок: «Delete “{name}”? / Удалить «{name}»?» + +- «The repertoire leaves this list. PGN files on disk do not change. / Репертуар исчезнет из списка. + PGN-файлы на диске не меняются.» +- «Your answers are kept: import the same PGN again and the progress returns. / Ответы сохранятся: если + импортировать тот же PGN снова, прогресс вернётся.» (сверить с ядром; если прогресс не возвращается — + разработчик сообщает, текст меняется на «Progress of its moves is erased / Прогресс по его ходам будет + стёрт».) +- Кнопки: «Cancel / Отмена», «Delete / Удалить». После удаления выбирается соседняя строка. + +### 7.6. Сообщения и ошибки + +Полоса сообщения над нижним рядом экрана «Репертуары» (20, всегда зарезервирована): одна строка с обрезкой, +полный текст в подсказке, справа `small_close_button` (`widgets.rs:74`). Ошибка — цвет предупреждения +(«Could not save: {e} / Не удалось сохранить: {e}»), успех экспорта — обычный бледный («Saved to {path} / +Сохранено: {path}»), исчезает через 6 с. Сообщение никогда не сдвигает таблицу. + +## 8. Что удаляется из интерфейса + +| Что | Где сейчас | +| --- | --- | +| Экран «Статистика обучения» целиком: вкладки Обзор, Динамика, Расписание, Ходы, меню «Дополнительно» (Варианты, Серии), селекторы репертуара и стороны, «Показатели обучения» | `learning_dashboard.rs`, `learning_charts.rs`, `learning_branches.rs`; вход `repertoire_ui.rs:1007`; хук `CP_LEARNING_DASHBOARD_TAB` | +| Окно «Параметры тренировки» и кнопка «Параметры» | `repertoire_ui.rs:1669`, `learning_context_controls.rs` | +| Экран «Изменить» («редактор»): список главной линии, «Без ограничения глубины», «Глубина … полуходов», «Аналитика хода», «Отмена/Сохранить» в шапке | `repertoire_editor.rs`; вход `repertoire_ui.rs:992`. Заменён экраном «Варианты» | +| Переключатель «Цвет» и список «Режим» (По расписанию / Подряд / Сначала новые и давние) в карточке | `repertoire_ui.rs:1515` (`workspace_panel`) | +| Строки «Не изучались… · Пора повторить…», «Тренировка: часть репертуара» | `repertoire_ui.rs:1591` и рядом | +| Кнопки «Статистика», «Продолжить» (возобновление) | `workspace_panel` | +| Вставные формы: имя (`name_editor`), импорт (`import_preview`), удаление, сброс (`shared_reset_panel`) | `repertoire_ui.rs:1403`, `:1448`, `:1172–1195`, `:1906` | +| Строка таблицы высотой 156 с пятью названиями ECO, колонки «ECO» и «Варианты», индикатор вращения в строке | `repertoire_ui.rs:1136` (`show_library`), `:1297–1331` | +| Пункт меню «Изменить» | `repertoire_ui.rs:1350` | +| В занятии: «Заданий: k из n», строка «По расписанию · Белые», блок сообщений переменной высоты, тексты «…не будет самостоятельным успехом», «Самостоятельный ответ не засчитан», «…не считается самостоятельным» | `learning_training.rs` (`side`, тексты состояния) | +| В занятии: пауза/отмена автопоказа (Space, P, Esc), L, Shift+A; кнопки управления показом | `learning_training.rs:1124–1139` | +| Собственная раскладка «доска сверху» по правилу `width < 900 && height > width`; id панели `repertoire_workspace_side`; ширина панели 420–560 | `learning_training.rs:1530–1554`, `repertoire_ui.rs:1507`, `repertoire_editor.rs:100` | +| Режим «за оба цвета», лимит глубины в любом виде | по концепции | + +Строки `i18n.rs`, которые после этого нигде не используются, удалить (тест `all_used_keys_are_translated` +ловит обратное, не это — проверить поиском). + +## 9. Визуальная приёмка + +Ревьюер — не автор кода; изолированный профиль; снимки 1400×900 и 960×600, тёмная тема, русский язык; +дополнительно три ключевых кадра (репертуары, S3, итог) в светлой теме, на английском и при масштабе 2. + +**Сравнение с эталонами** (снимки в одном размере окна, наложением): + +1. Прямоугольник доски в «Репертуарах», «Занятии», «Вариантах» совпадает с доской игры с компьютером + (`ref-04`): 1400×900 — x 54…886, y 60…892; 960×600 — x 22…554, y 60…592; допуск 1 px. +2. Высота шапки, положение кнопки «назад», заголовка, подписи и «Настроек» — как у партии (`ref-02`). +3. Левый край правой панели — как у игры (940 при 1400; 576 при 960). +4. Карточка состояния рядом с карточкой игрока (`ref-04`): те же поля, радиус, обводка, заливка активной. +5. Строка и заголовок таблицы рядом с таблицей библиотеки (`ref-01`): высоты 24 и 26, чередование, выделение. +6. Диалоги рядом с «Игра с компьютером» и «Подготовка к сопернику» (`ref-03`, `ref-05`): заголовок, поля, + кнопки справа внизу, одна главная. +7. Высота всех кнопок в рядах — 30, значков полосы — 28; ширины главных кнопок 170. + +**Состояния для снимков** (каждое в двух размерах): пустой список; один репертуар; 12 репертуаров (поиск, +прокрутка); длинное имя (120 знаков); каждое состояние карточки из §3 (девять); меню `⋯`; все диалоги §7, +включая импорт с предупреждениями, сброс с общими позициями и ошибку имени; S0–S9 занятия, включая S3a и +S5a; длинный комментарий (прокрутка в D); позиция без названия дебюта; итог без ошибок, с ошибками (> 8), +досрочный; «Повторить всё подряд» (S1 между вариантами, итог); «Тренировать эту ветку»; «Варианты» — начало, +выбран глубокий ход, выключенная ветка; полоса сообщения с ошибкой; панель, суженная до 320. + +**Отсутствие скачков** — серии кадров с наложением, различия допускаются только внутри названных блоков: + +- A. Выбор строк 1→2→3 и возврат: меняются только тексты карточки и позиция доски; рамка карточки, таблица, + нижний ряд неподвижны. +- B. Импорт: до диалога → диалог → после: таблица сдвигается только на добавленную строку; во время счёта + нет «…» поверх прежних чисел и нет индикатора вращения. +- C. «Тренироваться» → S1 → S3 → S4 → S3 → S5 → S6 → S7 → S6 → S8 → «К репертуарам»: доска и границы + блоков A–F совпадают на всех кадрах; меняются только тексты, рамка A и содержимое D. +- D. Ошибка записи (S9) и повтор: те же границы. +- E. «Варианты»: выбор десяти разных ходов, включение/выключение ветки — блок выбранного хода и полоса не + меняют высоту. +- F. Открытие общих настроек из каждого экрана и возврат: состояние не сброшено. + +**Понятность без цвета**: в S4, S5, S9 состояние названо словом в заголовке; выключенная ветка — словом «Не +тренируется»; цвет репертуара — фигурой короля и подсказкой. + +Дефект записывается так: снимок, размер, состояние, блок, ожидаемое и фактическое значение в pt. + +## 10. Передать тестировщику + +- Числа карточки, таблицы, счётчика занятия и итога сходятся между собой на одном сценарии (10 новых, + 3 ошибки, 1 подсказка). +- Ошибочный ход возвращается в том же занятии; S5a не считается ошибкой. +- Выход на каждом состоянии (Esc, Ctrl+W, кнопки) не теряет записанные ответы; PGN-файлы не меняются + (контрольные суммы до и после). +- Репертуары 2.2.0/2.3.0 с режимом «оба цвета», с `max_plies = 20`, с незаконченной сессией открываются без + ошибок и без потери прогресса. +- Сброс с общими позициями меняет ровно названные репертуары. +- Клавиши §4.3 и §6.3 не срабатывают под диалогом и в поле ввода. + +## Возражения и риски + +1. **Строка «Путь» (блок C).** 03.11 владелец убрал нотацию из тренировки. Здесь это одна бледная + нередактируемая строка «где я», без дерева. Считаю её полезной для запоминания номеров ходов; если + владелец против — блок удаляется без последствий для вёрстки (D займёт его место один раз, при сборке). +2. **Полоса прогресса с сегментом «учится».** Концепция даёт одно число «Выучено X из Y». Критерий ядра + «изучено» — три верных ответа подряд, поэтому первые дни X = 0 и работа не видна. Сегмент «учится» не + вводит настроек и снимает это; число `k` можно убрать, оставив только цвет. +3. **«Новый репертуар» без редактирования ходов** создаёт пустой объект, который нечем наполнить на этом + экране. Диалог это объясняет, но путь остаётся слабым до этапа «ходы на доске». +4. **Отметка выключенных веток** требует правки общего `notation.rs` (§6.3) — нужно решение оркестратора. +5. **Текст удаления про возврат прогресса** (§7.5) не проверен по ядру. +6. **Предвыбор цвета при импорте** — эвристика; на PGN из целых партий она ненадёжна, поэтому выбор всегда + показан и подписан «проверьте». +7. Пометка «(α версия)» в названии оставлена: её ввёл владелец, снять её может только он. + +## Решения оркестратора по вопросам дизайнера (2026-11-26) + +1. `widgets::section_header_sub` — **принято**: новая функция в `widgets.rs`, существующие функции и их вызовы не меняются. +2. Поле в общем `notation.rs` для выключенных веток — **отклонено**: экран партии не трогаем. Состояние ветки показывается в блоке выбранного хода; если нужна отметка в дереве — только средствами раздела (например, своя обёртка/постобработка), без изменения поведения и вида нотации в других экранах. +3. Строка «Путь» в занятии — **не делать**: владелец дважды (03.11) явно убирал нотацию из тренировки. Место строки не резервировать. +4. Сегмент «учится» в полосе прогресса — **принято**. +5. Текст диалога удаления — разработчик сверяет с ядром (удаление репертуара не стирает LearningItem; при повторном импорте того же дерева прогресс подхватывается по `(FEN4, UCI)`); если не так — исправить текст, а не ядро. diff --git a/docs/research/opening-trainer-code-audit-2026-11-26.md b/docs/research/opening-trainer-code-audit-2026-11-26.md new file mode 100644 index 0000000..2bbb2d0 --- /dev/null +++ b/docs/research/opening-trainer-code-audit-2026-11-26.md @@ -0,0 +1,617 @@ +# Тренировка дебюта: технический аудит кода (2026-11-26) + +Автор: developer. Только чтение и анализ; исходный код не менялся, сборки и тесты +**не запускались** — все выводы сделаны чтением кода, `grep` и `git`. +Темы аналитика (ChessTempo, объём) и дизайнера (UX) не исследовались; целевой +объём взят из `docs/research/opening-trainer-rethink-2026-11-26.md`, вариант B. + +Обозначения: **[Факт]** — проверено по коду/гиту, ссылка рядом; **[Вывод]** — следует +из фактов; **[Предложение]** — рекомендация, не решение. + +## 0. Главное, что нужно знать до проектирования + +1. **Рабочее дерево отстаёт от выпущенного кода.** [Факт] Текущая ветка — + `feature/opening-repertoire-training` @ `f425e3a` («release: prepare 2.2.0»). + `main` @ `ddc8361` ушёл на 5 коммитов вперёд и содержит **выпущенный 2.3.0** + (`git log HEAD..main`, `git ls-remote --tags origin` показывает `v2.3.0`). Разница + по разделу — 1619 добавленных / 251 удалённая строка в 11 файлах + (`git diff --stat HEAD main -- crates/trainer apps/desktop/src`), в том числе + `learning_session.rs` (+352), `learning_graph.rs`, `store.rs`, `learning_training.rs` (+624). + Локальных тегов `v2.2.0`/`v2.3.0` нет. `AGENTS.md` («релиз 2.2.0») и файлы + `docs/decisions.md`, `docs/dev/tasks.md` в рабочем дереве тоже старее `main`: + в `main` есть решения «Разметка PGN и собственные альтернативы после 2.2.0» и + «Выпуск 2.3.0» (оба 2026-11-06). + **Следствие:** переписывать нужно от `main`, а незакоммиченные чужие правки + (временные стрелки) сначала перенести на `main`. Иначе потеряется поведение 2.3.0. +2. **2.3.0 отменил «один основной ответ».** [Факт, `main:docs/decisions.md`, + `main:CHANGELOG.md`] Тренируются все включённые собственные ответы позиции; + «основной» ход влияет только на порядок. В отчёте аналитика (§4.1) «один основной + ответ» назван незатрагиваемым решением — это устарело. +3. **Старый `repertoire_training.rs` недостижим как экран** (доказательство — §2.1), но в + `main` из него используются два помощника разметки доски. +4. **Формат данных на диске менять не нужно** ни для одного варианта (§3). +5. **У каждого нового репертуара скрытый лимит 20 полуходов** (§3.4) — действует с 2.2.0, + виден только бледной строкой «Training scope: selected part». +6. **Ядро покрывает вариант B примерно на 85 %**; не хватает одной небольшой функции + очереди и одного решения по возврату ошибочного хода (§5.3). + +Номера строк ниже — по рабочему дереву (HEAD `f425e3a` + незакоммиченные правки), если +не помечено `main:` (тогда — `git show main:<файл>`). В файлах ядра, которые 2.3.0 не +менял, номера совпадают. + +## 1. Карта раздела + +### 1.1. Модули и ответственность + +Desktop-UI (`apps/desktop/src/`, все под `#[cfg(not(web))]`, `lib.rs:33–63`): + +| Файл | Строк (всего / без тестов) | Ответственность | Кто вызывает | +|---|---|---|---| +| `repertoire_ui.rs` | 2360 / 2358 | Корневой экран `RepertoireUi`: загрузка хранилищ, таблица репертуаров, карточка, импорт/экспорт, создание/переименование/удаление, «Добавить в репертуар», окно параметров, общий сброс, фоновые задачи и их события, dev-хуки | `app.rs` | +| `repertoire_ui_tests.rs` | 1727 | Тесты корневого экрана (`#[path]`, `repertoire_ui.rs:2358`) | — | +| `learning_training.rs` | 3608 / 1566 (`main`: 4139 / ~1730) | Экран задания `LearningTrainingUi`: показ контекста, ввод хода, фоновая запись попытки, подсказка, пауза, итог | `repertoire_ui.rs:23, 698` | +| `repertoire_editor.rs` | 1060 / 757 | Редактор `RepertoireEditorUi`: дерево, ход на доске, основной ответ, отключение ветки, глубина, аналитика хода | `repertoire_ui.rs:24, 301` | +| `learning_dashboard.rs` | 1968 / 1420 | Статистика `LearningDashboardUi`: scope, вкладки, таблицы ходов, автоснимок истории | `repertoire_ui.rs:22, 285` | +| `learning_branches.rs` | 763 / 238 | Таблица веток/линий для дашборда | `learning_dashboard.rs:20, 302` | +| `learning_charts.rs` | 507 / 354 | Графики History/Scheduled/Sequences | `learning_dashboard.rs:900, 943, 972` | +| `learning_context_controls.rs` | 204 / 97 | Шесть параметров контекста | `repertoire_ui.rs:1734` | +| `repertoire_training.rs` | 1557 / 1090 | **Мёртвый** экран случайной практики (модель 03.11), `#![allow(dead_code)]` | никто (§2.1) | + +Итого в разделе: **13 754 строки**, из них рабочего кода ~7 880, тестов ~5 870. + +Граф вызовов UI: + +``` +app.rs ── RepertoireUi (repertoire_ui.rs) + ├─ LearningTrainingUi (learning_training.rs) [main: + 2 fn из repertoire_training.rs] + ├─ RepertoireEditorUi (repertoire_editor.rs) + ├─ LearningDashboardUi (learning_dashboard.rs) + │ ├─ learning_branches::show + │ └─ learning_charts::{history, scheduled, sequences} + └─ learning_context_controls::show +``` + +Ядро (`crates/trainer/src/`): + +| Модуль | Строк | Ответственность | Нужен UI сегодня | +|---|---|---|---| +| `lib.rs` | 481 | Legacy линейный тренер + `training.json` | Android; desktop — только dev-хук (§2.3) | +| `repertoire/model.rs` | 789 | `Library`, `Repertoire` (PGN-строка + флаги), слияние партий/префиксов, имена | да | +| `repertoire/tree.rs` | 476 | `RepertoireTree`: позиции, FEN4, пути, транспозиции; + кандидаты/цели/маршруты старых моделей | частично | +| `repertoire/learning.rs` | 298 | `LearningItem`, `LearningItemKey`, `TrainingAttempt`, журнал | да | +| `repertoire/srs.rs` | 199 | Расписание | да | +| `repertoire/learning_graph.rs` | 652 | `StatsScope`, активное множество ходов по графу FEN4, агрегат scope, проекция сброса | да | +| `repertoire/aggregate.rs` | 455 | `LearningAggregate` (счётчики, проценты, статус) | да | +| `repertoire/learning_session.rs` | 1115 (`main`: 1345) | Автомат сессии `LearningSessionSnapshot` | да | +| `repertoire/learning_context.rs` | 131 | Политика контекста (шесть параметров) | да | +| `repertoire/learning_modes.rs` | 87 | Четыре приоритета, сортировки | да | +| `repertoire/store.rs` + `migration.rs` | 1106 + 104 | `LibraryStore`, `LearningStore` (v3, чтение v2), `StatsStore` (v2) | да, кроме `StatsStore` | +| `repertoire/scope.rs` | 70 | `TrainingScope`/`TrainingScopeKey` (префиксы) | ключ — да (в формате сессии) | +| `repertoire/learning_analytics.rs` | 348 | Снимки истории, гистограммы, аналитика хода | дашборд, редактор | +| `repertoire/branch_analytics.rs`, `line_analytics.rs` | 71 + 107 | Статистика веток и линий | дашборд | +| `repertoire/stats.rs` | 1070 | v2: `MoveStats/RunStats/PathStats`, курсоры; + enum `TrainingMode`, `QueueMode` | только enum и чтение v2 | +| `repertoire/session.rs` | 1162 | v2: `TrainingSession` (практика/очередь по дереву) | **нет** (§2.2) | +| тесты (11 файлов) | 8 115 | | — | + +### 1.2. Экраны и состояния + +`RepertoireUi::show` (`repertoire_ui.rs:960`) выбирает один из четырёх экранов по полям: + +1. **Задание** — `training_visible && training.is_some()` (`:971`). +2. **Редактор** — `editor.is_some()` (`:992`). +3. **Статистика** — `dashboard.is_some()` (`:1007`). +4. **Рабочая область** (иначе): шапка `:1027`, `show_workspace` `:1477` (доска-превью `:1834`, + карточка `workspace_panel` `:1515`, таблица `show_library` `:1136`), поверх — + `show_add` `:1982` («Добавить в репертуар»), `parameters_window` `:1669`, + `import_preview` `:1448`, `name_editor` `:1403`, `shared_reset_panel` `:1907`, `errors` `:1048`. + +Состояние корневого экрана — 45 полей (`repertoire_ui.rs:150–197`), из них 9 — счётчики +поколений и флаги фоновых задач (`index_generation`, `indexing`, `preparing`, +`training_generation`, `reset_generation`, `review_reset_pending`, `cancel`, `tx`, `rx`). +Восемь видов событий от фоновых потоков — `enum Event` (`:111`). + +Экран задания — 29 полей (`learning_training.rs:105–137`); собственный автомат показа +`enum Playback` (`:81`) поверх автомата ядра `LearningSessionPhase` (6 фаз, +`learning_session.rs:33`). То есть состояний задания два слоя: фаза ядра × фаза показа +× «запись идёт / ошибка записи / пауза / остановлено». + +### 1.3. Точки входа из остального приложения + +| Точка | Место | +|---|---| +| Поле экрана | `app.rs:299` `repertoire: Option`; `:301` `toast_repertoire` | +| Кнопка в библиотеке | `library.rs:843–848` (под `CAPS.training`), действие `LibraryAction::OpeningTraining` `library.rs:93`; расчёт ширины панели `library.rs:163–182`; дубль в меню узкого окна `library.rs:1727` | +| Открытие/закрытие | `app.rs:2269` `open_repertoire`, `:2293` `close_repertoire`, вызов `app.rs:4277` | +| Отрисовка и действия экрана | `app.rs:2304` `show_repertoire`; `RepertoireAction` (`repertoire_ui.rs:27`): `Close`, `OpenSettings`, `Sound`, `Toast`, `SettingsChanged`, `Added` — разбор `app.rs:2313–2343`; ветка кадра `app.rs:3938–3940` | +| «Добавить в репертуар…» | `game_view.rs:2066–2081` (меню ☰), `game_view.rs:1636`, `notation.rs:482–487` (контекстное меню хода), `GameAction::AddToRepertoire` `game_view.rs:134`, `game_view.rs:3927`; приём `app.rs:4080–4081` → `open_repertoire_add` `app.rs:2284` | +| Toast «Открыть» после добавления | `app.rs:4406–4466` → `open_from_toast` `repertoire_ui.rs:352` | +| Запрет горячих клавиш библиотеки при открытом разделе | `app.rs:3891–3926` | +| Защита несохранённого при закрытии окна | `app.rs:3803–3813` → `has_unsaved`/`resolve_unsaved` `repertoire_ui.rs:267, 276` | +| Миграция настроек при старте | `app.rs:435` → `Settings::migrate_repertoire_flow` `settings.rs:253` | +| Поля настроек | `settings.rs:162–176` (§3.3). В `settings_ui.rs` раздел не упоминается: общие настройки открываются действием `OpenSettings` | +| Флаг платформы | `platform/mod.rs:48` `CAPS.training` (`:66` desktop = true, `:81` web = false) | +| Путь legacy-файла | `lib.rs:153–162` `train::set_file` (`CP_TRAINING_FILE`) | +| Пути хранилищ раздела | `repertoire_ui.rs:2340` `stores()` (`CP_REPERTOIRE_DIR`) | +| Dev-хуки | `app.rs:778–860`: `CP_REPERTOIRE`, `CP_REPERTOIRE_IMPORT_FILE`, `CP_REPERTOIRE_EXPORT`, `CP_REPERTOIRE_CONFIRM_IMPORT`, `CP_REPERTOIRE_RENAME`, `CP_REPERTOIRE_DELETE`, `CP_REPERTOIRE_MOVES`, `CP_REPERTOIRE_HINT`; `app.rs:951–969` `CP_ADD_REPERTOIRE`; `app.rs:975–982` `CP_TRAIN`, `CP_TRAIN_MOVES` (legacy). Приёмники — `repertoire_ui.rs:2050–2130` (`debug_*`) | +| i18n | Ключ = английская строка; таблица `ROWS` `i18n.rs:218`, 9 языков. Тест `all_used_keys_are_translated` (`i18n.rs:20377`) читает исходники по списку `include_str!` (`i18n.rs:20408–20415` — восемь файлов раздела). В файлах раздела ~184 ключа, из них ~156 не используются больше нигде (оценка однострочным `grep`, многострочные вызовы занижают) | + +## 2. Слои и мёртвый код + +Раздел содержит четыре модели, наложенные друг на друга: + +| № | Модель | Дата | Ядро | UI | Состояние | +|---|---|---|---|---|---| +| L0 | Линейный тренер «до этого хода» | до 02.11 | `trainer/src/lib.rs` | `game_view.rs:3924–4520` | Android — рабочий; desktop — только dev-хук | +| L1 | Дерево + очередь по ходам, v2 | 02.11 | `session.rs`, `stats.rs`, часть `tree.rs`, `StatsStore` | `repertoire_training.rs` | мёртвый | +| L2 | Случайная практика маршрутов | 03.11 | там же (курсоры, `PathStats`) | `repertoire_training.rs` | мёртвый | +| L3 | LearningItem + SRS, v3 | 04.11 → 2.2.0/2.3.0 | `learning*.rs`, `srs.rs`, `aggregate.rs`, `LearningStore` | остальные файлы раздела | рабочий | + +### 2.1. `repertoire_training.rs` — доказательство недостижимости + +[Факт] Рабочее дерево (2.2.0): + +- Файл подключён только строкой `mod repertoire_training;` (`lib.rs:61`) и начинается с + `#![allow(dead_code)]` (`repertoire_training.rs:1`). +- `grep -rn "repertoire_training::\|crate::repertoire_training" apps crates` — **пусто**. +- Его типы `TrainingUi` и `TrainingAction` нигде не названы: в `repertoire_ui.rs:980–987` + имя `TrainingAction` — псевдоним `LearningTrainingAction` (`repertoire_ui.rs:23`). +- Единственные внешние упоминания файла — `include_str!` в тесте переводов + (`i18n.rs:20415`) и два строковых идентификатора панелей внутри него самого. + +**Вывод для 2.2.0: файл целиком недостижим из интерфейса; компилируется и тянет 28 +ключей перевода.** + +[Факт] `main` (2.3.0): `learning_training.rs:27` содержит +`use crate::repertoire_training::{BoardAnnotations, pgn_annotations_at};` +(структура `main:repertoire_training.rs:40`, функция `:1033` — значок NAG, стрелки и +поля `[%cal]/[%csl]` узла PGN). Экран `TrainingUi` остаётся недостижимым. + +**Вывод для 2.3.0: достижимы ровно два элемента (~60 строк); остальные ~1 030 строк +рабочего кода и ~500 строк тестов файла мёртвые.** При переписывании помощник +разметки нужно перенести в новый модуль, файл удалить. + +### 2.2. Ядро: что достижимо из UI + +Проверка — `grep -lw <тип> apps/desktop/src/*.rs`: + +| Элемент ядра | Где используется вне `crates/trainer` | Вердикт | +|---|---|---| +| `TrainingSession`, `TrainingVerdict`, `SessionError`, `SrsPolicy` (`session.rs`, `stats.rs`) | только `repertoire_training.rs` | мёртвые для UI | +| `StatsStore`, `StatsData`, `RunStats` | `repertoire_training.rs`, `repertoire_ui_tests.rs` | только мёртвый экран и тесты | +| `MoveStats`, `PathStats`, `AttemptRecord`, `RunRecord`, `MoveKey`, `PathKey`, `PreparedNextPath`, `MoveChooser`, `FirstMoveChooser`, `SessionAttempt`, `PlayedMove`, `TrainingPath`, `TrainingTarget`, `TrainingScopeKey`, `LegacyMigrationReport`, `MigrationReport` | нигде в `apps/` | только ядро и его тесты | +| `Candidate` (`tree.rs`) | `repertoire_training.rs` (в `prep_ui.rs`, `review_engine.rs` — одноимённые чужие типы) | мёртвый для UI | +| `TrainingScope` | `repertoire_training.rs`, `repertoire_ui.rs` (подсчёт вариантов `pgn_route_count` `:2209`) | один живой вызов | +| `Library::migrate_legacy_lines` (`model.rs:459`) | нигде, кроме тестов ядра | мёртвая | +| `QueueMode`, `TrainingMode` (`stats.rs`) | `learning_training.rs`, `repertoire_ui.rs`, `repertoire_editor.rs`, **`settings.rs:167–168`** | живые, входят в форматы (§3) | + +Внутри самого ядра legacy всё ещё связан с рабочим путём: + +- `store.rs:18` и `migration.rs:7` читают `StatsData`/`MoveStats` — это **чтение файла v2** + при миграции в v3 (`store.rs:633–650`). Удалить структуры v2 нельзя, пока поддерживается + чтение v2 (§3.2). +- `learning_session.rs:16`, `learning_graph.rs:13`, `store.rs:18` используют `QueueMode` и + `TrainingMode` из `stats.rs` — живые типы лежат в legacy-модуле. +- `session.rs` (1162 строки) не используется никем, кроме `repertoire_training.rs` и + тестов `tests.rs`/`advanced_tests.rs` (2 595 строк тестов). + +Оценка мёртвого объёма: ядро — `session.rs` 1162 + ~900 из `stats.rs` + ~250 из `tree.rs` +(кандидаты, цели, маршруты) + `StatsStore` ~100 + тесты ~2 600 ≈ **5 000 строк**; +UI — `repertoire_training.rs` ~1 500. Всего ≈ 6 500 строк, которые не исполняются +пользователем. + +### 2.3. Что нужно Android и web + +[Факт] `crates/mobile-api/src/train.rs:10` импортирует только +`trainer::{LineStats, TrainStart, Training, Verdict}`, `:17` — `trainer::set_file`, +`:144` — `trainer::runs_to`. `grep -rn "repertoire::" crates/mobile-api apps/web` — пусто. +Модуль `trainer::repertoire` в Android компилируется, но не вызывается. + +[Факт] Desktop и web используют корневой legacy-API так: + +- `lib.rs:82` `use trainer as train;`, `lib.rs:161` `train::set_file` при старте. +- `game_view.rs:87` `train: Option` и ~600 строк линейной тренировки + (`game_view.rs:3924–4520`). Запуск — `start_training` (`game_view.rs:3934`) ← только + `App::open_training` (`app.rs:2350`) ← только dev-хук `CP_TRAIN` (`app.rs:975–978`). + **Пользователь desktop до линейной тренировки добраться не может** с 02.11 + («Учить дебют до этого хода» заменено на «Добавить в репертуар…»). +- `TrainStart::from_game` служит предикатом доступности «Добавить в репертуар…» + (`game_view.rs:2070, 3928`, `notation.rs:483`) — это живое использование. + +Это мёртвый UI в чужом файле (`game_view.rs` — экран партии). В рамках переписывания +раздела его трогать нельзя; фиксирую как отдельный технический долг. + +[Факт] Web: `settings.rs` собирается и под wasm и называет типы +`trainer::repertoire::{TrainingMode, QueueMode, LearningPriority, LearningContextPolicy}` +(`settings.rs:164–176`). Поэтому весь крейт `trainer` обязан собираться под wasm, а эти +четыре типа — существовать и десериализоваться (§3.3, §4.3). + +## 3. Данные на диске + +### 3.1. Файлы + +Каталог данных — `ProjectDirs("io.github","vrubelroman","ChessPenguin").data_local_dir()` +(на Linux `~/.local/share/chesspenguin/`), переопределяется `CP_REPERTOIRE_DIR` +(`repertoire_ui.rs:2340–2356`). + +| Файл | Формат | Версия | Кто пишет | Выпущен | +|---|---|---|---|---| +| `repertoires.json` | `Library { version, revision, repertoires[] }` (`model.rs:200`). Репертуар (`model.rs:74`): `id`, `name`, **`pgn` — текст PGN целиком внутри JSON**, `max_plies`, `disabled_prefixes`, `main_answer_overrides`, `path`, `detached` | `LIBRARY_VERSION = 1` (`model.rs:14`) | `LibraryStore::save` (`store.rs:258`) | 2.2.0 | +| `repertoire-training.json` | `LearningStoreData` (`store.rs:296`): `version`, `revision`, `learning { items[], attempts[] }`, `sessions[]`, `session_snapshots[]`, `snapshots[]` (история по дням), `legacy_practice` (сырой JSON v2), + неизвестные поля (`#[serde(flatten)] extensions`) | `LEARNING_STORE_VERSION = 3` (`store.rs:282`) | `LearningStore` (`store.rs:392`) | 2.2.0 | +| `repertoire-training.json.before-learning-v3` | Копия файла v2 перед первой записью v3 (`store.rs:929`, `backup_v2_once` `:733`) | — | один раз | 2.2.0 | +| `*.lock` | Пустые файлы межпроцессной блокировки (`store.rs:178`) | — | — | 2.2.0 | +| `training.json` | Legacy L0: карта «ключ линии → счётчики» (`lib.rs:263–385`) | без версии | корневой `trainer` (Android; desktop — dev-хук) | до 2.2.0 | +| `settings.json` (`~/.config/chesspenguin/`) | Общие настройки, четыре поля раздела (§3.3) | — | `Settings::save` (`settings.rs:309`) | 2.2.0 | + +Отдельных файлов PGN-репертуаров **нет**: PGN хранится строкой в `repertoires.json`; +на диск PGN попадает только явным экспортом (`repertoire_ui.rs:799`). Исходный +импортируемый файл не изменяется (читается в `read_import`, `repertoire_ui.rs:2140`). + +### 3.2. Миграции + +[Факт] Путь чтения `LearningStore::load_latest` (`store.rs:621–716`): + +1. Файл есть, `version == 3` → читается как есть; неизвестные поля сохраняются при записи + (`preserve_extensions`, `store.rs:751`). +2. Файл есть, `version == 2` (`STATS_VERSION`) → `migration::migrate_v2` (`migration.rs:18`) + консервативно строит `LearningItem` из `move_stats`; весь исходный JSON кладётся в + `legacy_practice`; при первой записи делается копия `.before-learning-v3`. +3. Файла нет, есть `training.json` → его содержимое кладётся в `legacy_practice`, сам + файл не трогается. +4. Иная версия → ошибка `UnsupportedVersion`, файл не перезаписывается. + +[Факт] Формат v2 **не входил ни в один выпуск**: в теге `v2.1.5` каталог +`crates/trainer/src/` содержит только `lib.rs`; `store.rs` впервые появился в коммите +`f49aab6` (03.11), `learning.rs` — в `d1733b4` (04.11); первый выпуск с разделом — 2.2.0, +уже с v3. Файлы v2 существуют только на машинах разработки. **Но профиль на этой машине +(`~/.local/share/chesspenguin/repertoire-training.json`, 03.11) — именно v2**: revision 82, +все списки пусты, один `random_practice_cursor`. Пять репертуаров в `repertoires.json` +имеют `max_plies = 4294967295`. + +[Факт] 2.3.0 формат не менял: новые поля `LearningSessionSnapshot` помечены +`#[serde(skip)]` (`main:learning_session.rs:88`), версии констант те же. + +### 3.3. Поля настроек раздела (`settings.rs:162–176`) + +| Поле | Тип | Смысл | +|---|---|---| +| `repertoire_flow_version` | `u8` | Одноразовая миграция 02.11 (`settings.rs:253`) | +| `repertoire_modes` | `HashMap` | Цвет и режим репертуара; читается `select` (`repertoire_ui.rs:391–406`), пишется `start` (`:688–690`) и окном параметров (`:1651`) | +| `repertoire_priorities` | `HashMap` | Порядок; `repertoire_ui.rs:407`, `:691`, `:1656`, `:1775` | +| `repertoire_context_policies` | `HashMap` | Шесть параметров; `repertoire_ui.rs:677–681`, окно `:1669`, запись `:1730–1736` | + +**Опасность.** [Факт] `Settings::load` при любой ошибке разбора JSON возвращает +`Settings::default()` (`settings.rs:286–292`) — то есть сбрасывает **все** настройки +приложения. Перечисления сериализуются именами вариантов (`QueueMode` — `Practice`, +`SpacedRepetition`, `ReviewInOrder`, `LeastRecent`, `stats.rs:32`; `TrainingMode` — +`stats.rs:15`; `LearningPriority` — `learning_modes.rs:13`). Если удалить вариант из ядра, +оставив поле в `Settings`, у пользователя 2.2.0/2.3.0 с сохранённым таким значением при +обновлении **молча сбросятся язык, движки, базы и всё остальное**. Удаление самого поля +из `Settings` безопасно (unknown fields игнорируются: `deny_unknown_fields` нет), но +значение исчезнет при следующем сохранении. + +### 3.4. Скрытое ограничение глубины у новых репертуаров + +[Факт по коду; запуском не проверялось] + +- `Library::create` присваивает `max_plies: DEFAULT_MAX_PLIES` = 20 (`model.rs:15, 348`); + это закреплено тестом ядра (`tests.rs:240`). +- Все пути создания идут через `create`/`create_empty`: новый пустой + (`repertoire_ui.rs:1434`), импорт PGN (`:2186`), «Добавить в репертуар» (`:2025`). + После создания `max_plies` нигде не меняется: в `repertoire_ui.rs` поле только + читается (`:562, :1590, :1812`); изменить его можно лишь в редакторе + (`repertoire_editor.rs:274–292`). Нормализации при загрузке нет (в `model.rs`/`store.rs` + нет присваивания `u32::MAX`; она была в коде 03.11 и удалена 04.11 — + `git log -S"max_plies = u32::MAX"`). +- UI передаёт лимит в scope: `StatsScope::…with_max_depth(Some(max_plies))` + (`repertoire_ui.rs:1809–1814`); граф отбрасывает ходы глубже (`learning_graph.rs:423`, + условие `depth >= maximum`). +- Единственный видимый признак — бледная строка «Training scope: selected part» + (`repertoire_ui.rs:1590–1592`). + +**Вывод:** у пользователя 2.2.0/2.3.0 каждый импортированный PGN тренируется только на +первые 10 ходов, счётчики считают только их, а причина почти не видна. Это вероятный +источник части жалоб «непонятно». Любой новый UI обязан явно решить судьбу этого +значения (§5.4). + +### 3.5. Что можно упростить, что нельзя + +**Нельзя менять (выпущено, содержит пользовательские данные):** + +- `repertoires.json` v1 — все поля `Repertoire`, включая `disabled_prefixes`, + `main_answer_overrides`, `max_plies`. +- `repertoire-training.json` v3: `learning.items[]` (все поля `LearningItem`, + `learning.rs:55–85`), `learning.attempts[]` (журнал, по нему работает идемпотентность + `client_attempt_id`), `session_snapshots[]` (незавершённые занятия), `snapshots[]`, + `legacy_practice`, неизвестные поля. +- Сериализованные имена вариантов `QueueMode`, `TrainingMode`, `LearningPriority`, + `LearningSessionPhase`, `TrainingEventType`, `LearningSide` — они записаны в файлах + сессий и настроек. +- `training.json` и корневой API `trainer` — Android. + +**Можно упростить без потери данных** (все пункты — [Предложение], не требуются варианту B): + +- Не показывать и не пополнять `snapshots[]` (история по дням) — данные остаются в файле. +- Не создавать новых сессий режима `LeastRecent` и с нестандартной политикой; старые + остаются в файле. +- Чтение v2 свести к маленькой serde-структуре с одним полем `move_stats` вместо + `stats.rs` (1070 строк): `migrate_v2` использует только `move_stats` + (`migration.rs:18–34`), остальное сохраняется как сырой JSON. Либо убрать чтение v2 + совсем после однократной миграции машины владельца — v2 не выпускался. +- Удалить `StatsStore` (запись v2) — рабочий путь v2 не пишет. + +**Замечания по росту файла** [Факт]: + +- `sessions[]` и `session_snapshots[]` только пополняются (`upsert_session`, `store.rs:908`); + удаления завершённых сессий нет. Каждый снимок хранит всю очередь с полными путями ходов. +- `attempts[]` растёт без ограничения, и **каждая попытка перечитывает и целиком + переписывает файл** (`apply_attempt_and_session`, `store.rs:560–611`; pretty-JSON). + Работа идёт в фоновом потоке, но цена хода растёт линейно с историей. Замеров нет. + В 2.3.0 автопоказ контекста записывается одной пачкой (`main:store.rs` + `apply_attempts_and_session`), что убрало худший случай, но не рост. + +## 4. Граница переписывания + +### 4.1. Что можно заменить, не задевая остальное приложение + +Удаляются/заменяются целиком (вне раздела на них никто не ссылается, §1.1): + +- `apps/desktop/src/repertoire_ui.rs`, `repertoire_ui_tests.rs` +- `apps/desktop/src/learning_training.rs` +- `apps/desktop/src/repertoire_editor.rs` +- `apps/desktop/src/learning_dashboard.rs`, `learning_branches.rs`, `learning_charts.rs` +- `apps/desktop/src/learning_context_controls.rs` +- `apps/desktop/src/repertoire_training.rs` (в `main` сначала перенести `BoardAnnotations` и + `pgn_annotations_at`) + +Контракт с `app.rs`, который новый корневой модуль должен сохранить, чтобы `app.rs` не +менялся вообще: + +- путь и имя типа `crate::repertoire_ui::RepertoireUi`; +- методы: `new()`, `open_library()`, `open_from_toast(id, title, &Settings)`, + `open_add_from_game(Game, NodeId, String)`, `has_unsaved()`, `resolve_unsaved()`, + `show(&mut Ui, &mut Settings) -> Vec`; +- `RepertoireAction::{Close, OpenSettings, Sound, Toast, SettingsChanged, Added{id,name,report}}`; +- dev-хуки `debug_open`, `debug_import`, `debug_confirm_import`, `debug_export`, + `debug_rename`, `debug_delete`, `debug_add_from_game`, `debug_moves`, `debug_hint` + (сигнатуры — `repertoire_ui.rs:2050–2130`). Они нужны и для визуальной приёмки снимками. + +Неизбежные правки вне файлов раздела (минимальный набор): + +| Файл | Правка | Риск | +|---|---|---| +| `lib.rs:33–63` | Список `mod` раздела | нулевой | +| `i18n.rs` | Новые строки в `ROWS` (9 языков каждая); список `include_str!` в тесте (`:20408–20415`). Старые строки можно оставить: теста на неиспользуемые ключи нет (`rows_are_unique_and_complete` проверяет только уникальность и заполненность) | низкий; объёмный файл, возможны конфликты слияния | +| `app.rs` | Ничего при сохранении контракта выше | — | +| `settings.rs` | Ничего (рекомендация §5.4: поля оставить) | — | +| `library.rs`, `game_view.rs`, `notation.rs` | Ничего | — | + +### 4.2. Общие компоненты — только использовать, не менять + +| Компонент | Что берёт раздел | +|---|---| +| `board.rs` | `BoardView` (`:198`), `BoardState` (`:39`), `Arrow` (`:9`), `Badge` (`:19`), `ui_target` (`:791`). Поля `alert` (`:219–220`, «wrong move, learning an opening») и незакоммиченное `temporary_shapes` (`:208–209`) обязательны при конструировании `BoardView` | +| `widgets.rs` | `section_header` (`:14`), `settings_button` (`:6`), `primary` (`:112`), `primary_wide` (`:117`), `check_panel` (`:36`) | +| `settings.rs` | `Settings.animation.seconds()`, `board_theme`, `piece_set`, `show_coords`; четыре поля раздела | +| `assets.rs` | `Sound::{Move, Success, Wrong}`; воспроизведение — через `RepertoireAction::Sound` → `App::play` | +| `platform` | `spawn` (`platform/mod.rs:111`) для фоновых задач; `CAPS.training` | +| `san.rs` | `san::show` (фигурная нотация по настройке) | +| `app.rs` | `overlay_open` (`:180`) | +| `game_view.rs`, `notation.rs` | `shape_color` (`game_view.rs:5292`), `assessment_color` (`notation.rs:695`) — цвета разметки PGN | +| `chess-core` | `Game`, `NodeId`, `parse_str`, `comments_after` (`game.rs:130`), `nags` (`:122`), `parse_comment` (`comment.rs:58`), `comment_display_text` (`:258`), правка дерева `edit.rs` | +| `chess-openings` | Названия/ECO для таблицы (`opening_labels`, `repertoire_ui.rs:2264`) | + +**Незакоммиченные чужие правки.** [Факт, `git status`, `git diff --stat`] 18 изменённых +путей; в разделе затронуты `learning_training.rs`, `repertoire_editor.rs`, +`repertoire_training.rs`, `repertoire_ui.rs` — по одной строке `temporary_shapes: …` в +конструкторах `BoardView`; основная работа — `board.rs` (+257) и `game_view.rs` (+20). +При удалении файлов раздела эти четыре строки исчезнут вместе с файлами — это допустимо +только если новый модуль тоже задаёт `temporary_shapes: true` на доске задания и +`false` на досках превью/редактора (так в текущих правках). Сами `board.rs` и +`game_view.rs` не трогать. Перед началом работ правки нужно закоммитить или отложить их +владельцу (не мне решать): пока они висят в рабочем дереве, любой `git checkout main` +/ rebase рискует ими. + +### 4.3. Риски для wasm и mobile-api + +- **wasm (`apps/web`).** Все файлы раздела под `#[cfg(not(web))]` (`lib.rs:33–63`), + `CAPS.training = false` (`platform/mod.rs:81`), вызовы в `app.rs` — под `#[cfg(not(web))]`. + Но `settings.rs` общий и называет четыре типа ядра → крейт `trainer` целиком собирается + под wasm. Новый UI-модуль должен оставаться под тем же `cfg`; новые зависимости в + `trainer` (потоки, файловые блокировки сверх уже имеющихся) под wasm нужно проверять + сборкой `apps/web`. Сегодня ядро использует `std::fs` и `File::lock` (`store.rs:178–195`) — + под wasm это компилируется, но не вызывается. +- **mobile-api.** Использует только корень `trainer` (§2.3). Риск один: случайная правка + `crates/trainer/src/lib.rs` или изменение зависимостей крейта. Проверка — + `cargo test -p mobile-api -p trainer` и сравнение сигнатур шести имён. +- **Совместимость назад.** Добавление нового варианта в `QueueMode` или + `LearningSessionPhase` сделает файл нечитаемым для 2.2.0/2.3.0 (ошибка разбора при + откате версии; данные не теряются, но раздел не откроется). Поэтому новые режимы + лучше не вводить как варианты enum (§5.3). + +## 5. Оценка ядра и готовность к варианту B + +### 5.1. Что качественно и стоит сохранить + +| Часть | Почему | +|---|---| +| `LearningItemKey (profile, FEN4, UCI)` — `learning.rs:8–31` | Транспозиции и общие ходы разных репертуаров дают одну запись; в 2.3.0 это же позволило учить несколько своих ответов без смены формата | +| Типизированные события `TrainingEventType` (`learning.rs:205`) и разделение «самостоятельный ответ / показ / повтор после ошибки» | Счётчики не раздуваются подсказками; это решение 04.11, подтверждённое сверкой 05.11 | +| `srs.rs` (199 строк) | Чистые функции без ввода-вывода, константы в одном месте (`:8–15`) | +| `LearningStore` (`store.rs:392–750`) | Межпроцессная блокировка, атомарная замена, `revision` против конфликтов, идемпотентность по `client_attempt_id` (`:573–590`), сохранение неизвестных полей, резервная копия при миграции. Это самое дорогое в воспроизведении место | +| `learning_graph.rs` | Активное множество ходов по графу FEN4 с **реальными** путями PGN (`GraphEdge.source_path`), отключённые ветки, корень ветки, лимит глубины; проекция общего сброса (`reset_impact`, `:230`) | +| `aggregate.rs` | Один проход, проверка инвариантов, `next_due_at` | +| Автомат сессии `LearningSessionSnapshot` | Сохраняемый, возобновляемый, с проверкой согласованности (`validate`, `learning_session.rs:686`) | +| Тесты | 174 теста в 11 файлах (8 115 строк), включая приёмочные AT | + +### 5.2. Что переусложнено + +Ничто из этого не мешает варианту B: всё выключается значениями по умолчанию. + +- **Политика контекста**: шесть параметров + план (`learning_context.rs`, 131 строка), + адаптивная скорость, «пропуск знакомого начала». По умолчанию + (`learning_context.rs`, `impl Default`): подкрепление выключено + (`consider_leadup_moves: false`), скорость фиксированная, порог пропуска 100 верных + подряд — то есть весь подвод показывается автоматически. +- **Четыре приоритета** (`learning_modes.rs:13`): `CommonPositionsFirst` реализован как + тот же `BreadthOverDepth` (комментарий в коде: данных о популярности нет). +- **Режим `LeastRecent`** со своей веткой в планировщике контекста. +- **Аналитика**: `learning_analytics.rs`, `branch_analytics.rs`, `line_analytics.rs` + (526 строк) + ежедневные снимки в хранилище. +- **`LearningItem` — 20 полей** (`learning.rs:55–85`): гистограмма неверных ходов, времена + ответов, последние исходы, `resistant`. Варианту B нужны шесть: `introduced`, + `correct_streak`, `next_review_at`, `last_correct_at`, `previous_interval_seconds`, + `last_review_at`. Остальные — в выпущенном формате, оставить. +- **`SrsSettings` (8 параметров) хранится в каждой сессии**, хотя UI всегда передаёт + `SrsSettings::default()` (`repertoire_ui.rs:704, 1826`). +- **Дубли API**: `new`/`new_with_mode`; `presentation`/`presentation_with_learning`; + `play_uci`/`play_uci_with_learning`/(`main`) `play_uci_with_learning_answers`; + `advance_context`/`advance_context_with_learning`. Версии без `learning` дают другое + поведение контекста — ловушка для нового кода: использовать только `*_with_learning*`. +- **Дубли в формате**: `sessions[]` повторяет `session_snapshots[].session` + (`store.rs:908–927`); `LearningSession.scope` повторяет `stats_scope.branch_root`. +- **Производительность**: `LearningData::item` — линейный поиск (`learning.rs:284`); + `repertoire_memberships` заново разбирает PGN при каждом вызове + (`learning_graph.rs`, `RepertoireTree::from_game(repertoire.game(), …)`); + запись — см. §3.5. Всё вынесено в фон, замеров на больших репертуарах в этом аудите нет. +- **Legacy внутри**: `session.rs`, большая часть `stats.rs`, `StatsStore`, + `Library::migrate_legacy_lines` (§2.2). + +### 5.3. Проверка требований варианта B + +Строки: рабочее дерево / `main`, где отличаются. Файлы — `crates/trainer/src/repertoire/`. + +| № | Требование | Есть в ядре | API | Что дописать | +|---|---|---|---|---| +| 1 | Очередь «повторения на сегодня + не более N новых» | **Частично** | Повторения: `LearningSessionSnapshot::new` (`learning_session.rs:193` / `main:246`) → `select_queue`, режим SRS берёт только `is_due(scope.as_of)` (`:989–996` / `main:1163–1171`). Новые: `introduce_new` (`:252` / `main:306`) — только из фазы `Finished`, **заменяет** очередь на **все** невиданные, без лимита | Нет смешанной очереди и нет N. Нужен конструктор вида `new_daily(…, max_new)`: `due` + первые N невиданных в порядке `DepthFirst`. ~40–60 строк + тесты. Обходной путь без правки ядра есть (поля `queue` и `current_index` публичны: после `introduce_new` сделать `queue.truncate(N)`), но это правка состояния автомата снаружи — не рекомендую | +| 2 | Показ нового хода перед вопросом | **Да, но UI должен вызвать сам** | `preview(client_attempt_id, at)` (`:494` / `main:576`) → событие `PREVIEWED`, фаза `PreviewedReplay`; ход отдаётся в `LearningPresentation.revealed_move` (`:102–110` / `main:143–151`); следующий ход пользователя пишется как `AUTO_CONTEXT`, серии не меняет | В ядре ничего. Новый UI обязан вызвать `preview` сразу, когда цель не введена (`learning.item(key)` отсутствует или `!introduced`). **Сегодняшний UI этого не делает**: `preview` вызывается только по кнопке подсказки (`learning_training.rs:854–875`), то есть новый ход спрашивается вслепую | +| 3 | Немедленный показ ответа на ошибке | **Да** | Неверный ход → `INCORRECT_INDEPENDENT`, фаза `AwaitingReplayAfterError`, `revealed_move` заполнен; повтор пишется как `REPLAY_AFTER_ERROR` (`play_uci_impl`, `:547+` / `main:676–845`) | Ничего | +| 4 | Скорый возврат ошибочного хода | **Частично** | Расписание: ошибка → `next_review_at = now + 30 с` (`srs.rs:10`, `apply_independent_wrong`); показ → `+60 с` (`srs.rs:11`). Но очередь сессии фиксирована; после повтора цель помечается пройденной (`complete_current`, `:799` / `main:959`). Новый круг — `start_next_pass` (`:277` / `main:331`), он отбирает по **старому** `stats_scope.as_of`, зафиксированному при создании сессии | Нужен «следующий круг на текущий момент»: `start_next_pass_at(library, learning, as_of)` (~15 строк + тесты) и решение, что делать, если пользователь закончил круг быстрее 30/60 с (варианты: горизонт `as_of = now + 60 с` для ходов, тронутых в этой сессии; либо перенос ошибочной цели в конец очереди — ~20 строк в `play_uci_impl`). Обход без правки ядра: `stats_scope.as_of` публично | +| 5 | «Повторить всё подряд» | **Да** | `new_with_mode(…, QueueMode::ReviewInOrder)` (`:210` / `main:263`) + `StatsScope::with_learning_priority(DepthFirst)` (`learning_graph.rs:60`); порядок — `pgn_order` (`learning_modes.rs`, `compare_priority`); ответы идут через общий обработчик и меняют расписание. Курсор сохраняется, сброс — `LearningStore::reset_review_order` (`store.rs:547`) | В ядре ничего. Особенность: режим **не завершается сам** — после последней цели очередь начинается заново и растёт `cycle` (`complete_current`, `:810–817`). UI должен закончить занятие при смене `cycle`. Счётчик «Вариант 3 из 9» ядро не даёт (у цели есть `pgn_order` и `variation_depth`, но не номер варианта) — считать в UI по дереву (`RepertoireTree::visit_source_paths`, `tree.rs:329`) либо показывать «ход k из n» через `remaining()` | +| 6 | Тренировка отдельной ветки | **Да, не покрыто тестами сессии** | `StatsScope::with_branch_root(path)` (`learning_graph.rs:55`); сессия берёт `branch_root` из scope (`:228–231` / `main:281–284`); подвод показывается от начала партии, потому что путь цели — реальный путь PGN | В ядре ничего, но `with_branch_root` проверен только в `graph_tests.rs`, `branch_tests.rs`, `line_tests.rs` — в `session_tests.rs` его нет. Добавить 1–2 теста сессии с корнем ветки. В UI этого запуска сегодня нет вовсе (в `repertoire_ui.rs:564` только проверка `branch_root.is_none()`) | +| 7 | Счётчики «сегодня повторить / новых / выучено X из Y» | **Да** | `aggregate_scope` (`learning_graph.rs:206` / `main:208`) → `LearningAggregate` (`aggregate.rs:20–40`): `due`, `unseen`, `learnt`, `total`, `next_due_at` | Ничего. Уточнение: `due` считается на момент `scope.as_of`, а не «до конца дня». Если нужно именно «сегодня» — передать `as_of` = конец локального дня; для очереди при этом использовать отдельный scope с `as_of = now` | +| 8 | Комментарий PGN хода | **Да** | Путь цели `LearningSessionTarget.path` (`:43–52` / `main:46–56`) → `RepertoireTree::node_at_path` (`tree.rs:258`) → `Game::node(id).comments_after()` (`chess-core/src/game.rs:130`) → `comment_display_text` (`chess-core/src/comment.rs:258`) | Ничего в ядре. В `main` экран задания уже держит разобранные партии и показанный узел для разметки (`main:learning_training.rs:1206–1222`) — текст комментария берётся оттуда же | +| 9 | «Осталось N» | **Да** | `remaining()` (`:334` / `main:388`) | — | +| 10 | Несколько своих ответов (2.3.0) | **Да, только в `main`** | `pending_answers_for_position` (`main:397`), `is_active_repertoire_answer` (`main:411`), ошибка `LearningSessionError::RepertoireAlternative { already_completed }` (`main:174, 784`) | UI обязан обработать `RepertoireAlternative` как «этот ход тоже в репертуаре, сейчас нужен другой», без штрафа (как `main:learning_training.rs:800`) | +| 11 | Общий сброс с предупреждением | **Да** | `reset_impact` (`learning_graph.rs:230`), `LearningStore::reset_learning` (`store.rs:501`) | — | +| 12 | Правка репертуара: добавить/удалить ход на доске | **Нет в разделе** | Сегодняшний «редактор» ходы не меняет: доска неинтерактивна (`repertoire_editor.rs:233`), команды — только выбор, основной ответ, отключение, глубина (`:600–610`). Ходы попадают в репертуар лишь импортом и «Добавить в репертуар…» (`Library::add_game` `model.rs:380`, `add_prefix` `:422`) | Сценарий аналитика §5.1 п. 10 — **новая функция**: разбор `Repertoire.pgn` → `Game::add_move`/`delete_variation` (`chess-core/src/edit.rs:140, 229`) → `to_pgn()` → запись. Требует тестов семантического roundtrip (комментарии, NAG, FEN, `--`). Оценка отдельно: +300–400 строк и тесты | + +**Итог:** ядро нужно дополнить двумя-тремя небольшими функциями (пп. 1 и 4, тест к п. 6), +примерно 100–150 строк кода и 200–300 строк тестов, без изменения формата и без новых +вариантов enum. Утверждение «ядро даёт всё нужное без изменений» **неверно в двух +пунктах** (дозированный ввод новых; возврат ошибки в том же занятии) и **неверно в части +редактора** (п. 12). + +Минимальному сценарию «импортировал PGN → выбрал цвет → учу по расписанию → вижу +прогресс» нужны: `model.rs`, `tree.rs` (дерево, `fen4`, `node_at_path`), `learning.rs`, +`srs.rs`, `learning_graph.rs`, `aggregate.rs`, `learning_session.rs` (+ `learning_context.rs`, +`learning_modes.rs` со значениями по умолчанию), `store.rs` (`LibraryStore`, `LearningStore`), +`scope.rs` (тип ключа в формате). Не нужны: `learning_analytics.rs` (кроме типа +`LearningSnapshot` в формате файла), `branch_analytics.rs`, `line_analytics.rs`, +`session.rs`, `StatsStore`, большая часть `stats.rs`. + +### 5.4. Сохранённые настройки 2.2.0/2.3.0 при удалении их из интерфейса + +Общее правило [Предложение]: **поля в `Settings` и типы в ядре оставить как есть** +(иначе §3.3 «Опасность»), новый UI их не читает, кроме цвета. + +| Сохранённое | Где действует сегодня | Что будет, если просто убрать из UI | Что сделать, чтобы не действовало скрыто | +|---|---|---|---| +| Цвет (`repertoire_modes[id].0`) | `select` (`repertoire_ui.rs:391–401`) | — | Продолжать читать и писать: это единственная оставшаяся настройка | +| Режим (`repertoire_modes[id].1`) | `select` → `self.queue` → `start` | Если новый код перестанет читать — не действует | Главная кнопка всегда создаёт SRS-сессию; при записи цвета сохранять `(цвет, SpacedRepetition)`. Значение `Practice` уже приводится к SRS (`settings.rs:253–267`) | +| Порядок (`repertoire_priorities[id]`) | `scope.with_learning_priority` (`repertoire_ui.rs:671–674`); входит в сравнение при возобновлении (`learning_training.rs:1529`) | Не действует, если scope строится с приоритетом по умолчанию | Всегда `LearningPriority::default()` (= `DepthFirst`); запись в поле прекратить, старые значения не стирать | +| Шесть параметров контекста (`repertoire_context_policies[id]`) | Копируются в новую сессию (`repertoire_ui.rs:677–681`, `learning_training.rs:235`) | Не действуют на **новые** сессии, если передавать `LearningContextPolicy::default()` | Всегда передавать значение по умолчанию. Упомянуть в CHANGELOG: у менявших параметры изменится показ подвода | +| Политика/порядок/режим **внутри незавершённой сессии** (`session_snapshots[]`) | `resume` (`learning_session.rs:312`) восстанавливает снимок со своей политикой (решение 04.11) | Возобновлённая сессия продолжит жить по старым параметрам — **скрытое состояние** до её конца | Возобновлять только сессии, у которых `context_policy == default`, `learning_priority == default` и режим ∈ {SRS, ReviewInOrder}; прочие не возобновлять и не удалять. Знание при этом не теряется: каждая попытка уже записана в `learning.items` отдельно от очереди, теряется лишь позиция в очереди, а несделанные повторения остаются «на сегодня». Менять политику у живого снимка снаружи не рекомендую: `validate` сверяет фазу с планом контекста (`learning_session.rs:717–733`) | +| `max_plies` (в `repertoires.json`) | UI передаёт в scope (`repertoire_ui.rs:1809–1814`); участвует в сравнении при возобновлении (`learning_training.rs:1526`) | Если новый код перестанет передавать — лимит **молча исчезнет**, вырастут «Y» и число новых; если продолжит — останется **скрытым** | (1) Продолжать передавать `Some(max_plies)`; (2) при конечном значении показывать явную строку с действием «Снять ограничение» (запись `u32::MAX`); (3) **новые** репертуары создавать без лимита — сегодня они получают 20 (§3.4): либо присваивать `u32::MAX` сразу после `create` в UI, либо поменять умолчание в `Library::create` (`model.rs:348`, тест `tests.rs:240`) — второе меняет ядро в одной строке и чище. Требует решения владельца: существующие репертуары 2.2.0/2.3.0 с лимитом 20 пользователь, скорее всего, не выбирал сам | +| `disabled_prefixes` | `only_active` в scope (`learning_graph.rs`, `path_allowed`) | Продолжают действовать | Оставить; должны быть видны в редакторе (как сейчас, `repertoire_editor.rs` `SetDisabled`) | +| `main_answer_overrides` | 2.2.0 — единственный тренируемый ответ; 2.3.0 — только порядок (`main:learning_graph.rs`, `preferred_children`) | Продолжают влиять на порядок | Оставить; при переписывании от `main` скрытого ограничения нет | +| `snapshots[]` (история по дням) | Пишется при открытии статистики (`LearningStore::record_snapshot`, `store.rs:468`) | Перестанут пополняться | Допустимо; данные остаются | + +## 6. Стратегия + +### 6.1. Варианты + +**(а) Новый UI-модуль поверх существующего ядра, старые UI-файлы удалить.** + +- Объём (грубо): удаляется ~13 700 строк UI (из них ~5 900 тестов). Пишется: + корневой экран (таблица, карточка, импорт/экспорт, «добавить из партии», сброс) — + 900–1 100 строк; экран задания — 700–900; редактор в сегодняшнем объёме функций — + 400–600 (с добавлением/удалением ходов на доске ещё +300–400); тесты UI — 1 500–2 000; + ядро — 100–150 + 200–300 тестов; i18n — 40–60 новых строк × 9 языков. + Итого ~4 000–5 000 новых строк против 13 700 удаляемых. +- Срок: 8–12 рабочих дней разработчика до сдачи на дизайн-ревью и QA; +2–3 дня, если + в объём входит правка ходов на доске. Это оценка, не замер. +- Риски: + 1. Потерять неочевидные исправления экрана задания: возврат фигуры при перетаскивании + во время записи (05.11), повтор уже показанного подвода (05.11, + `reuse_shown_context`, `learning_training.rs:506`), идемпотентный повтор записи + (`PendingCommit`, `retry_pending` `:985`), пакетная запись контекста (2.3.0). Смягчение: + перенести соответствующие тесты из `learning_training.rs` (2 040 строк тестов) как + приёмочные для нового экрана — тесты переносить раньше кода. + 2. Работать не от того кода (§0 п. 1). + 3. `i18n.rs` — большой общий файл; правки только добавлением строк. +- Плюсы: формат и ядро не меняются → данные 2.2.0/2.3.0 читаются как есть; Android и web + не затронуты; `app.rs` не меняется при сохранении контракта §4.1; число состояний + экрана задаётся заново, а не вычитается из 45 полей. + +**(б) Инкрементальная чистка существующих файлов.** + +- Объём: убрать дашборд, окно параметров, выбор режима/порядка, мёртвый файл; править + `repertoire_ui.rs` и `learning_training.rs` на месте. 3–5 дней. +- Риски: корневой экран остаётся с 45 полями и восемью фоновыми событиями, экран + задания — с двумя слоями автоматов; каждая из шести прошлых переделок шла именно так + и оставила слой. Новое поведение (показ нового хода, дозировка, конец занятия, + возврат ошибки) всё равно требует переписать основной цикл экрана задания. + Тесты `repertoire_ui_tests.rs` (1 727 строк) привязаны к нынешней компоновке и будут + ломаться на каждом шаге. +- Плюс: меньше одномоментных изменений. + +**(в) Переписать и ядро.** + +- Объём: ~8 300 строк ядра + 8 100 строк тестов, новая версия формата и миграция v3→v4 + с резервной копией, повторное прохождение AT. 4–6 недель. +- Риски: потеря или искажение пользовательского прогресса при миграции; регресс + идемпотентности и межпроцессной блокировки; пользователь ничего из этого не увидит. + Претензии владельца относятся к интерфейсу, не к расчётам (сверка 05.11 арифметических + дефектов не нашла). +- Не рекомендую. + +### 6.2. Рекомендация + +**Вариант (а)**, со следующими условиями: + +1. **База — `main` (2.3.0), а не текущая ветка.** До начала: владелец/оркестратор решает + судьбу незакоммиченных правок временных стрелок (закоммитить в свою ветку и перенести + на `main`). Документы аналитика и дизайнера сверить с решениями 06.11 из `main` + (несколько своих ответов). +2. **Ядро — только добавления** (§5.3 пп. 1, 4, тест к п. 6; возможно умолчание + `max_plies`). Формат файлов, имена вариантов enum, корневой API `trainer` не менять. +3. **`Settings` и `app.rs` не менять**; контракт `RepertoireUi` сохранить (§4.1). +4. **Порядок работ:** (1) добавления в ядро с тестами; (2) новый экран задания с + перенесёнными тестами записи/перетаскивания/подвода; (3) новый корневой экран; + (4) редактор; (5) удаление старых файлов одним коммитом; (6) дизайн-ревью на + снимках через dev-хуки `CP_REPERTOIRE*`, QA на копии профиля. +5. **Удаление мёртвого кода ядра** (`session.rs`, запись v2, большая часть `stats.rs`, + ~5 000 строк с тестами) — отдельной задачей после приёмки владельцем, 1–2 дня. + Перенос `QueueMode`/`TrainingMode` из `stats.rs` в живой модуль — тогда же. + Мёртвый линейный тренер в `game_view.rs` (§2.3) — отдельное решение: это экран партии. + +### 6.3. Не проверено + +- Сборки и тесты не запускались; утверждения о поведении — из чтения кода. +- §3.4 (лимит 20 полуходов у новых репертуаров) не подтверждён запуском приложения. +- Тренировка ветки через сессию (§5.3 п. 6) — нет теста, работоспособность выведена + из кода графа. +- Производительность записи и агрегатов на больших репертуарах не измерялась. +- UI-файлы `main` прочитаны выборочно (отличия от рабочего дерева — `learning_training.rs`, + `repertoire_editor.rs`, `repertoire_training.rs`); карта §1 построена по рабочему дереву. +- Сайт, пакеты и Android-клиент не смотрел. + +### 6.4. Вопросы + +1. Работаем от `main` (2.3.0)? Кто переносит незакоммиченные правки стрелок? +2. Лимит 20 полуходов у уже созданных репертуаров: показать с кнопкой «снять» или + снять автоматически, раз пользователь его не выбирал? +3. Входит ли в объём правка ходов на доске в редакторе (сегодня её нет)? +4. Незавершённые сессии 2.2.0/2.3.0 с нестандартными параметрами: не возобновлять + (рекомендация §5.4) или дать доиграть по старым параметрам? +5. Чтение файла v2 (не выпускался, есть на машине владельца): сохранять? diff --git a/docs/research/opening-trainer-rethink-2026-11-26.md b/docs/research/opening-trainer-rethink-2026-11-26.md new file mode 100644 index 0000000..5aa97ee --- /dev/null +++ b/docs/research/opening-trainer-rethink-2026-11-26.md @@ -0,0 +1,537 @@ +# Тренировка дебюта: переосмысление объёма раздела (2026-11-26) + +Статус: исследование аналитика, **не решение**. Код, ТЗ и другие документы не менялись. +Запрос владельца (слово пользователя, через оркестратора): раздел «Тренировка дебюта (α версия)» +не устраивает; цель — функционал, подобный , но +**проще и понятнее**; функции раздела можно удалять и дополнять; остальные разделы не трогать. + +Метки: **[Факт]** — проверено по источнику/коду/данным; **[Гипотеза]** — требует проверки; +**[Предложение]** — вариант решения. Источник требования помечается рядом. + +## 0. Что и как проверено + +| Источник | Как проверен 2026-11-26 | Результат | +|---|---|---| +| [M] ChessTempo User Guide, гл. 17 и §10.5 — | Загружен полный HTML (≈450 КБ текста), разделы 17.1–17.4.6, 17.15, 17.24, 17.25, 10.5 прочитаны дословно | **Проверено сегодня** | +| [P] Страница продукта — | Загружена | **Проверено сегодня** (только вводный текст; сам тренер за логином) | +| [F] Форум, блог, FAQ ChessTempo | Страницы отдают только оболочку, текст подгружается JavaScript; `webfetch` и `curl` содержимого не получили | **Сегодня не проверено.** Утверждения с меткой [F] взяты из исследования 02–04.11 (`docs/research/chesstempo-opening-trainer.md`, там ссылки S8–S21) и повторно не подтверждены | +| Живая тренировка в аккаунте ChessTempo | Не выполнялась (нужен логин) | **Не проверено.** Раскладка экрана, тексты кнопок во время задания, поведение на транспозиции вживую не наблюдались | +| Решения владельца | `docs/decisions.md` строки 267–480, `docs/dev/tasks.md` задачи 15, 24, 37, `docs/qa/*2026-11-05*`, `docs/design/opening-cleanup-2026-11-05.md` | Прочитано | +| Текущие функции | Код `apps/desktop/src/repertoire_*.rs`, `learning_*.rs`, строки `i18n.rs` | Выборочно, см. §3 | + +Подсчётов по PGN в этом исследовании нет; числа пользовательских данных ниже — цитаты +`docs/qa/learning-counts-and-parameters-2026-11-05.md` (снимок 05.11, не пересчитывались). + +## 1. ChessTempo: реальный путь пользователя + +### 1.1. Путь по шагам + +1. **Создать репертуар.** Кнопка New repertoire → имя + цвет (репертуар всегда либо белый, + либо чёрный) → Create. Либо Import PGN при создании. [Факт, M §17.1] +2. **Импорт PGN.** Несколько партий в файле = несколько линий одного репертуара. + Альтернативные ходы **своего** цвета в одной позиции по умолчанию импортируются + **выключенными** (можно включить или не импортировать). Комментарии импортируются. + Руководство прямо предупреждает не импортировать целые партии: миттельшпиль и эндшпиль + «не полезны для тренировки». [Факт, M §17.2] +3. **Добавить ходы.** Вне режима тренировки ход на доске сразу добавляется в выбранный + репертуар и сохраняется. Удаление/promote — правой кнопкой в дереве. [Факт, M §17.3] +4. **Запустить.** Две кнопки: **Train** (весь репертуар) и **Train branch** (только ниже + выбранного хода дерева). Если выбрать папку White или Black — тренируются все репертуары + цвета. Отдельного диалога запуска с параметрами нет: режим и приоритеты лежат в Settings. + [Факт, M §17.1, §17.4, §17.4.4] +5. **Задание.** Пользователь играет только цвет репертуара. Единица — один ход в одной + позиции. Перед заданием система может проиграть подводящие ходы как контекст: хорошо + известные пропускает, менее известные показывает (тем быстрее, чем лучше известны), а + «почти пора» — может попросить сыграть. [Факт, M §17.4.3 «Context for training moves»] +6. **Новый ход.** При первом показе правильный ход показан стрелкой (по умолчанию). + [Факт, M §17.4.1] +7. **Ошибка.** Правильный ход показывается, пользователь его играет и идёт дальше; это + повторение **не** считается верным ответом. Ошибочный ход ставится на повтор почти сразу + (по умолчанию через 30 с) — на практике после заданий, уже ожидавших в начале сессии. + [Факт, M §17.4.3, §17.15.2] +8. **Верный ответ.** Следующий показ отодвигается: первый успех +1 день, далее ×2 от + прошедшего интервала, максимум 1095 дней. [Факт, M §17.15.2] +9. **Что дальше.** Следующий ход выбирает расписание; по умолчанию просроченные сортируются + **по варианту**, чтобы меньше прыгать по репертуару. Когда просроченных нет, а + пользователь продолжает — вводится ещё не виденный ход в порядке Learning priority + (по умолчанию Depth first: главная линия до конца, затем её ответвления). [Факт, M §17.4.3, §17.15.2] +10. **Когда остановиться.** Счётчик Due под доской; при Due = 0 показана дата следующего + повтора. Рекомендация разработчика — останавливаться на Due = 0. [Факт о счётчике: M §10.5, + §17.4.2; рекомендация: F, сегодня не перепроверена] +11. **Статистика.** Сводка под доской; таблица по репертуарам `Learning / Learnt / Unseen / + Uncertain / Due(или дата)`; графики History (глобально), Scheduled и Sequences (по + репертуару) — через меню действий, не на основном экране. [Факт, M §10.5, §17.25] + +### 1.2. Режимы и настройки (полный перечень из руководства) + +- **Режимы (3):** Spaced repetition; Review in order; Least recent/unseen first. Два последних + тоже обновляют расписание. Review in order руководство **не рекомендует** как основной — + «для обзора перед турниром». [Факт, M §17.4.3] +- **Порядок ввода новых (4):** Depth first (по умолчанию), Breadth over depth, Main lines first, + Common positions first (нужны данные Opening Explorer). Влияет только на ввод новых ходов и + на порядок двух обзорных режимов. [Факт, M §17.4.3] +- **Basic:** режим; пауза в конце линии; три вида предпоказа стрелкой; показ своих комментариев; + приоритет; максимальная глубина. [Факт, M §17.15.1] +- **SRS (7):** сортировка просроченных, окно сортировки, gap growth, max days, mistake/initial/ + preview reschedule. [Факт, M §17.15.2] +- **Advanced:** leadup при тренировке ветки, Reinforce minimum correct, Reinforce minimum days, + Don't show start moves threshold, Move speed adjustment, Use fixed piece movement speed + (+ три настройки отображения движка/дерева). [Факт, M §17.15.3] +- **Прочее:** Resistant-наборы, транспозиции с общей историей позиции между репертуарами, + сброс обучения (затрагивает общие позиции во всех репертуарах), Reset Review Order, + экспорт PGN, закладки, sunburst, move list table, bulk disable, синхронизация с Explorer и + движком, интеграция с игрой онлайн. [Факт, M §17.4.5–17.24] + +### 1.3. Ядро и периферия + +**Ядро — без этого это не «как ChessTempo»** [Предложение аналитика на основе M]: + +1. Репертуар = дерево из PGN с **цветом**; играю только свой цвет, соперник отвечает из дерева. +2. Задание = **один ход**; новый ход сначала **показывают**, потом спрашивают. +3. На ошибке **сразу показан верный ход**; ход вернётся скоро. +4. Верные ответы отодвигают повтор; счётчик «сегодня осталось N» и ясный конец занятия. +5. Перед заданием — автоматический контекст (подводящие ходы), чтобы понимать, где я. +6. Одна кнопка запуска; тренировка ветки — вторая, необязательная. +7. Прогресс: сколько ходов выучено / учится / не видел. + +**Периферия** (у ChessTempo спрятана в Settings/меню, большинству не нужна): два обзорных +режима, четыре приоритета, 7 SRS-коэффициентов, 6 параметров контекста/скорости, глубина, +Resistant, графики History/Scheduled/Sequences, сравнение репертуаров, sunburst, закладки, +bulk disable, Explorer/движок, общая история между репертуарами (внутренний механизм, не UI). + +Наблюдение [Факт, M]: у ChessTempo все значения по умолчанию работают без единой настройки: +Create → ходы → Train. Сложность лежит **за** меню, а не на пути. Текущий раздел ChessPenguin +вынес периферию на путь (см. §3). + +### 1.4. Чего проверить не удалось + +- Точный вид экрана задания и подписи кнопок после ошибки (ранее — по пользовательскому видео + 2025 г.: `Expected: …`, зелёная стрелка, `Next`/`Finish`; сегодня не пересматривалось). +- Как именно тренировка продолжается после транспозиции; как выбирается ответ соперника среди + нескольких веток. +- Содержимое форума/блога/FAQ на сегодня (см. §0). +- Паритет мобильного приложения: руководство многократно помечает функции «Desktop only until + next app update». + +## 2. История претензий владельца + +### 2.1. Хронология (все записи — `docs/decisions.md`, если не указано иное) + +| Дата | Что сделала команда | Что сказал/отменил владелец | +|---|---|---| +| 25.10 (задача 15) | Линия «до этого хода», пользователь ходит за обе стороны | Принято; «подсказок нет, ошибки считаются» | +| 02.11 утро | Два режима, SRS, глубина 20 полуходов, disable веток, scope | Делегировал решения оркестратору | +| 02.11 после живой пробы | Целевой ход + «try again» | **Отверг**: «ход есть в репертуаре, но сейчас повторяется другой» — «непонятно, чего программа требует и как продолжить». Хочет: пройти ветку целиком, подсказка сразу, «Следующая ветка» по Enter | +| 03.11 | Режимы, глубина, область, дерево ходов | **Отменил** ручные параметры и расширенные режимы; убрал видимое дерево, нотацию в тренировке, колонки due, кнопки `⏮ ◀ ▶ ⏭`. Оставил: цвет, число вариантов, запуск. Случайный круг без повторов | +| 03.11 | Список и карточка — два экрана | **Отменил**: один экран, клик выбирает, запуск отдельной кнопкой | +| 03.11 | «Пути», «Готовим дерево», «Прежние линии» | Переименовал «Пути» → «Варианты»; «Готовим дерево» — непонятно; «Прежние линии» **удалил** как «непонятный и ненужный» | +| 03.11 | Вёрстка | Серия замечаний: выравнивание ECO, одинаковая ширина кнопок, фиксированная высота, никаких скачков; потребовал отдельного дизайн-ревьюера | +| 03.11 | Счётчик вариантов | Считать только исходные PGN-ветки; транспозиции не создают новые варианты | +| 04.11 | — | Подтвердил приоритет ТЗ ChessTempo (945 строк) **над своими же упрощениями** 02–03.11: SRS, LearningItem, дашборд, 6 параметров контекста | +| 05.11 | Реализация ТЗ | **Отклонил** как «перегруженную и непонятную»: «непонятные Total/Unseen», «техническая глубина» (`4294967295 полуходов`), «разнородные и разнесённые кнопки», «нечитаемые ветки», «ручное сохранение истории» | +| 05.11 | — | Убрать «Сохранение прогресса» на каждом ходе и вращающиеся индикаторы | +| 05.11 | Параметры контекста | Потребовал понятных подписей с единицами; «Минимум дней для закрепления» оказался понят неверно. Усомнился в счётчиках — QA арифметику подтвердил, т. е. **непонятен смысл числа, а не расчёт** | +| 05.11 | — | Повтор первого хода (автоконтекст выглядел как двойной вопрос); фигура «возвращалась» при сохранении; кнопка переворота не там | +| 05.11 | — | Назвал раздел «α версия» | +| 26.11 | — | Раздел в целом не устраивает; хочет «как ChessTempo, но проще и понятнее» | + +### 2.2. Устойчивые закономерности [Факт — повторяются ≥ 2 раз в журнале] + +1. **«Непонятно, что от меня хотят сейчас»** — главный отказ (02.11 try again; 05.11 счётчики; + 05.11 повтор первого хода). Любое состояние, где программа ждёт чего-то скрытого, отвергается. +2. **Настройки на пути к запуску отвергаются** (03.11 — все параметры; 05.11 — глубина, + параметры контекста). Принимается: выбрать репертуар → цвет → «Тренироваться». +3. **Термины модели данных отвергаются**: Total, Unseen, «полуходы», «Пути», «Готовим дерево», + «Прежние линии», «Минимум дней для закрепления». Принимаются слова «ходы», «варианты», + «изучено X из Y». +4. **Счёт в вариантах понятнее счёта в ходах-позициях** (03.11 выбрал «Варианты»; 05.11 усомнился + в счётчиках ходов). [Гипотеза: владелец мыслит линиями, а не позициями — проверить вопросом В2.] +5. **Визуальная дисциплина**: один экран, одна группа одинаковых кнопок, ничего не прыгает, + нет служебных уведомлений и спиннеров. +6. **Лишние сущности удаляются при первой встрече**, если их польза не очевидна за секунды + («Прежние линии», ручной снимок истории, кнопки навигации). +7. **Маятник.** Дважды владелец просил «как ChessTempo» (02.11, 04.11) и дважды отвергал + результат как сложный (03.11, 05.11). [Факт] Оба раза команда отвечала на «как ChessTempo» + **полнотой функций**, а не **опытом по умолчанию**. Сегодняшняя формулировка «как ChessTempo, + но проще» снимает противоречие, только если читать её как «ядро §1.3 без периферии». + +### 2.3. Чего он хочет [Гипотеза, выведена из 2.2; подтверждать вопросами §7] + +Открыл раздел → выбрал дебют и цвет → нажал одну кнопку → программа сама показывает новые ходы +и спрашивает старые → при ошибке сразу видно правильный ход → видно, сколько осталось сегодня +и сколько выучено всего → закончил. Никаких режимов, порядков, коэффициентов и терминов SRS. + +Противоречие, которое нельзя решить без владельца: 02–03.11 он требовал «любой ход из +репертуара принимается» и «пройти вариант целиком»; модель ChessTempo — «один конкретный ход». +В MVP 04.11 конфликт сглажен правилом «один основной ответ на позицию» (альтернатив своего +цвета в тренировке нет, значит и «try again» не возникает). Это правило нужно сохранить +в любом варианте ниже. + +## 3. Инвентаризация текущих функций и вердикты + +Источник [Факт]: пользовательские строки `tr("…")` в `apps/desktop/src/repertoire_ui.rs`, +`repertoire_editor.rs`, `learning_training.rs`, `learning_dashboard.rs`, `learning_branches.rs`, +`learning_charts.rs`, `learning_context_controls.rs` (чтение кода 26.11; приложение не +запускалось, снимки не снимались). Объём: desktop-UI раздела ≈ 14 тыс. строк, ядро +`crates/trainer/src/repertoire/` ≈ 16 тыс. строк с тестами (`wc -l`). + +Вердикты — [Предложение]; «удалить» везде означает **убрать из интерфейса**, данные и ядро +сохраняются (§6). + +### 3.1. Библиотека и подготовка + +| Функция сейчас | Вердикт | Обоснование | +|---|---|---| +| Единый экран: доска + карточка + таблица `Название / ECO / Варианты` | **Оставить** | Решение владельца 03.11; замечаний после 05.11 нет | +| Создать / Импорт PGN / Импорт в существующий / Экспорт / Переименовать / Удалить | **Оставить** | Ядро ChessTempo §1.1 шаги 1–2; сохранность PGN | +| «Добавить в репертуар…» из партии | **Оставить** | Требование владельца 02.11; аналог «ход на доске = ход репертуара» | +| Выбор цвета Белые/Чёрные на каждом запуске | **Упростить** | У ChessTempo цвет — свойство репертуара, задаётся один раз (M §17.1). Предложение: запоминать цвет за репертуаром (уже делается, 05.11) и показывать как свойство, а не как параметр запуска | +| Селектор «Режим» (По расписанию / По порядку / Сначала новые и давние) | **Удалить с пути** | Закономерность 2; у ChessTempo режим в Settings, а Review in order не рекомендован как основной (M §17.4.3) | +| Селектор «Порядок изучения» (4 приоритета) | **Удалить** | Закономерность 2; оставить один порядок по умолчанию — Depth first, как в ChessTempo. `Common positions first` без данных Explorer всё равно вырождается | +| Кнопка «Параметры» (окно: 6 параметров контекста + сброс + Reset Review Order) | **Удалить кнопку**; сброс перенести в меню репертуара | Закономерности 2 и 3; у ChessTempo это Advanced settings; владелец неверно понял параметр 05.11 | +| Сводка «Изучено X из Y ходов · Пора повторить · Ещё не изучали» | **Упростить** | Смысл чисел не считывается (сомнение в счётчиках 05.11). Предложение — одна строка под кнопкой: «Сегодня: N повторить, M новых» + полоса «Выучено X из Y» | +| «Тренировка: часть репертуара» (`max_plies`) | **Удалить из UI** новый ввод; существующий лимит уважать | Владелец отменил глубину 03.11 и назвал её «технической» 05.11. Данные не трогать (§6) | +| Подсказка «Нет заданий в этом режиме» / «Новые ходы вводятся только по запросу» | **Удалить** | Состояние «кнопка есть, а тренировать нечего» — закономерность 1. Кнопка должна всегда вести к понятному действию (§5) | + +### 3.2. Экран задания + +| Функция сейчас | Вердикт | Обоснование | +|---|---|---| +| Один основной ответ на позицию, соперник отвечает из дерева | **Оставить** | Ядро; исключает «try again», отвергнутый 02.11 | +| Показ нового хода перед вопросом (`PREVIEWED · replay the shown move; this is not an independent success.`) | **Оставить механику, переписать текст** | Ядро (M §17.4.1). Текст — язык модели данных (закономерность 3). Нужно: «Новый ход. Запомните и сыграйте его» | +| Ошибка: показ верного хода, повтор не считается (`Wrong move. Replay the revealed move; it will not count…`) | **Оставить механику, переписать текст** | Ядро (M §17.4.3). Нужно: «Неверно. Правильный ход — …. Сыграйте его» | +| Автоконтекст с адаптивной скоростью | **Оставить, фиксированные значения по умолчанию** | Ядро №5; значения ChessTempo (reinforce 3, skip 100 — [F], не перепроверено) | +| Кнопки Пауза / Стоп / Выход / Назад / Детали / Продолжить / Подсказка / Повтор | **Упростить** до: «Подсказка», «Закончить» (+ переворот внизу) | Закономерность 5 («разнородные кнопки»). Пауза нужна только чтобы читать комментарий — заменить остановкой после ошибки/нового хода до действия пользователя | +| Счётчик заданий сессии | **Оставить и усилить** | Ядро №4: «осталось N» и явный конец | +| NAG и стрелки PGN на доске, временные пометки правой кнопкой | **Оставить** | Решения 03.11 и 26.11 | +| Нотация в тренировке отсутствует | **Оставить как есть** | Решение 03.11, не отменялось | +| Комментарий PGN к ходу | **Добавить** показ после ответа/при показе нового хода | У ChessTempo «Show our move comments» (M §17.15.1); учебные PGN владельца содержат комментарии [Гипотеза о пользе — вопрос В5] | +| Итог занятия («Training complete») | **Упростить**: «Готово: N верно, M ошибок. Следующее повторение — завтра» | Ядро №4; рекомендация остановиться на Due = 0 | + +### 3.3. Статистика (дашборд) + +| Функция сейчас | Вердикт | Обоснование | +|---|---|---| +| Отдельный экран «Статистика тренировки» с фильтрами Репертуар/Сторона | **Удалить экран**; заменить блоком в карточке репертуара | У ChessTempo базовая сводка — под доской, графики — в меню (M §10.5, §17.25). Закономерности 2, 6 | +| Вкладки Обзор / Динамика / Расписание / Ходы + «Дополнительно» | **Удалить** | Отклонено 05.11 как перегруженное; после переделки осталось четыре вкладки | +| Графики History, Scheduled (Сегодня/7/30/365/Позже), Sequences | **Удалить из UI** (ядро и снимки истории оставить) | Периферия §1.3; ни одного запроса владельца на графики в журнале нет [Факт] | +| Таблица ходов с Accuracy / streak / Last at / Introduced / Found in / Wrong answers | **Удалить из UI** | Периферия; дублируется в редакторе | +| Branches / Lines («Варианты» в «Дополнительно») | **Удалить из UI** | «Нечитаемые ветки» 05.11; пересечения линий порождают числа, которые нельзя сложить | +| Сравнение всех репертуаров + «Всего без повторов» | **Удалить** | «Сумма строк ≠ итог» требует сноски — признак непонятности; закономерность 3 | +| Resistant | **Удалить из UI** | Периферия; SRS и так возвращает трудные ходы | +| Автоснимок истории раз в день | **Оставить в фоне** без UI | Не мешает; пригодится, если графики вернутся | + +### 3.4. Термины + +| Сейчас (EN / RU) | Вердикт | Предлагаемый показ | +|---|---|---| +| Total / «Ходов для изучения» | **Удалить как отдельное число** | Только знаменатель: «Выучено X из Y» | +| Unseen / «Ещё не изучали» | **Упростить** | «Новых: M» | +| Learning / «Закрепляем» | **Упростить** | «Учу: K» (или спрятать: Y − X − M) | +| Learnt / «Изучено» | **Оставить** | «Выучено: X» | +| Uncertain / «Давно не повторяли» | **Удалить из UI** | Такие ходы и так попадают в «Повторить сегодня» | +| Due / «Пора повторить» | **Оставить** — главное число | «Повторить сегодня: N» | +| Resistant, Confident %, Accuracy, streak, Introduced, Shared, Learning items, scope | **Удалить из UI** | Язык модели данных | + +Итог: три числа — **сегодня повторить**, **новых**, **выучено X из Y**. Инвариант +`Y = выучено + учу + новых` сохраняется в ядре [Факт, решение 04.11]. + +### 3.5. Редактор + +| Функция сейчас | Вердикт | Обоснование | +|---|---|---| +| Дерево PGN + доска, ход на доске добавляет ход | **Оставить** | Ядро ChessTempo (M §17.3); без редактора репертуар нельзя исправить | +| «Сделать основным ответом» | **Оставить** | Нужно для правила «один ответ»; аналог promote (M §17.3.1) | +| Отключить/включить ветку для тренировки | **Оставить**, подпись «Не тренировать эту ветку» | Единственный ответ на «длинные примерные партии» (M §17.2 предупреждает о них) | +| Глубина («Depth», «plies», «No depth limit») | **Удалить из UI** | «Техническая глубина» 05.11; отмена 03.11 | +| Панель «Move analytics» (Accuracy, streaks, Response median, Next due, Wrong moves) | **Удалить из UI** | Периферия; «не создавать вторую копию статистики» (дизайн 05.11) | + +### 3.6. Сброс + +| Функция сейчас | Вердикт | Обоснование | +|---|---|---| +| «Сбросить прогресс…» с перечнем затронутых репертуаров и галочкой «понимаю» | **Оставить, упростить текст**, перенести в меню `⋯` репертуара | Нужен (M §17.24.3); общий прогресс — факт модели, предупреждение обязательно, но короткое: «Общие ходы сбросятся и в: A, B» | +| «Reset Review Order» | **Удалить** | Исчезает вместе с режимом «По порядку» | + +### 3.7. Прочее + +- `repertoire_training.rs` (1557 строк, строки «Next variation», «Repeat path», «Several + continuations…») — прежний «проход вариантов» 02–03.11. [Гипотеза: из UI уже недостижим — + в `repertoire_ui.rs`/`app.rs` ссылок `repertoire_training::` поиском не найдено; разработчику + подтвердить.] Вердикт зависит от В1 (§7). +- Режим «за обе стороны» в новом UI отсутствует (`TrainingMode::Both` сводится к белым, + `repertoire_ui.rs:397`) [Факт]. В ChessTempo его нет (F, 2022; сегодня не перепроверено). + +## 4. Варианты целевого объёма + +Общее для всех вариантов [Предложение]: ядро `crates/trainer` (LearningItem, SRS, хранилище, +миграции) **не переписывается**; переписывается desktop-UI раздела. Внутри ядра остаются +режимы, приоритеты, политика контекста, агрегаты и снимки — UI просто перестаёт их показывать +и всегда передаёт значения по умолчанию. Это делает любой вариант обратимым. + +### Вариант A — «Минимум» + +**Состав.** Библиотека как сейчас → карточка репертуара: цвет, три числа, одна кнопка +«Тренироваться» → задание (новый ход показывают, старый спрашивают, на ошибке показывают +ответ) → «Готово». Редактор: дерево, добавить ход, основной ответ, «не тренировать ветку». +Сброс в меню `⋯`. Ничего больше: ни режимов, ни порядков, ни параметров, ни экрана +статистики, ни тренировки ветки. + +- **Цена:** наименьшая. Новый код — карточка и экран задания; остальное удаляется из UI. +- **Риски:** (1) нет способа «прогнать весь дебют перед турниром» — именно это владелец просил + 02–03.11 («пройти варианты целиком»); вероятен запрос на возврат. (2) Большой импортированный + PGN можно ограничить только отключением веток в редакторе. +- **Отменяет решения владельца:** см. таблицу §4.1, столбец A. + +### Вариант B — «Рекомендуемый» + +**Состав = A плюс четыре вещи, каждая закрывает зафиксированную потребность:** + +1. **«Повторить всё подряд»** — вторичное действие (пункт меню `⋯` или текстовая ссылка под + основной кнопкой, не вторая большая кнопка). Проходит весь репертуар вариант за вариантом, + главная линия первой; ответы учитываются в расписании. Это Review in order + Depth first + (M §17.4.3: «для обзора перед турниром») и одновременно ответ на требование 02–03.11. +2. **«Тренировать эту ветку»** в редакторе на выбранном ходе (Train branch, M §17.1). +3. **Комментарий PGN** к ходу — после ответа и при показе нового хода (M §17.15.1). +4. **Дозированный ввод новых:** занятие = все «повторить сегодня» + не более 10 новых ходов + (число фиксировано, настройки нет); в конце — «Готово» и ссылка «Ещё 10 новых». + У ChessTempo порции нет — там новое вводится, пока пользователь продолжает (M §17.4.3); + это наше упрощение ради ясного конца занятия [Предложение; число 10 — гипотеза, вопрос В6]. + +- **Цена:** A + примерно треть сверху (оба дополнительных запуска уже есть в ядре: режим + Review in order и line/branch-scope реализованы и приняты 04–06.11 [Факт, задача 37]). +- **Риски:** (1) «Повторить всё» — второй режим; если он выглядит как равноправный выбор, + вернётся претензия «непонятно, что выбрать». Смягчение: он не на карточке, а в меню. + (2) Комментарий может выдать ответ на следующий ход — показывать только к уже сыгранному ходу. + (3) Пользователи 2.2.0, менявшие режим/параметры, потеряют доступ к настройке (§6.4). +- **Отменяет решения владельца:** см. §4.1, столбец B. + +### Вариант C — «Близко к полному ChessTempo» + +**Состав.** Весь нынешний набор сохраняется (3 режима, 4 порядка, 6 параметров, статистика с +графиками, варианты, resistant), но периферия уезжает в одно окно «Настройки тренировки» и в +меню «Статистика», как у ChessTempo; путь по умолчанию — как в B. + +- **Цена:** наибольшая: всё надо перепроектировать, а не удалить; полная матрица визуальной + приёмки по всем экранам. +- **Риски:** тот же состав отклонён 05.11 как перегруженный, а после переделки компоновки в тот же день раздел в целом отклонён 26.11. Вероятность третьего + отказа высокая [Гипотеза, основана на закономерностях 2, 3, 6]. Каждый спрятанный экран — + всё равно экран, который владелец откроет и оценит. +- **Отменяет:** только компоновку 05.11. + +### 4.1. Какие подтверждённые решения отменяет каждый вариант + +Требуют **явного переподтверждения владельцем**. «—» = решение сохраняется. + +| Решение (дата в `docs/decisions.md`) | A | B | C | +|---|---|---|---| +| ТЗ ChessTempo имеет приоритет над упрощениями; AT-01…30 обязательны (04.11) | Отменяется в части UI (режимы, дашборды, контекст-настройки); AT ядра остаются | То же, кроме Review in order | — | +| Review in Order / Least Recent как режимы (04.11) | Оба убраны из UI | Least Recent убран; Review in order = «Повторить всё» | — | +| Четыре Learning priority (04.11) | Отменяется (всегда Depth first) | Отменяется | — | +| Шесть параметров контекста на репертуар, collapsed-блок/окно (04.11, 05.11) | Отменяется | Отменяется | Перенос | +| Dashboard: Details/Global, вкладки History/Scheduled/Sequences (04.11); вкладки Обзор/Динамика/Расписание/Ходы (05.11) | Отменяется | Отменяется | Перенос | +| Branches/Lines, Uncertain/Resistant в UI (04.11) | Отменяется | Отменяется | — | +| `max_plies` в редакторе ограничивает scope (04.11); явный переключатель «без ограничения» (05.11) | Ввод убран; существующий лимит см. §6.3 | То же | — | +| Строка трёх равных кнопок «Тренироваться / Параметры / Статистика» (05.11) | Отменяется (одна кнопка) | Отменяется | Отменяется | +| «Если заданий нет — подсказка выбрать режим» (05.11) | Отменяется | Отменяется | — | +| Подсказка по запросу после третьей ошибки (25.10, 02.11) | Уже заменено показом ответа на ошибке (04.11) — зафиксировать явно | То же | То же | + +**Не затрагиваются ни одним вариантом:** общий LearningItem по `(FEN4, ход)`, константы SRS, +«выучено = 3 верных подряд», один основной ответ, общий сброс с предупреждением, хранилище и +миграции (04.11); единый экран, таблица с ECO, «Варианты», отсутствие нотации и кнопок +навигации в тренировке, NAG/стрелки (03.11); тихое сохранение, общая кнопка настроек, +пометка α, поведение перетаскивания (05.11); Android на legacy API (02.11). + +### 4.2. Рекомендация + +**Вариант B.** Обоснование: A не закрывает дважды высказанное желание «пройти дебют целиком»; +C повторяет отклонённый состав. B = ядро §1.3 + две функции, которые ChessTempo держит на +первом экране (Train branch) или сам рекомендует для конкретной ситуации (Review in order), +и обе уже есть в ядре. Если владелец сомневается — начать с A: он является строгим +подмножеством B, работа не пропадёт. + +## 5. Вариант B: сценарий и критерии приёмки + +### 5.1. Основной сценарий + +1. Главный экран → «Тренировка дебюта (α версия)». Слева доска, справа карточка выбранного + репертуара и таблица репертуаров (как сейчас). +2. Нет репертуаров: текст «Создайте репертуар или импортируйте PGN» и две кнопки. +3. Импорт PGN → репертуар появляется в таблице и выбран. Карточка: + `Испанская · играю белыми [сменить]` / `Сегодня: 0 повторить · 10 новых` / + `Выучено 0 из 25 ходов` + полоса / **[ Тренироваться ]**. +4. «Тренироваться». Программа проигрывает подводящие ходы, затем: «Новый ход. Запомните и + сыграйте: стрелка». Пользователь играет ход по стрелке; соперник отвечает; следующий ход. +5. Позже тот же ход приходит без стрелки: «Ваш ход». Верно — короткое «Верно», дальше. +6. Неверно — фигура возвращается, «Неверно. Правильный ход — Сb5» + стрелка; пользователь + играет его; ход вернётся в этом же занятии. +7. Сверху всё время «Осталось: N». При N = 0 — «Готово на сегодня. Верно 14, ошибок 2. + Следующее повторение — завтра» и кнопки «К репертуару» (Enter), «Ещё 10 новых» (если есть). +8. На следующий день карточка показывает «Сегодня: 12 повторить · 10 новых». +9. Перед турниром: меню `⋯` → «Повторить всё подряд» → те же правила ответа, порядок по вариантам, + счётчик «Вариант 3 из 9». +10. Исправить репертуар: `⋯` → «Редактировать» → ход на доске добавляет ход; правый клик по ходу: + «Сделать основным», «Не тренировать эту ветку», «Тренировать эту ветку», «Удалить». + +Сквозные ветки сценария: выход посреди занятия (уже данные ответы сохранены, занятие можно +продолжить); репертуар изменён в редакторе (прогресс неизменных ходов сохраняется, новые — +«новые»); экспорт PGN → импорт обратно (дерево, комментарии, NAG, FEN те же; прогресс общих +ходов подхватывается по `(позиция, ход)`); ошибка записи на диск (видимое сообщение и +«Повторить», ответ не считается сохранённым). + +### 5.2. Критерии приёмки (наблюдаемые) + +Источник каждого: З — закономерность §2.2; M — руководство ChessTempo; Р — решение в +`docs/decisions.md`; И — инвариант AGENTS.md. + +**Путь и ясность** + +1. От открытия раздела с готовым репертуаром до первого задания — **один клик** + («Тренироваться»); между ними нет диалогов и выбора. [З2] +2. На карточке репертуара ровно один primary-элемент и не более **трёх чисел**; на экране нет + слов Total, Unseen, Due, Uncertain, Resistant, scope, «полуходы», «элементы», «по + расписанию» — проверка поиском по строкам RU/EN раздела и по снимкам. [З3] +3. Нет селекторов режима и порядка, нет кнопок «Параметры» и «Статистика»; в разделе нет + экранов с вкладками и графиками — проверка по снимкам всех состояний. [З2, З6] +4. Кнопка «Тренироваться» активна всегда, когда в репертуаре есть хотя бы один тренируемый ход + выбранного цвета. Если «повторить сегодня» = 0 и новых = 0, нажатие начинает досрочное + повторение, а карточка заранее пишет «На сегодня всё. Следующее повторение — <дата>». [З1] +5. В любой момент задания на экране есть одна строка, отвечающая на вопрос «что делать сейчас»: + «Смотрите ходы…» / «Новый ход — сыграйте его» / «Ваш ход» / «Неверно. Правильный ход — X, + сыграйте его» / «Готово». Проверка: снимок каждого из пяти состояний. [З1] + +**Механика (совпадение с ядром ChessTempo)** + +6. Пользователь двигает только фигуры своего цвета; ходы соперника делает программа и только + из дерева репертуара. [M §17.4; Р 04.11] +7. Ход, впервые попавший в занятие, показан стрелкой до ответа; сыграв его, пользователь **не** + увеличивает «выучено». [M §17.4.1; Р 04.11] +8. После неверного хода правильный показан сразу (текст + стрелка), без счётчика попыток и без + кнопки «показать». Тот же ход спрашивается снова до конца этого занятия. [M §17.4.3] +9. Три самостоятельных верных ответа подряд на один ход в разных показах увеличивают «Выучено» + на 1; ошибка уменьшает обратно. Проверка сценарием с подменой времени. [Р 04.11] +10. Ход, на который ответили верно сегодня впервые, не входит в «повторить сегодня» до + следующего дня; после второго успеха — не раньше удвоенного интервала. [M §17.15.2] +11. Занятие содержит все «повторить сегодня» и не более 10 новых; счётчик «Осталось» убывает + до 0 и занятие завершается само экраном итога. [Предложение B-4] +12. Автоматически показанный подводящий ход не спрашивается повторно как первый вопрос + (регрессия 05.11 «повтор первого хода»). [Р 05.11] +13. «Повторить всё подряд» проходит каждый включённый ход цвета ровно один раз за круг, + вариант за вариантом начиная с главной линии; ошибки в нём попадают в «повторить сегодня». + [M §17.4.3] +14. «Тренировать эту ветку» спрашивает только ходы ниже выбранного. [M §17.1] +15. Отключённая ветка не спрашивается, не входит в Y «Выучено X из Y», остаётся в редакторе и в + экспорте PGN. [Р 02.11; M §17.3] +16. Комментарий PGN виден только для уже сыгранного хода; до ответа комментарий к ожидаемому + ходу не виден. [M §17.15.1; риск спойлера] + +**Данные и инварианты** + +17. После обновления с 2.2.0 на копии реального профиля: числа «выучено / учу / новых» по + каждому репертуару и цвету совпадают с рассчитанными ядром 2.2.0 на тех же файлах + (методика — как в `docs/qa/learning-counts-and-parameters-2026-11-05.md`). [Сохранность] +18. Файлы PGN-репертуаров после запуска, тренировки и выхода побайтово равны исходным + (SHA-256 до/после), если пользователь не редактировал репертуар. [И] +19. Репертуар с конечным `max_plies` из 2.2.0: тренируется та же часть, на карточке видно + «Тренируется часть репертуара · [Снять ограничение]»; молча лимит не снимается и не + теряется. [Р 03.11 «не ограничивать скрыто»; Р 05.11 «не терять лимит»] +20. Незавершённое занятие из 2.2.0 продолжается после обновления без потери ответов. [Р 04.11] +21. Сброс прогресса: до подтверждения показано, какие другие репертуары затронет; после — + «Выучено 0 из Y», PGN не изменён. [Р 04.11] +22. Импорт PGN с веткой, содержащей `--`, со стартом из FEN (включая fullmove = 0) и с ходом + чёрных первым: импорт завершается, ветка с `--` не спрашивается, экспорт её сохраняет. + [И; проверка на файлах из копии `pgnFilesforExample/` — сегодня **не выполнялась**] +23. Импорт большого PGN и подготовка занятия не блокируют окно: во время операции окно + перерисовывается и реагирует на «Отмена». [И] +24. Android: `cargo test -p mobile-api -p trainer` зелёные; публичный API `trainer::{TrainStart, + Training, Verdict, LineStats, set_file, runs_to}` не изменён (сравнение сигнатур). [Р 02.11] +25. Другие разделы: `git diff --stat` не содержит файлов вне раздела тренировки, кроме i18n-строк + раздела. [Слово владельца 26.11] + +**Визуальная приёмка** — отдельным дизайн-ревьюером на реальных снимках 960×600 и 1400×900, +обе темы, сравнение с экраном партии, отсутствие скачков при появлении данных. [AGENTS.md; Р 04.11] + +## 6. Ограничения, которые нельзя нарушить + +1. **Инварианты AGENTS.md:** исходные PGN не меняются без явного действия; дерево вариантов, + FEN, комментарии, NAG сохраняются; `--` не становится обычным ходом; тяжёлые операции вне + UI-потока; запись атомарна, ошибки видимы. +2. **Данные 2.2.0 уже у пользователей.** [Факт: выпуск 06.11.] Хранилище обучения + (`learning.json` — имя по коду desktop; файл библиотеки репертуаров и legacy `training.json`/ + `stats.json` — см. `crates/trainer/src/repertoire/store.rs`, точные имена подтвердить + разработчику) должно читаться новой версией без потери. Упрощение UI **не требует** смены + формата; рекомендация — формат не менять вообще. Если менять — версия + backup перед первой + записью, как решено 04.11. +3. **Скрытые ограничения.** Сохранённые `max_plies` и отключённые ветки продолжают действовать; + раз ввод глубины убирается, существующий конечный лимит обязан быть виден и снимаем (кр. 19). +4. **Сохранённые предпочтения режима/порядка/политики контекста** (per-repertoire, 2.2.0). + [Предложение] Значения в файле не удалять; новые занятия используют значения по умолчанию; + начатое занятие сохраняет свой snapshot (Р 04.11). Последствие: у пользователя, менявшего + параметры, поведение контекста изменится без его действия — упомянуть в CHANGELOG. + Альтернатива — продолжать уважать сохранённые значения без UI — создаёт ненастраиваемое + скрытое состояние; не рекомендую. +5. **Android** использует legacy API `crates/trainer` (`TrainStart`, `Training`, `Verdict`, + `LineStats`, `set_file`, `runs_to` — `crates/mobile-api/src/train.rs:10,17,144` [Факт]) и + `training.json`. Этот API и формат не менять; удаление «мёртвого» кода ядра — только после + проверки, что `mobile-api` его не использует. +6. **Другие разделы не трогать.** Общие виджеты (доска, настройки) — только через существующие + интерфейсы. В рабочем дереве сейчас есть незакоммиченные правки `board.rs` и др. + (временные пометки 26.11) [Факт, `git status`] — переписывание не должно их затереть. +7. **Удаление из UI ≠ удаление из ядра.** Агрегаты, снимки истории, режимы остаются и + покрыты тестами; удалять код ядра — отдельным решением после приёмки владельцем. + +## 7. Открытые вопросы к владельцу + +Только те, где ответ меняет решение. + +- **В1. Единица тренировки.** (а) Один ход, как в ChessTempo: программа сама выбирает, какой ход + спросить, подводит к нему и спрашивает; дебют целиком — отдельным «Повторить всё подряд» + [рекомендую, вариант B]. (б) Всегда проход варианта от начала до конца (ваш сценарий 02–03.11): + понятнее, но это не ChessTempo, расписание повторений становится грубым (по вариантам), + длинные варианты утомляют. Ответ определяет весь экран задания. +- **В2. В чём считать прогресс.** (а) В ходах: «Выучено 17 из 22 ходов» [рекомендую — так считает + ядро и ChessTempo]. (б) В вариантах: «Выучено 3 из 9 вариантов» — привычнее по таблице, но + общие начала вариантов делают число условным. Можно (а) на карточке и «Варианты» в таблице, + как сейчас. +- **В3. Экран статистики и графики** — убрать полностью, оставить три числа на карточке? + (Да → A/B. Нет → назовите, какой один график нужен; это уже шаг к C.) +- **В4. Настройки тренировки** (режимы, 4 порядка, 6 параметров показа ходов) — убрать совсем, + без «расширенного» окна? Последствие: изменить скорость показа подводящих ходов можно будет + только общей настройкой анимации приложения. +- **В5. Комментарии из PGN во время тренировки** — показывать после хода? (Да → B-3; нет → экран + задания ещё проще.) +- **В6. Порция новых ходов за занятие** — фиксированные 10 с кнопкой «Ещё 10»? Или вводить все + новые подряд, пока не остановитесь (как ChessTempo)? +- **В7. Режим «ходить за обе стороны»** в новом разделе не возвращаем (в ChessTempo его нет)? + Android остаётся со старым тренером линии — подтверждаете? +- **В8. Переподтверждение отмен** из таблицы §4.1 для выбранного варианта — одним ответом + («B, отмены принимаю») достаточно. + +## 8. Отчёт + +**Выводы.** [Факт] ChessTempo по умолчанию — это «создал → Train → показали новый ход → +спросили → на ошибке показали ответ → Due = 0»; три режима, четыре порядка и два десятка +настроек лежат за меню. [Факт] Владелец неоднократно (02.11, 03.11, 05.11, 26.11 — см. §2.1) отклонял раздел по одним и тем же причинам: +скрытые ожидания программы, настройки на пути, термины модели, лишние сущности. [Факт] Дважды +«как ChessTempo» было реализовано как полнота функций и дважды отклонено. [Предложение] +Вариант B: одна кнопка, три числа, показ ответа на ошибке, «Повторить всё подряд» и «Тренировать +ветку» как вторичные действия; ядро и формат данных не менять. [Гипотеза] Владелец мыслит +вариантами, а не ходами-позициями — проверить В1/В2 до проектирования. + +**Изменённые файлы.** Только `docs/research/opening-trainer-rethink-2026-11-26.md` (создан). + +**Не выполнено / ограничения исследования.** Форум, блог и FAQ ChessTempo сегодня не +перепроверены (JS-страницы); живая тренировка в аккаунте не запускалась; приложение +ChessPenguin не запускалось, инвентаризация — по строкам кода; проверок на PGN из +`pgnFilesforExample/` не было; достижимость `repertoire_training.rs` из UI не доказана. + +**Что нужно от других ролей.** +- Оркестратор: получить от владельца ответы В1–В8 до начала дизайна. +- Дизайнер: после ответов — один экран карточки и один экран задания с пятью состояниями + (кр. 5); словарь из трёх чисел; без новых документов-надстроек над `repertoire-training.md` + (988 строк с 23 разделами отменяющих друг друга правил — предложить заменить одним коротким). +- Разработчик: подтвердить, что UI может вызывать ядро с фиксированными режимом/порядком/ + политикой без изменения формата; точные имена файлов хранилища; достижимость + `repertoire_training.rs`; способ реализовать порцию «10 новых» поверх текущей сессии. +- Тестировщик: подготовить копию профиля 2.2.0 для кр. 17–20; набор PGN для кр. 22; сравнение + сигнатур legacy API для кр. 24. From 3db35e4d039142e0165fe0dd26dc82d872145e19 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Thu, 26 Nov 2026 16:47:16 +0300 Subject: [PATCH 02/31] trainer: daily session (due + N new), mistakes return in the session, one-pass and branch review - LearningSessionSnapshot::new_daily: every due move and at most N unseen, PGN order - introduce_more: the next N unseen after a finished daily session - a move answered after a mistake or a hint goes back to the end of the queue; preview_new shows a new move without bringing it back - new_single_pass_review / new_branch_review: one pass, lines through a move - optional snapshot flags (absent when unused, old files read as before) --- crates/trainer/src/repertoire/daily_tests.rs | 450 ++++++++++++++++++ .../src/repertoire/learning_session.rs | 188 ++++++++ crates/trainer/src/repertoire/mod.rs | 2 + 3 files changed, 640 insertions(+) create mode 100644 crates/trainer/src/repertoire/daily_tests.rs diff --git a/crates/trainer/src/repertoire/daily_tests.rs b/crates/trainer/src/repertoire/daily_tests.rs new file mode 100644 index 0000000..8b72827 --- /dev/null +++ b/crates/trainer/src/repertoire/daily_tests.rs @@ -0,0 +1,450 @@ +//! Daily sessions (due + N new), mistakes coming back in the same session, one-pass +//! review and sessions limited to a branch. + +use super::*; + +const NOW: i64 = 1_800_000_000; +const PGN: &str = "1. e4 e5 2. Nf3 Nc6 3. Bb5 (3. Bc4 Bc5) a6 4. Ba4 *"; + +fn library(pgn: &str) -> (Library, RepertoireId) { + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + (library, id) +} + +fn key_for(library: &Library, scope: &StatsScope, expected_uci: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected_uci) + .unwrap() + .key +} + +fn queue_moves(session: &LearningSessionSnapshot) -> Vec<&str> { + session + .queue + .iter() + .skip(session.current_index) + .filter(|target| !session.completed_keys.contains(&target.key)) + .map(|target| target.key.expected_uci.as_str()) + .collect() +} + +/// Plays the automatic context up to the question, applying every event. +fn to_question( + session: &mut LearningSessionSnapshot, + library: &Library, + learning: &mut LearningData, +) { + let mut step = 0; + while session + .presentation_with_learning(library, learning) + .unwrap() + .phase + == LearningSessionPhase::AdvancingContext + { + step += 1; + let attempt = session + .advance_context_with_learning( + library, + learning, + format!("ctx-{step}-{}", session.revision), + NOW, + ) + .unwrap(); + session.revision += 1; + learning + .apply_attempt(attempt, &SrsSettings::default()) + .unwrap(); + } +} + +fn answer( + session: &mut LearningSessionSnapshot, + library: &Library, + learning: &mut LearningData, + uci: &str, + id: &str, +) -> TrainingAttempt { + let attempt = session + .play_uci_with_learning(library, learning, uci, id, NOW, Some(1000)) + .unwrap(); + learning + .apply_attempt(attempt.clone(), &SrsSettings::default()) + .unwrap(); + attempt +} + +#[test] +fn daily_queue_takes_every_due_move_and_at_most_n_new_in_pgn_order() { + let (library, id) = library(PGN); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + // Due deep in the line, known and not due early in it. + for (uci, next) in [("f1b5", NOW - 10), ("e2e4", NOW + 3600)] { + let item = learning.ensure_item(key_for(&library, &scope, uci)); + item.introduced = true; + item.next_review_at = Some(next); + } + let session = LearningSessionSnapshot::new_daily( + "daily", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 2, + ) + .unwrap(); + // Own moves in PGN order: e4 Nf3 Bb5 Ba4 Bc4. Due: Bb5. New: Nf3, Ba4 (2 of 3). + assert_eq!(queue_moves(&session), ["g1f3", "f1b5", "b5a4"]); + assert!(session.return_mistakes); + assert_eq!(session.session.mode, QueueMode::SpacedRepetition); + let all = LearningSessionSnapshot::new_daily( + "daily-all", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 10, + ) + .unwrap(); + assert_eq!(queue_moves(&all), ["g1f3", "f1b5", "b5a4", "f1c4"]); + let none = LearningSessionSnapshot::new_daily( + "daily-none", + &library, + &learning, + scope, + SrsSettings::default(), + 0, + ) + .unwrap(); + assert_eq!(queue_moves(&none), ["f1b5"]); +} + +#[test] +fn a_mistake_comes_back_in_the_same_session_and_a_shown_new_move_does_not() { + let (library, id) = library("1. e4 e5 2. Nf3 Nc6 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + let e4 = key_for(&library, &scope, "e2e4"); + let item = learning.ensure_item(e4.clone()); + item.introduced = true; + item.next_review_at = Some(NOW); + let mut session = LearningSessionSnapshot::new_daily( + "return", + &library, + &learning, + scope, + SrsSettings::default(), + 10, + ) + .unwrap(); + assert_eq!(queue_moves(&session), ["e2e4", "g1f3"]); + assert_eq!(session.remaining(), 2); + assert!(!session.current_is_new(&learning)); + + let wrong = answer(&mut session, &library, &mut learning, "d2d4", "wrong"); + assert_eq!(wrong.event_type, TrainingEventType::IncorrectIndependent); + assert_eq!( + session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + assert_eq!(session.remaining(), 2); + let replay = answer(&mut session, &library, &mut learning, "e2e4", "replay"); + assert_eq!(replay.event_type, TrainingEventType::ReplayAfterError); + // e4 is not done: it waits behind Nf3. + assert_eq!(queue_moves(&session), ["g1f3", "e2e4"]); + assert_eq!(session.remaining(), 2); + assert!(!session.completed_keys.contains(&e4)); + session.validate(&library).unwrap(); + + to_question(&mut session, &library, &mut learning); + assert!(session.current_is_new(&learning)); + let shown = session.preview_new("show-nf3", NOW).unwrap().unwrap(); + assert_eq!(shown.event_type, TrainingEventType::Previewed); + assert!(session.showing_new); + learning + .apply_attempt(shown, &SrsSettings::default()) + .unwrap(); + let played = answer(&mut session, &library, &mut learning, "g1f3", "play-nf3"); + assert_eq!(played.event_type, TrainingEventType::AutoContext); + // A shown new move is played once and counts as done. + assert_eq!(queue_moves(&session), ["e2e4"]); + assert_eq!(session.remaining(), 1); + assert!(!session.showing_new); + + let correct = answer(&mut session, &library, &mut learning, "e2e4", "second-try"); + assert_eq!(correct.event_type, TrainingEventType::CorrectIndependent); + assert_eq!(session.phase, LearningSessionPhase::Finished); + assert_eq!(session.remaining(), 0); + let item = learning.item(&e4).unwrap(); + assert_eq!((item.wrong_count, item.correct_count), (1, 1)); + session.validate(&library).unwrap(); +} + +#[test] +fn a_hint_comes_back_but_not_in_a_one_pass_review() { + let (library, id) = library("1. e4 e5 2. Nf3 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + for uci in ["e2e4", "g1f3"] { + let item = learning.ensure_item(key_for(&library, &scope, uci)); + item.introduced = true; + item.next_review_at = Some(NOW); + } + let mut daily = LearningSessionSnapshot::new_daily( + "hint-daily", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 10, + ) + .unwrap(); + daily.preview("hint", NOW).unwrap().unwrap(); + assert!(!daily.showing_new); + answer(&mut daily, &library, &mut learning, "e2e4", "after-hint"); + assert_eq!(queue_moves(&daily), ["g1f3", "e2e4"]); + + let mut review = LearningSessionSnapshot::new_single_pass_review( + "hint-review", + &library, + &learning, + scope, + SrsSettings::default(), + ) + .unwrap(); + assert!(!review.return_mistakes); + answer(&mut review, &library, &mut learning, "d2d4", "review-wrong"); + answer( + &mut review, + &library, + &mut learning, + "e2e4", + "review-replay", + ); + assert_eq!(queue_moves(&review), ["g1f3"]); +} + +#[test] +fn one_pass_review_finishes_instead_of_starting_a_new_cycle() { + let (library, id) = library("1. e4 e5 2. Nf3 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + let mut review = LearningSessionSnapshot::new_single_pass_review( + "single", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + ) + .unwrap(); + assert_eq!(review.session.mode, QueueMode::ReviewInOrder); + assert_eq!(queue_moves(&review), ["e2e4", "g1f3"]); + answer(&mut review, &library, &mut learning, "e2e4", "single-e4"); + to_question(&mut review, &library, &mut learning); + answer(&mut review, &library, &mut learning, "g1f3", "single-nf3"); + assert_eq!(review.phase, LearningSessionPhase::Finished); + assert_eq!(review.cycle, 0); + review.validate(&library).unwrap(); + + // The old looping review is unchanged. + let mut looping = LearningSessionSnapshot::new_with_mode( + "loop", + &library, + &learning, + scope, + SrsSettings::default(), + QueueMode::ReviewInOrder, + ) + .unwrap(); + answer(&mut looping, &library, &mut learning, "e2e4", "loop-e4"); + to_question(&mut looping, &library, &mut learning); + answer(&mut looping, &library, &mut learning, "g1f3", "loop-nf3"); + assert_eq!(looping.cycle, 1); + assert_ne!(looping.phase, LearningSessionPhase::Finished); +} + +#[test] +fn introduce_more_takes_the_next_unseen_moves_only() { + let (library, id) = library(PGN); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let mut learning = LearningData::default(); + let mut session = LearningSessionSnapshot::new_daily( + "more", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + 2, + ) + .unwrap(); + assert_eq!(queue_moves(&session), ["e2e4", "g1f3"]); + assert_eq!( + session.introduce_more(&library, &learning, 2), + Err(LearningSessionError::IntroductionRequiresFinished) + ); + for uci in ["e2e4", "g1f3"] { + to_question(&mut session, &library, &mut learning); + let shown = session + .preview_new(format!("show-{uci}"), NOW) + .unwrap() + .unwrap(); + learning + .apply_attempt(shown, &SrsSettings::default()) + .unwrap(); + answer( + &mut session, + &library, + &mut learning, + uci, + &format!("play-{uci}"), + ); + } + assert_eq!(session.phase, LearningSessionPhase::Finished); + // The two shown moves are due again in a minute, yet "more" means new ones only. + assert_eq!(session.introduce_more(&library, &learning, 2), Ok(2)); + assert_eq!(queue_moves(&session), ["f1b5", "b5a4"]); + assert_eq!( + session.introduce_more(&library, &learning, 2), + Err(LearningSessionError::IntroductionRequiresFinished) + ); + let mut review = LearningSessionSnapshot::new_single_pass_review( + "more-review", + &library, + &learning, + scope, + SrsSettings::default(), + ) + .unwrap(); + while review.current_target().is_some() { + review.current_index += 1; + } + review.phase = LearningSessionPhase::Finished; + assert_eq!( + review.introduce_more(&library, &learning, 2), + Err(LearningSessionError::UnsupportedMode( + QueueMode::ReviewInOrder + )) + ); +} + +#[test] +fn branch_session_asks_only_moves_of_the_branch_from_the_start_of_the_game() { + let (library, id) = library(PGN); + let through = ["e2e4", "e7e5", "g1f3", "b8c6", "f1c4"].map(str::to_owned); + let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, NOW); + let mut learning = LearningData::default(); + // Through an own move: that move is asked, its sibling Bb5 is not. + let mut session = LearningSessionSnapshot::new_branch_review( + "branch", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + &through, + ) + .unwrap(); + assert_eq!(queue_moves(&session), ["f1c4"]); + assert_eq!( + session.stats_scope.branch_root.as_deref(), + Some(&through[..4]) + ); + assert!(session.single_pass); + let target = session.current_target().unwrap(); + assert_eq!(target.path, through); + // The context is played from the start of the game, not from the branch. + let presentation = session + .presentation_with_learning(&library, &learning) + .unwrap(); + assert_eq!(presentation.automatic_context.len(), 4); + assert_eq!(presentation.automatic_context[0].uci, "e2e4"); + to_question(&mut session, &library, &mut learning); + answer(&mut session, &library, &mut learning, "f1c4", "branch-bc4"); + assert_eq!(session.phase, LearningSessionPhase::Finished); + session.validate(&library).unwrap(); + + // Through an opponent's move: every own move below it. + let below = LearningSessionSnapshot::new_branch_review( + "branch-below", + &library, + &LearningData::default(), + scope.clone(), + SrsSettings::default(), + &through[..4], + ) + .unwrap(); + assert_eq!(queue_moves(&below), ["f1b5", "b5a4", "f1c4"]); + assert!( + below + .queue + .iter() + .all(|target| target.path.starts_with(&through[..4])) + ); + + // The whole repertoire, and a daily session limited by a branch root. + let whole = LearningSessionSnapshot::new_branch_review( + "branch-whole", + &library, + &LearningData::default(), + scope.clone(), + SrsSettings::default(), + &[], + ) + .unwrap(); + assert_eq!(queue_moves(&whole).len(), 5); + let daily = LearningSessionSnapshot::new_daily( + "branch-daily", + &library, + &LearningData::default(), + scope.with_branch_root(through[..4].to_vec()), + SrsSettings::default(), + 10, + ) + .unwrap(); + assert_eq!(queue_moves(&daily), ["f1b5", "b5a4", "f1c4"]); +} + +#[test] +fn new_flags_are_optional_in_the_file_and_survive_a_roundtrip() { + let (library, id) = library("1. e4 *"); + let scope = StatsScope::for_repertoire(id, LearningSide::White, NOW); + let learning = LearningData::default(); + let plain = LearningSessionSnapshot::new( + "plain", + &library, + &learning, + scope.clone(), + SrsSettings::default(), + ) + .unwrap(); + let json = serde_json::to_value(&plain).unwrap(); + // 2.3.0 snapshots stay byte-compatible when no new behaviour is used. + for field in ["return_mistakes", "single_pass", "showing_new"] { + assert!( + json.get(field).is_none(), + "{field} written for an old-style session" + ); + } + let read: LearningSessionSnapshot = serde_json::from_value(json).unwrap(); + assert_eq!(read, plain); + + let mut daily = LearningSessionSnapshot::new_daily( + "flags", + &library, + &learning, + scope, + SrsSettings::default(), + 10, + ) + .unwrap(); + daily.preview_new("show", NOW).unwrap(); + daily.single_pass = true; + let json = serde_json::to_string(&daily).unwrap(); + let read: LearningSessionSnapshot = serde_json::from_str(&json).unwrap(); + assert!(read.return_mistakes && read.single_pass && read.showing_new); + read.validate(&library).unwrap(); +} diff --git a/crates/trainer/src/repertoire/learning_session.rs b/crates/trainer/src/repertoire/learning_session.rs index 205a983..c93ac8a 100644 --- a/crates/trainer/src/repertoire/learning_session.rs +++ b/crates/trainer/src/repertoire/learning_session.rs @@ -85,10 +85,24 @@ pub struct LearningSessionSnapshot { /// Per-session optimistic revision, independent from the store revision. #[serde(default)] pub revision: u64, + /// A move answered after a mistake or a hint goes to the end of this session's + /// queue instead of being completed (daily sessions). + #[serde(default, skip_serializing_if = "is_false")] + pub return_mistakes: bool, + /// Review in order ends after one pass instead of starting the next cycle. + #[serde(default, skip_serializing_if = "is_false")] + pub single_pass: bool, + /// The pending preview is the first showing of a new move, not a hint. + #[serde(default, skip_serializing_if = "is_false")] + pub showing_new: bool, #[serde(skip)] runtime: SessionRuntime, } +fn is_false(value: &bool) -> bool { + !*value +} + // Derived data only: clones share it, persistence and snapshot equality do not. #[derive(Clone, Default, Debug)] struct SessionRuntime(Arc>); @@ -295,12 +309,114 @@ impl LearningSessionSnapshot { completed_keys: BTreeSet::new(), cycle: 0, revision: 0, + return_mistakes: false, + single_pass: false, + showing_new: false, runtime: SessionRuntime::default(), }; snapshot.reset_current_target_with_library(library)?; Ok(snapshot) } + /// A daily session: every move due at `stats_scope.as_of` and at most `max_new` + /// moves never shown before, in the scope's priority order. A move answered after a + /// mistake or a hint comes back later in the same session. + pub fn new_daily( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + max_new: usize, + ) -> Result { + let mut snapshot = Self::new_with_mode( + id, + library, + learning, + stats_scope, + settings, + QueueMode::SpacedRepetition, + )?; + snapshot.queue = daily_targets(library, learning, &snapshot.stats_scope, true, max_new)?; + snapshot.return_mistakes = true; + snapshot.reset_current_target_with_library(library)?; + Ok(snapshot) + } + + /// One pass over every active move in the scope's order, then `Finished`. + pub fn new_single_pass_review( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + ) -> Result { + let mut snapshot = Self::new_with_mode( + id, + library, + learning, + stats_scope, + settings, + QueueMode::ReviewInOrder, + )?; + snapshot.single_pass = true; + Ok(snapshot) + } + + /// One pass over the lines through the move at `through` (a PGN path; empty: every + /// line). The move itself is asked when it is the trained side's. + pub fn new_branch_review( + id: impl Into, + library: &Library, + learning: &LearningData, + stats_scope: StatsScope, + settings: SrsSettings, + through: &[String], + ) -> Result { + let stats_scope = match through.split_last() { + Some((_, root)) => stats_scope.with_branch_root(root.to_vec()), + None => stats_scope, + }; + let mut snapshot = + Self::new_single_pass_review(id, library, learning, stats_scope, settings)?; + snapshot + .queue + .retain(|target| target.path.starts_with(through)); + snapshot.reset_current_target_with_library(library)?; + Ok(snapshot) + } + + /// After a finished daily session: the next `max_new` unseen moves only. + pub fn introduce_more( + &mut self, + library: &Library, + learning: &LearningData, + max_new: usize, + ) -> Result { + self.validate_configuration()?; + if self.session.mode != QueueMode::SpacedRepetition { + return Err(LearningSessionError::UnsupportedMode(self.session.mode)); + } + if self.phase != LearningSessionPhase::Finished { + return Err(LearningSessionError::IntroductionRequiresFinished); + } + self.queue = daily_targets(library, learning, &self.stats_scope, false, max_new)?; + self.current_index = 0; + self.completed_keys.clear(); + self.reset_current_target_with_library(library)?; + Ok(self.queue.len()) + } + + /// The current move has never been shown: true when it has no learning state or was + /// never introduced. + pub fn current_is_new(&self, learning: &LearningData) -> bool { + self.current_target().is_some_and(|target| { + learning + .item(&target.key) + .is_none_or(|item| !item.introduced) + }) + } + /// Explicitly replaces a finished queue with the currently unseen items. No item is /// introduced into SRS until an independent answer or preview is recorded. pub fn introduce_new( @@ -577,6 +693,25 @@ impl LearningSessionSnapshot { &mut self, client_attempt_id: impl Into, happened_at: i64, + ) -> Result, LearningSessionError> { + self.preview_impl(client_attempt_id, happened_at, false) + } + + /// Shows a new move before asking it. The move is recorded as `PREVIEWED`, but in a + /// daily session it does not come back as a mistake would. + pub fn preview_new( + &mut self, + client_attempt_id: impl Into, + happened_at: i64, + ) -> Result, LearningSessionError> { + self.preview_impl(client_attempt_id, happened_at, true) + } + + fn preview_impl( + &mut self, + client_attempt_id: impl Into, + happened_at: i64, + new: bool, ) -> Result, LearningSessionError> { let client_attempt_id = checked_attempt_id(client_attempt_id.into())?; self.validate_configuration()?; @@ -598,6 +733,7 @@ impl LearningSessionSnapshot { "preview has no current target", ))?; self.phase = LearningSessionPhase::PreviewedReplay; + self.showing_new = new; Ok(Some(self.attempt( &target.key, TrainingEventType::Previewed, @@ -834,6 +970,8 @@ impl LearningSessionSnapshot { { if context { self.complete_context(challenge_key, library, learning)?; + } else if self.return_mistakes && !self.showing_new { + self.return_current(library)?; } else { self.complete_current(library)?; } @@ -968,6 +1106,7 @@ impl LearningSessionSnapshot { self.current_index += 1; } if self.session.mode == QueueMode::ReviewInOrder + && !self.single_pass && self.current_index >= self.queue.len() && !self.queue.is_empty() { @@ -978,6 +1117,22 @@ impl LearningSessionSnapshot { self.reset_current_target_with_library(library) } + /// Moves the current target behind the rest of the queue: it is asked again later + /// in this session, from the start of its line. + fn return_current(&mut self, library: &Library) -> Result<(), LearningSessionError> { + if self.current_index < self.queue.len() { + let target = self.queue.remove(self.current_index); + self.queue.push(target); + } + while self + .current_target() + .is_some_and(|target| self.completed_keys.contains(&target.key)) + { + self.current_index += 1; + } + self.reset_current_target_with_library(library) + } + fn complete_context( &mut self, key: LearningItemKey, @@ -1137,6 +1292,7 @@ impl LearningSessionSnapshot { fn reset_current_target(&mut self) { self.context_index = 0; + self.showing_new = false; self.phase = match self.current_target() { None => LearningSessionPhase::Finished, Some(target) if target.path.len() > 1 => LearningSessionPhase::AdvancingContext, @@ -1190,6 +1346,38 @@ fn select_queue( } } +fn daily_targets( + library: &Library, + learning: &LearningData, + scope: &StatsScope, + include_due: bool, + max_new: usize, +) -> Result, LearningSessionError> { + let mut new = 0usize; + Ok(select_memberships( + library, + learning, + scope, + |item| { + item.is_none_or(|item| !item.introduced) + || item.is_some_and(|item| item.is_due(scope.as_of)) + }, + scope.learning_priority, + )? + .into_iter() + .filter(|membership| { + let item = learning.item(&membership.key); + if item.is_none_or(|item| !item.introduced) { + new += 1; + new <= max_new + } else { + include_due + } + }) + .map(LearningSessionTarget::from) + .collect()) +} + fn select_targets( library: &Library, learning: &LearningData, diff --git a/crates/trainer/src/repertoire/mod.rs b/crates/trainer/src/repertoire/mod.rs index 18dedc7..7c4bfaa 100644 --- a/crates/trainer/src/repertoire/mod.rs +++ b/crates/trainer/src/repertoire/mod.rs @@ -82,6 +82,8 @@ mod analytics_tests; #[cfg(test)] mod branch_tests; #[cfg(test)] +mod daily_tests; +#[cfg(test)] mod graph_tests; #[cfg(test)] mod line_tests; From 98f0e4749fe84cb7941450b65aaa9c31bf9aa09f Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Thu, 26 Nov 2026 17:13:34 +0300 Subject: [PATCH 03/31] wip: opening trainer v2 desktop UI (repertoires, session, lines), i18n, devhooks doc One repertoire_ui test still fails (see docs/qa/opening-trainer-v2-devhooks.md). --- apps/desktop/src/i18n.rs | 1340 +++++- apps/desktop/src/learning_branches.rs | 763 --- apps/desktop/src/learning_charts.rs | 507 -- apps/desktop/src/learning_context_controls.rs | 204 - apps/desktop/src/learning_dashboard.rs | 1968 -------- apps/desktop/src/learning_training.rs | 4139 ---------------- apps/desktop/src/lib.rs | 20 +- apps/desktop/src/opening_layout.rs | 498 ++ apps/desktop/src/opening_lines.rs | 584 +++ apps/desktop/src/opening_session.rs | 2426 ++++++++++ apps/desktop/src/opening_session_tests.rs | 2129 +++++++++ apps/desktop/src/repertoire_editor.rs | 1070 ----- apps/desktop/src/repertoire_training.rs | 1604 ------- apps/desktop/src/repertoire_ui.rs | 4150 +++++++++-------- apps/desktop/src/repertoire_ui_tests.rs | 2138 ++------- apps/desktop/src/widgets.rs | 32 + docs/dev/opening-trainer-v2-handoff.md | 37 + docs/qa/opening-trainer-v2-devhooks.md | 46 + 18 files changed, 9865 insertions(+), 13790 deletions(-) delete mode 100644 apps/desktop/src/learning_branches.rs delete mode 100644 apps/desktop/src/learning_charts.rs delete mode 100644 apps/desktop/src/learning_context_controls.rs delete mode 100644 apps/desktop/src/learning_dashboard.rs delete mode 100644 apps/desktop/src/learning_training.rs create mode 100644 apps/desktop/src/opening_layout.rs create mode 100644 apps/desktop/src/opening_lines.rs create mode 100644 apps/desktop/src/opening_session.rs create mode 100644 apps/desktop/src/opening_session_tests.rs delete mode 100644 apps/desktop/src/repertoire_editor.rs delete mode 100644 apps/desktop/src/repertoire_training.rs create mode 100644 docs/dev/opening-trainer-v2-handoff.md create mode 100644 docs/qa/opening-trainer-v2-devhooks.md diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 7ff828f..431e489 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -216,6 +216,1326 @@ 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]] = &[ + [ + "Learned", + "Выучено", + "Appris", + "Gelernt", + "Aprendidas", + "Imparate", + "Aprendidas", + "O‘rganildi", + "Үйренілді", + ], + [ + "You play White", + "Вы играете белыми", + "Vous jouez les Blancs", + "Sie spielen Weiß", + "Juegas con blancas", + "Giochi con il Bianco", + "Você joga de brancas", + "Siz oq bilan o‘ynaysiz", + "Сіз ақпен ойнайсыз", + ], + [ + "You play Black", + "Вы играете чёрными", + "Vous jouez les Noirs", + "Sie spielen Schwarz", + "Juegas con negras", + "Giochi con il Nero", + "Você joga de pretas", + "Siz qora bilan o‘ynaysiz", + "Сіз қарамен ойнайсыз", + ], + [ + "Correct!", + "Верно", + "Exact !", + "Richtig!", + "¡Correcto!", + "Esatto!", + "Correto!", + "To‘g‘ri!", + "Дұрыс!", + ], + [ + "tomorrow", + "завтра", + "demain", + "morgen", + "mañana", + "domani", + "amanhã", + "ertaga", + "ертең", + ], + [ + "today at {time}", + "сегодня в {time}", + "aujourd’hui à {time}", + "heute um {time}", + "hoy a las {time}", + "oggi alle {time}", + "hoje às {time}", + "bugun soat {time} da", + "бүгін {time}", + ], + [ + "in {days} days", + "через {days} дн.", + "dans {days} jours", + "in {days} Tagen", + "en {days} días", + "tra {days} giorni", + "em {days} dias", + "{days} kundan keyin", + "{days} күннен кейін", + ], + [ + "Not trained", + "Не тренируется", + "Pas entraînée", + "Wird nicht trainiert", + "No se entrena", + "Non allenata", + "Não treinada", + "Mashq qilinmaydi", + "Жаттықтырылмайды", + ], + [ + "Counting moves…", + "Считаем ходы…", + "Comptage des coups…", + "Züge werden gezählt…", + "Contando jugadas…", + "Conteggio delle mosse…", + "Contando lances…", + "Yurishlar sanalmoqda…", + "Жүрістер саналуда…", + ], + [ + "Review all lines", + "Повторить всё подряд", + "Réviser toutes les lignes", + "Alle Varianten wiederholen", + "Repasar todas las líneas", + "Ripassa tutte le linee", + "Revisar todas as linhas", + "Barcha variantlarni takrorlash", + "Барлық нұсқаны қайталау", + ], + [ + "Train this branch", + "Тренировать эту ветку", + "Entraîner cette branche", + "Diesen Zweig trainieren", + "Entrenar esta rama", + "Allena questo ramo", + "Treinar este ramo", + "Shu shoxni mashq qilish", + "Осы тармақты жаттықтыру", + ], + [ + "Train again", + "Снова тренировать", + "Entraîner à nouveau", + "Wieder trainieren", + "Volver a entrenar", + "Allena di nuovo", + "Treinar de novo", + "Yana mashq qilish", + "Қайта жаттықтыру", + ], + [ + "Don't train", + "Не тренировать", + "Ne pas entraîner", + "Nicht trainieren", + "No entrenar", + "Non allenare", + "Não treinar", + "Mashq qilmaslik", + "Жаттықтырмау", + ], + [ + "⬅ Repertoires", + "⬅ Репертуары", + "⬅ Répertoires", + "⬅ Repertoires", + "⬅ Repertorios", + "⬅ Repertori", + "⬅ Repertórios", + "⬅ Repertuarlar", + "⬅ Репертуарлар", + ], + [ + "⬅ Lines", + "⬅ Варианты", + "⬅ Lignes", + "⬅ Varianten", + "⬅ Líneas", + "⬅ Linee", + "⬅ Linhas", + "⬅ Variantlar", + "⬅ Нұсқалар", + ], + [ + "⬅ To game", + "⬅ К партии", + "⬅ À la partie", + "⬅ Zur Partie", + "⬅ A la partida", + "⬅ Alla partita", + "⬅ Para a partida", + "⬅ Partiyaga", + "⬅ Партияға", + ], + [ + "Below: {n} lines · {y} your moves · learned {x}", + "Дальше: вариантов {n} · ваших ходов {y} · выучено {x}", + "En dessous : {n} lignes · {y} de vos coups · {x} appris", + "Darunter: {n} Varianten · {y} eigene Züge · {x} gelernt", + "Debajo: {n} líneas · {y} jugadas tuyas · {x} aprendidas", + "Sotto: {n} linee · {y} tue mosse · {x} imparate", + "Abaixo: {n} linhas · {y} lances seus · {x} aprendidos", + "Keyin: {n} ta variant · sizning {y} ta yurishingiz · {x} tasi o‘rganilgan", + "Әрі қарай: {n} нұсқа · сіздің {y} жүрісіңіз · {x} үйренілді", + ], + [ + "Lines · {n} lines · {y} your moves", + "Варианты · вариантов: {n} · ваших ходов: {y}", + "Lignes · {n} lignes · {y} de vos coups", + "Varianten · {n} Varianten · {y} eigene Züge", + "Líneas · {n} líneas · {y} jugadas tuyas", + "Linee · {n} linee · {y} tue mosse", + "Linhas · {n} linhas · {y} lances seus", + "Variantlar · {n} ta variant · sizning {y} ta yurishingiz", + "Нұсқалар · {n} нұсқа · сіздің {y} жүрісіңіз", + ], + [ + "Training · you play White", + "Тренировка · вы играете белыми", + "Entraînement · vous jouez les Blancs", + "Training · Sie spielen Weiß", + "Entrenamiento · juegas con blancas", + "Allenamento · giochi con il Bianco", + "Treino · você joga de brancas", + "Mashq · siz oq bilan o‘ynaysiz", + "Жаттығу · сіз ақпен ойнайсыз", + ], + [ + "Training · you play Black", + "Тренировка · вы играете чёрными", + "Entraînement · vous jouez les Noirs", + "Training · Sie spielen Schwarz", + "Entrenamiento · juegas con negras", + "Allenamento · giochi con il Nero", + "Treino · você joga de pretas", + "Mashq · siz qora bilan o‘ynaysiz", + "Жаттығу · сіз қарамен ойнайсыз", + ], + [ + "Review all lines · you play White", + "Повторение подряд · вы играете белыми", + "Révision de toutes les lignes · vous jouez les Blancs", + "Alle Varianten · Sie spielen Weiß", + "Repaso de todas las líneas · juegas con blancas", + "Ripasso di tutte le linee · giochi con il Bianco", + "Revisão de todas as linhas · você joga de brancas", + "Barchasini takrorlash · siz oq bilan o‘ynaysiz", + "Бәрін қайталау · сіз ақпен ойнайсыз", + ], + [ + "Review all lines · you play Black", + "Повторение подряд · вы играете чёрными", + "Révision de toutes les lignes · vous jouez les Noirs", + "Alle Varianten · Sie spielen Schwarz", + "Repaso de todas las líneas · juegas con negras", + "Ripasso di tutte le linee · giochi con il Nero", + "Revisão de todas as linhas · você joga de pretas", + "Barchasini takrorlash · siz qora bilan o‘ynaysiz", + "Бәрін қайталау · сіз қарамен ойнайсыз", + ], + [ + "Watch", + "Смотрите", + "Regardez", + "Zuschauen", + "Observa", + "Guarda", + "Observe", + "Kuzating", + "Қараңыз", + ], + [ + "Moves up to your next question", + "Ходы до вашего следующего вопроса", + "Les coups jusqu’à votre prochaine question", + "Die Züge bis zu Ihrer nächsten Frage", + "Las jugadas hasta tu próxima pregunta", + "Le mosse fino alla prossima domanda", + "Os lances até a sua próxima pergunta", + "Keyingi savolingizgacha bo‘lgan yurishlar", + "Келесі сұрағыңызға дейінгі жүрістер", + ], + [ + "Next line", + "Следующий вариант", + "Ligne suivante", + "Nächste Variante", + "Siguiente línea", + "Linea successiva", + "Próxima linha", + "Keyingi variant", + "Келесі нұсқа", + ], + [ + "New move", + "Новый ход", + "Nouveau coup", + "Neuer Zug", + "Jugada nueva", + "Mossa nuova", + "Lance novo", + "Yangi yurish", + "Жаңа жүріс", + ], + [ + "Your move", + "Ваш ход", + "À vous", + "Ihr Zug", + "Tu jugada", + "Tocca a te", + "Sua vez", + "Sizning yurishingiz", + "Сіздің жүрісіңіз", + ], + [ + "Play the move from your repertoire", + "Сыграйте ход из репертуара", + "Jouez le coup de votre répertoire", + "Spielen Sie den Zug Ihres Repertoires", + "Juega la jugada de tu repertorio", + "Gioca la mossa del tuo repertorio", + "Jogue o lance do seu repertório", + "Repertuaringizdagi yurishni qiling", + "Репертуарыңыздағы жүрісті жасаңыз", + ], + [ + "Not this move", + "Не тот ход", + "Pas ce coup", + "Nicht dieser Zug", + "No es esta jugada", + "Non è questa mossa", + "Não é este lance", + "Bu yurish emas", + "Бұл жүріс емес", + ], + [ + "This one is in your repertoire too", + "Этот ход тоже есть в репертуаре", + "Ce coup est aussi dans votre répertoire", + "Auch dieser Zug ist in Ihrem Repertoire", + "Esta jugada también está en tu repertorio", + "Anche questa mossa è nel tuo repertorio", + "Este lance também está no seu repertório", + "Bu yurish ham repertuaringizda bor", + "Бұл жүріс те репертуарыңызда бар", + ], + [ + "Got it", + "Запомним", + "Noté", + "Gemerkt", + "Anotado", + "Ricevuto", + "Anotado", + "Eslab qolamiz", + "Есте сақтаймыз", + ], + [ + "Could not save your answer", + "Не удалось сохранить ответ", + "Impossible d’enregistrer votre réponse", + "Ihre Antwort konnte nicht gespeichert werden", + "No se pudo guardar tu respuesta", + "Impossibile salvare la risposta", + "Não foi possível salvar sua resposta", + "Javobingizni saqlab bo‘lmadi", + "Жауабыңызды сақтау мүмкін болмады", + ], + [ + "Could not continue the session", + "Не удалось продолжить занятие", + "Impossible de poursuivre la séance", + "Die Übung konnte nicht fortgesetzt werden", + "No se pudo continuar la sesión", + "Impossibile continuare la sessione", + "Não foi possível continuar a sessão", + "Mashg‘ulotni davom ettirib bo‘lmadi", + "Сабақты жалғастыру мүмкін болмады", + ], + [ + "Session stopped", + "Занятие прервано", + "Séance interrompue", + "Übung abgebrochen", + "Sesión interrumpida", + "Sessione interrotta", + "Sessão interrompida", + "Mashg‘ulot to‘xtatildi", + "Сабақ үзілді", + ], + [ + "Session complete", + "Занятие окончено", + "Séance terminée", + "Übung beendet", + "Sesión terminada", + "Sessione completata", + "Sessão concluída", + "Mashg‘ulot tugadi", + "Сабақ аяқталды", + ], + [ + "Everything is saved", + "Всё сохранено", + "Tout est enregistré", + "Alles ist gespeichert", + "Todo está guardado", + "Tutto è salvato", + "Tudo está salvo", + "Hammasi saqlandi", + "Бәрі сақталды", + ], + [ + "left", + "осталось", + "restants", + "übrig", + "quedan", + "rimaste", + "restantes", + "qoldi", + "қалды", + ], + [ + "line", + "вариант", + "ligne", + "Variante", + "línea", + "linea", + "linha", + "variant", + "нұсқа", + ], + [ + "Lines reviewed", + "Пройдено вариантов", + "Lignes révisées", + "Wiederholte Varianten", + "Líneas repasadas", + "Linee ripassate", + "Linhas revisadas", + "Takrorlangan variantlar", + "Қайталанған нұсқалар", + ], + [ + "Correct first time", + "Верно с первого раза", + "Justes du premier coup", + "Beim ersten Mal richtig", + "Correctas a la primera", + "Giuste al primo colpo", + "Certos de primeira", + "Birinchi urinishda to‘g‘ri", + "Бірінші реттен дұрыс", + ], + [ + "New moves learned", + "Новых ходов", + "Nouveaux coups appris", + "Neue Züge gelernt", + "Jugadas nuevas aprendidas", + "Mosse nuove imparate", + "Lances novos aprendidos", + "Yangi yurishlar", + "Жаңа жүрістер", + ], + [ + "Moves to remember", + "Что запомнить", + "Coups à retenir", + "Züge zum Merken", + "Jugadas que recordar", + "Mosse da ricordare", + "Lances para lembrar", + "Eslab qolinadigan yurishlar", + "Есте сақтайтын жүрістер", + ], + [ + "10 more new (N)", + "Ещё 10 новых (N)", + "10 nouveaux de plus (N)", + "10 weitere neue (N)", + "10 nuevas más (N)", + "Altre 10 nuove (N)", + "Mais 10 novos (N)", + "Yana 10 ta yangi (N)", + "Тағы 10 жаңа (N)", + ], + [ + "{n} more new (N)", + "Ещё {n} новых (N)", + "{n} nouveaux de plus (N)", + "{n} weitere neue (N)", + "{n} nuevas más (N)", + "Altre {n} nuove (N)", + "Mais {n} novos (N)", + "Yana {n} ta yangi (N)", + "Тағы {n} жаңа (N)", + ], + [ + "To lines (Enter)", + "К вариантам (Enter)", + "Aux lignes (Entrée)", + "Zu den Varianten (Enter)", + "A las líneas (Intro)", + "Alle linee (Invio)", + "Para as linhas (Enter)", + "Variantlarga (Enter)", + "Нұсқаларға (Enter)", + ], + [ + "To repertoires (Enter)", + "К репертуарам (Enter)", + "Aux répertoires (Entrée)", + "Zu den Repertoires (Enter)", + "A los repertorios (Intro)", + "Ai repertori (Invio)", + "Para os repertórios (Enter)", + "Repertuarlarga (Enter)", + "Репертуарларға (Enter)", + ], + [ + "Finish", + "Закончить", + "Terminer", + "Beenden", + "Terminar", + "Termina", + "Encerrar", + "Tugatish", + "Аяқтау", + ], + [ + "× Finish", + "× Закончить", + "× Terminer", + "× Beenden", + "× Terminar", + "× Termina", + "× Encerrar", + "× Tugatish", + "× Аяқтау", + ], + [ + "Finish the session (Esc)", + "Закончить занятие (Esc)", + "Terminer la séance (Échap)", + "Übung beenden (Esc)", + "Terminar la sesión (Esc)", + "Termina la sessione (Esc)", + "Encerrar a sessão (Esc)", + "Mashg‘ulotni tugatish (Esc)", + "Сабақты аяқтау (Esc)", + ], + [ + "Hint (H)", + "Подсказка (H)", + "Indice (H)", + "Hinweis (H)", + "Pista (H)", + "Suggerimento (H)", + "Dica (H)", + "Maslahat (H)", + "Кеңес (H)", + ], + [ + "Skip (Enter)", + "Пропустить (Enter)", + "Passer (Entrée)", + "Überspringen (Enter)", + "Saltar (Intro)", + "Salta (Invio)", + "Pular (Enter)", + "O‘tkazib yuborish (Enter)", + "Өткізу (Enter)", + ], + [ + "Preparing…", + "Готовим занятие…", + "Préparation…", + "Wird vorbereitet…", + "Preparando…", + "Preparazione…", + "Preparando…", + "Tayyorlanmoqda…", + "Дайындалуда…", + ], + [ + "Branch: {path}", + "Ветка: {path}", + "Branche : {path}", + "Zweig: {path}", + "Rama: {path}", + "Ramo: {path}", + "Ramo: {path}", + "Shox: {path}", + "Тармақ: {path}", + ], + [ + "today, {n} more", + "сегодня, ещё {n}", + "aujourd’hui, encore {n}", + "heute, noch {n}", + "hoy, {n} más", + "oggi, altre {n}", + "hoje, mais {n}", + "bugun, yana {n} ta", + "бүгін, тағы {n}", + ], + [ + "{k} of {n}", + "{k} из {n}", + "{k} sur {n}", + "{k} von {n}", + "{k} de {n}", + "{k} di {n}", + "{k} de {n}", + "{n} tadan {k}", + "{n} ішінен {k}", + ], + [ + "Play {san} — it is shown by the arrow", + "Сыграйте {san} — он показан стрелкой", + "Jouez {san} — la flèche le montre", + "Spielen Sie {san} — der Pfeil zeigt ihn", + "Juega {san}: la flecha lo muestra", + "Gioca {san}: lo mostra la freccia", + "Jogue {san} — a seta o mostra", + "{san} yurishini qiling — u strelka bilan ko‘rsatilgan", + "{san} жүрісін жасаңыз — ол көрсеткімен көрсетілген", + ], + [ + "One more move of yours here, not {san}", + "Здесь есть ещё один ваш ход, не {san}", + "Vous avez un autre coup ici, pas {san}", + "Hier gibt es noch einen eigenen Zug, nicht {san}", + "Aquí tienes otra jugada, no {san}", + "Qui hai un’altra mossa, non {san}", + "Há mais um lance seu aqui, não {san}", + "Bu yerda yana bir yurishingiz bor, {san} emas", + "Мұнда тағы бір жүрісіңіз бар, {san} емес", + ], + [ + "Correct: {san}. Play it", + "Правильно: {san}. Сыграйте его", + "Le bon coup : {san}. Jouez-le", + "Richtig ist {san}. Spielen Sie ihn", + "La correcta: {san}. Juégala", + "Quella giusta: {san}. Giocala", + "O correto: {san}. Jogue-o", + "To‘g‘risi: {san}. Uni qiling", + "Дұрысы: {san}. Соны жасаңыз", + ], + [ + "Now the other one: play {san}", + "Сейчас нужен другой: сыграйте {san}", + "Maintenant l’autre : jouez {san}", + "Jetzt der andere: Spielen Sie {san}", + "Ahora la otra: juega {san}", + "Ora l’altra: gioca {san}", + "Agora o outro: jogue {san}", + "Endi boshqasi: {san} yurishini qiling", + "Енді басқасы: {san} жүрісін жасаңыз", + ], + [ + "{move} will come back in this session", + "{move} вернётся в этом занятии", + "{move} reviendra dans cette séance", + "{move} kommt in dieser Übung wieder", + "{move} volverá en esta sesión", + "{move} tornerà in questa sessione", + "{move} voltará nesta sessão", + "{move} shu mashg‘ulotda yana so‘raladi", + "{move} осы сабақта қайта сұралады", + ], + [ + "Play {san}", + "Сыграйте {san}", + "Jouez {san}", + "Spielen Sie {san}", + "Juega {san}", + "Gioca {san}", + "Jogue {san}", + "{san} yurishini qiling", + "{san} жүрісін жасаңыз", + ], + [ + "Play {san}. It will come back in this session", + "Сыграйте {san}. Ход вернётся в этом занятии", + "Jouez {san}. Il reviendra dans cette séance", + "Spielen Sie {san}. Er kommt in dieser Übung wieder", + "Juega {san}. Volverá en esta sesión", + "Gioca {san}. Tornerà in questa sessione", + "Jogue {san}. Ele voltará nesta sessão", + "{san} yurishini qiling. U shu mashg‘ulotda yana so‘raladi", + "{san} жүрісін жасаңыз. Ол осы сабақта қайта сұралады", + ], + [ + "after {path}", + "после {path}", + "après {path}", + "nach {path}", + "después de {path}", + "dopo {path}", + "depois de {path}", + "{path} dan keyin", + "{path} кейін", + ], + [ + "and {k} more", + "и ещё {k}", + "et {k} de plus", + "und {k} weitere", + "y {k} más", + "e altre {k}", + "e mais {k}", + "va yana {k} ta", + "және тағы {k}", + ], + [ + "Nothing to train here right now", + "Сейчас здесь нечего тренировать", + "Rien à entraîner ici pour l’instant", + "Hier gibt es gerade nichts zu trainieren", + "Ahora no hay nada que entrenar aquí", + "Al momento qui non c’è niente da allenare", + "Nada para treinar aqui agora", + "Hozir bu yerda mashq qiladigan narsa yo‘q", + "Қазір мұнда жаттығатын ештеңе жоқ", + ], + [ + "A repertoire is your opening moves as a PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…”.", + "Репертуар — это ваши дебютные ходы в PGN с вариантами. Импортируйте файл или откройте любую партию, выберите ход и нажмите «Добавить в репертуар…».", + "Un répertoire, ce sont vos coups d’ouverture dans un PGN avec variantes. Importez un fichier, ou ouvrez une partie, choisissez un coup et « Ajouter au répertoire… ».", + "Ein Repertoire sind Ihre Eröffnungszüge als PGN mit Varianten. Importieren Sie eine Datei oder öffnen Sie eine Partie, wählen Sie einen Zug und „Zum Repertoire hinzufügen…“.", + "Un repertorio son tus jugadas de apertura en un PGN con variantes. Importa un archivo, o abre una partida, elige una jugada y pulsa «Añadir al repertorio…».", + "Un repertorio sono le tue mosse d’apertura in un PGN con varianti. Importa un file, oppure apri una partita, scegli una mossa e «Aggiungi al repertorio…».", + "Um repertório são seus lances de abertura em um PGN com variantes. Importe um arquivo, ou abra uma partida, escolha um lance e clique em “Adicionar ao repertório…”.", + "Repertuar — bu variantlari bor PGN dagi debyut yurishlaringiz. Faylni import qiling yoki istalgan partiyani ochib, yurishni tanlang va «Repertuarga qo‘shish…» ni bosing.", + "Репертуар — нұсқалары бар PGN-дегі дебют жүрістеріңіз. Файлды импорттаңыз немесе кез келген партияны ашып, жүрісті таңдап, «Репертуарға қосу…» басыңыз.", + ], + [ + "Moves are added from a PGN file or with “Add to repertoire…” in any game.", + "Ходы добавляются из PGN-файла или кнопкой «Добавить в репертуар…» в любой партии.", + "Les coups s’ajoutent depuis un fichier PGN ou avec « Ajouter au répertoire… » dans une partie.", + "Züge kommen aus einer PGN-Datei oder über „Zum Repertoire hinzufügen…“ in einer Partie.", + "Las jugadas se añaden desde un archivo PGN o con «Añadir al repertorio…» en cualquier partida.", + "Le mosse si aggiungono da un file PGN o con «Aggiungi al repertorio…» in una partita.", + "Os lances são adicionados de um arquivo PGN ou com “Adicionar ao repertório…” em qualquer partida.", + "Yurishlar PGN fayldan yoki istalgan partiyadagi «Repertuarga qo‘shish…» tugmasi bilan qo‘shiladi.", + "Жүрістер PGN файлынан немесе кез келген партиядағы «Репертуарға қосу…» батырмасымен қосылады.", + ], + [ + "Rename repertoire", + "Переименовать репертуар", + "Renommer le répertoire", + "Repertoire umbenennen", + "Renombrar el repertorio", + "Rinomina il repertorio", + "Renomear o repertório", + "Repertuar nomini o‘zgartirish", + "Репертуар атын өзгерту", + ], + [ + "Switch", + "Переключить", + "Changer", + "Wechseln", + "Cambiar", + "Cambia", + "Trocar", + "Almashtirish", + "Ауыстыру", + ], + [ + "The moves themselves and PGN files do not change.", + "Сами ходы и PGN-файлы не меняются.", + "Les coups eux-mêmes et les fichiers PGN ne changent pas.", + "Die Züge selbst und die PGN-Dateien ändern sich nicht.", + "Las jugadas y los archivos PGN no cambian.", + "Le mosse e i file PGN non cambiano.", + "Os lances e os arquivos PGN não mudam.", + "Yurishlarning o‘zi va PGN fayllar o‘zgarmaydi.", + "Жүрістердің өзі мен PGN файлдары өзгермейді.", + ], + [ + "The repertoire leaves this list. PGN files on disk do not change.", + "Репертуар исчезнет из списка. PGN-файлы на диске не меняются.", + "Le répertoire quitte cette liste. Les fichiers PGN sur le disque ne changent pas.", + "Das Repertoire verschwindet aus der Liste. PGN-Dateien auf dem Datenträger ändern sich nicht.", + "El repertorio desaparece de la lista. Los archivos PGN del disco no cambian.", + "Il repertorio esce dall’elenco. I file PGN sul disco non cambiano.", + "O repertório sai da lista. Os arquivos PGN no disco não mudam.", + "Repertuar ro‘yxatdan yo‘qoladi. Diskdagi PGN fayllar o‘zgarmaydi.", + "Репертуар тізімнен жоғалады. Дискідегі PGN файлдары өзгермейді.", + ], + [ + "Your answers are kept: import the same PGN again and the progress returns.", + "Ответы сохранятся: если импортировать тот же PGN снова, прогресс вернётся.", + "Vos réponses sont conservées : réimportez le même PGN et la progression revient.", + "Ihre Antworten bleiben: Importieren Sie dieselbe PGN erneut, ist der Fortschritt wieder da.", + "Tus respuestas se conservan: importa el mismo PGN de nuevo y el progreso vuelve.", + "Le risposte restano: reimporta lo stesso PGN e i progressi tornano.", + "Suas respostas ficam guardadas: importe o mesmo PGN de novo e o progresso volta.", + "Javoblaringiz saqlanadi: o‘sha PGN ni qayta import qilsangiz, natija qaytadi.", + "Жауаптарыңыз сақталады: сол PGN-ді қайта импорттасаңыз, нәтиже қайтады.", + ], + [ + "Nothing to review today", + "Повторять сегодня нечего", + "Rien à réviser aujourd’hui", + "Heute nichts zu wiederholen", + "Hoy no hay nada que repasar", + "Oggi niente da ripassare", + "Nada para revisar hoje", + "Bugun takrorlash kerak emas", + "Бүгін қайталайтын ештеңе жоқ", + ], + [ + "Done for today", + "На сегодня всё", + "C’est fini pour aujourd’hui", + "Für heute fertig", + "Por hoy, terminado", + "Per oggi è tutto", + "Por hoje é só", + "Bugunga yetarli", + "Бүгінге осы", + ], + [ + "No moves yet", + "Ходов пока нет", + "Pas encore de coups", + "Noch keine Züge", + "Aún no hay jugadas", + "Ancora nessuna mossa", + "Ainda sem lances", + "Hali yurishlar yo‘q", + "Әзірге жүріс жоқ", + ], + [ + "Add a PGN, or use “Add to repertoire…” in any game", + "Добавьте PGN или нажмите «Добавить в репертуар…» в любой партии", + "Ajoutez un PGN, ou « Ajouter au répertoire… » dans une partie", + "Fügen Sie eine PGN hinzu oder „Zum Repertoire hinzufügen…“ in einer Partie", + "Añade un PGN o usa «Añadir al repertorio…» en una partida", + "Aggiungi un PGN o usa «Aggiungi al repertorio…» in una partita", + "Adicione um PGN ou use “Adicionar ao repertório…” em uma partida", + "PGN qo‘shing yoki istalgan partiyada «Repertuarga qo‘shish…» ni bosing", + "PGN қосыңыз немесе кез келген партияда «Репертуарға қосу…» басыңыз", + ], + [ + "No moves for White here", + "Здесь нет ходов за белых", + "Pas de coups des Blancs ici", + "Hier gibt es keine Züge für Weiß", + "Aquí no hay jugadas de las blancas", + "Qui non ci sono mosse del Bianco", + "Não há lances das brancas aqui", + "Bu yerda oq uchun yurishlar yo‘q", + "Мұнда ақтың жүрістері жоқ", + ], + [ + "No moves for Black here", + "Здесь нет ходов за чёрных", + "Pas de coups des Noirs ici", + "Hier gibt es keine Züge für Schwarz", + "Aquí no hay jugadas de las negras", + "Qui non ci sono mosse del Nero", + "Não há lances das pretas aqui", + "Bu yerda qora uchun yurishlar yo‘q", + "Мұнда қараның жүрістері жоқ", + ], + [ + "This PGN may be a repertoire for the other colour", + "Возможно, это репертуар за другой цвет", + "Ce PGN est peut-être un répertoire pour l’autre couleur", + "Diese PGN ist vielleicht ein Repertoire für die andere Farbe", + "Quizá este PGN sea un repertorio del otro color", + "Forse questo PGN è un repertorio per l’altro colore", + "Talvez este PGN seja um repertório da outra cor", + "Ehtimol, bu boshqa rang uchun repertuar", + "Мүмкін, бұл басқа түстің репертуары", + ], + [ + "Cannot read this repertoire", + "Не удалось прочитать репертуар", + "Impossible de lire ce répertoire", + "Dieses Repertoire kann nicht gelesen werden", + "No se puede leer este repertorio", + "Impossibile leggere questo repertorio", + "Não foi possível ler este repertório", + "Bu repertuarni o‘qib bo‘lmadi", + "Бұл репертуарды оқу мүмкін болмады", + ], + [ + "Play as Black", + "Играть чёрными", + "Jouer les Noirs", + "Mit Schwarz spielen", + "Jugar con negras", + "Gioca con il Nero", + "Jogar de pretas", + "Qora bilan o‘ynash", + "Қарамен ойнау", + ], + [ + "Play as White", + "Играть белыми", + "Jouer les Blancs", + "Mit Weiß spielen", + "Jugar con blancas", + "Gioca con il Bianco", + "Jogar de brancas", + "Oq bilan o‘ynash", + "Ақпен ойнау", + ], + [ + "Lines…", + "Варианты…", + "Lignes…", + "Varianten…", + "Líneas…", + "Linee…", + "Linhas…", + "Variantlar…", + "Нұсқалар…", + ], + [ + "Rename…", + "Переименовать…", + "Renommer…", + "Umbenennen…", + "Renombrar…", + "Rinomina…", + "Renomear…", + "Nomini o‘zgartirish…", + "Атын өзгерту…", + ], + [ + "Add PGN to this repertoire…", + "Добавить PGN в этот репертуар…", + "Ajouter un PGN à ce répertoire…", + "PGN zu diesem Repertoire hinzufügen…", + "Añadir un PGN a este repertorio…", + "Aggiungi un PGN a questo repertorio…", + "Adicionar PGN a este repertório…", + "Bu repertuarga PGN qo‘shish…", + "Бұл репертуарға PGN қосу…", + ], + [ + "Reset progress…", + "Сбросить прогресс…", + "Réinitialiser la progression…", + "Fortschritt zurücksetzen…", + "Restablecer el progreso…", + "Azzera i progressi…", + "Redefinir o progresso…", + "Natijani tiklash…", + "Нәтижені тастау…", + ], + [ + "You play", + "Вы играете", + "Vous jouez", + "Sie spielen", + "Juegas con", + "Giochi con", + "Você joga de", + "Siz o‘ynaysiz", + "Сіз ойнайсыз", + ], + [ + "Import PGN", + "Импорт PGN", + "Importer un PGN", + "PGN importieren", + "Importar PGN", + "Importa PGN", + "Importar PGN", + "PGN import qilish", + "PGN импорттау", + ], + [ + "Chosen from the PGN — check it", + "Выбрано по PGN — проверьте", + "Choisi d’après le PGN — vérifiez", + "Aus der PGN gewählt — bitte prüfen", + "Elegido según el PGN: compruébalo", + "Scelto in base al PGN: controlla", + "Escolhido pelo PGN — confira", + "PGN bo‘yicha tanlandi — tekshiring", + "PGN бойынша таңдалды — тексеріңіз", + ], + [ + "Reading the file…", + "Читаем файл…", + "Lecture du fichier…", + "Datei wird gelesen…", + "Leyendo el archivo…", + "Lettura del file…", + "Lendo o arquivo…", + "Fayl o‘qilmoqda…", + "Файл оқылуда…", + ], + [ + "Nothing new in this file", + "В файле нет новых ходов", + "Rien de nouveau dans ce fichier", + "Nichts Neues in dieser Datei", + "No hay nada nuevo en este archivo", + "Niente di nuovo in questo file", + "Nada de novo neste arquivo", + "Bu faylda yangi yurishlar yo‘q", + "Бұл файлда жаңа жүріс жоқ", + ], + [ + "No moves for this colour", + "Нет ходов за этот цвет", + "Aucun coup pour cette couleur", + "Keine Züge für diese Farbe", + "No hay jugadas de este color", + "Nessuna mossa per questo colore", + "Sem lances para esta cor", + "Bu rang uchun yurishlar yo‘q", + "Бұл түс үшін жүріс жоқ", + ], + [ + "Import", + "Импортировать", + "Importer", + "Importieren", + "Importar", + "Importa", + "Importar", + "Import qilish", + "Импорттау", + ], + [ + "No games with moves in this file", + "В файле нет партий с ходами", + "Aucune partie avec des coups dans ce fichier", + "Keine Partie mit Zügen in dieser Datei", + "No hay partidas con jugadas en este archivo", + "Nessuna partita con mosse in questo file", + "Nenhuma partida com lances neste arquivo", + "Bu faylda yurishli partiyalar yo‘q", + "Бұл файлда жүрісі бар партия жоқ", + ], + [ + "Saved to {path}", + "Сохранено: {path}", + "Enregistré : {path}", + "Gespeichert: {path}", + "Guardado en {path}", + "Salvato in {path}", + "Salvo em {path}", + "Saqlandi: {path}", + "Сақталды: {path}", + ], + [ + "{n} repertoires", + "Репертуаров: {n}", + "{n} répertoires", + "{n} Repertoires", + "{n} repertorios", + "{n} repertori", + "{n} repertórios", + "Repertuarlar: {n}", + "Репертуарлар: {n}", + ], + [ + "Could not read the repertoires: {e}", + "Не удалось прочитать репертуары: {e}", + "Impossible de lire les répertoires : {e}", + "Die Repertoires konnten nicht gelesen werden: {e}", + "No se pudieron leer los repertorios: {e}", + "Impossibile leggere i repertori: {e}", + "Não foi possível ler os repertórios: {e}", + "Repertuarlarni o‘qib bo‘lmadi: {e}", + "Репертуарларды оқу мүмкін болмады: {e}", + ], + [ + "{n} to review, {m} new", + "Повторить: {n}, новых: {m}", + "{n} à réviser, {m} nouveaux", + "{n} zu wiederholen, {m} neu", + "{n} para repasar, {m} nuevas", + "{n} da ripassare, {m} nuove", + "{n} para revisar, {m} novos", + "Takrorlash: {n}, yangi: {m}", + "Қайталау: {n}, жаңа: {m}", + ], + [ + "Play “{name}” as Black?", + "Играть «{name}» чёрными?", + "Jouer « {name} » avec les Noirs ?", + "„{name}“ mit Schwarz spielen?", + "¿Jugar «{name}» con negras?", + "Giocare «{name}» con il Nero?", + "Jogar “{name}” de pretas?", + "«{name}» ni qora bilan o‘ynaysizmi?", + "«{name}» қарамен ойнайсыз ба?", + ], + [ + "Play “{name}” as White?", + "Играть «{name}» белыми?", + "Jouer « {name} » avec les Blancs ?", + "„{name}“ mit Weiß spielen?", + "¿Jugar «{name}» con blancas?", + "Giocare «{name}» con il Bianco?", + "Jogar “{name}” de brancas?", + "«{name}» ni oq bilan o‘ynaysizmi?", + "«{name}» ақпен ойнайсыз ба?", + ], + [ + "You will be asked Black's moves: {y}. Progress for White is kept and comes back if you switch again.", + "Спрашиваться будут ходы чёрных: {y}. Прогресс за белых сохранится и вернётся, если переключить обратно.", + "On vous demandera les coups des Noirs : {y}. La progression des Blancs est conservée et revient si vous changez à nouveau.", + "Gefragt werden die Züge von Schwarz: {y}. Der Fortschritt für Weiß bleibt erhalten und kehrt beim Zurückwechseln zurück.", + "Se te preguntarán las jugadas de las negras: {y}. El progreso de las blancas se guarda y vuelve si cambias de nuevo.", + "Ti verranno chieste le mosse del Nero: {y}. I progressi del Bianco restano e tornano se cambi di nuovo.", + "Serão perguntados os lances das pretas: {y}. O progresso das brancas fica guardado e volta se você trocar de novo.", + "Qoraning yurishlari so‘raladi: {y}. Oq bo‘yicha natija saqlanadi va qayta almashtirsangiz qaytadi.", + "Қараның жүрістері сұралады: {y}. Ақтағы нәтиже сақталады және қайта ауыстырсаңыз қайтады.", + ], + [ + "You will be asked White's moves: {y}. Progress for Black is kept and comes back if you switch again.", + "Спрашиваться будут ходы белых: {y}. Прогресс за чёрных сохранится и вернётся, если переключить обратно.", + "On vous demandera les coups des Blancs : {y}. La progression des Noirs est conservée et revient si vous changez à nouveau.", + "Gefragt werden die Züge von Weiß: {y}. Der Fortschritt für Schwarz bleibt erhalten und kehrt beim Zurückwechseln zurück.", + "Se te preguntarán las jugadas de las blancas: {y}. El progreso de las negras se guarda y vuelve si cambias de nuevo.", + "Ti verranno chieste le mosse del Bianco: {y}. I progressi del Nero restano e tornano se cambi di nuovo.", + "Serão perguntados os lances das brancas: {y}. O progresso das pretas fica guardado e volta se você trocar de novo.", + "Oqning yurishlari so‘raladi: {y}. Qora bo‘yicha natija saqlanadi va qayta almashtirsangiz qaytadi.", + "Ақтың жүрістері сұралады: {y}. Қарадағы нәтиже сақталады және қайта ауыстырсаңыз қайтады.", + ], + [ + "Reset progress of “{name}”?", + "Сбросить прогресс «{name}»?", + "Réinitialiser la progression de « {name} » ?", + "Fortschritt von „{name}“ zurücksetzen?", + "¿Restablecer el progreso de «{name}»?", + "Azzerare i progressi di «{name}»?", + "Redefinir o progresso de “{name}”?", + "«{name}» natijasini tiklaysizmi?", + "«{name}» нәтижесін тастау керек пе?", + ], + [ + "All {y} moves of this repertoire become new again: answers and review dates are erased.", + "Все ходы этого репертуара ({y}) снова станут новыми: ответы и сроки повторений будут стёрты.", + "Les {y} coups de ce répertoire redeviennent nouveaux : réponses et dates de révision sont effacées.", + "Alle {y} Züge dieses Repertoires werden wieder neu: Antworten und Wiederholungstermine werden gelöscht.", + "Las {y} jugadas de este repertorio vuelven a ser nuevas: se borran las respuestas y las fechas de repaso.", + "Tutte le {y} mosse di questo repertorio tornano nuove: risposte e date di ripasso vengono cancellate.", + "Todos os {y} lances deste repertório voltam a ser novos: respostas e datas de revisão são apagadas.", + "Bu repertuarning barcha yurishlari ({y}) yana yangi bo‘ladi: javoblar va takrorlash muddatlari o‘chiriladi.", + "Бұл репертуардың барлық жүрісі ({y}) қайта жаңа болады: жауаптар мен қайталау мерзімдері өшіріледі.", + ], + [ + "{s} of these moves are also in: {names}. They become new there too.", + "Из них {s} встречаются также в: {names}. Там они тоже станут новыми.", + "{s} de ces coups sont aussi dans : {names}. Ils y redeviennent nouveaux aussi.", + "{s} dieser Züge stehen auch in: {names}. Dort werden sie ebenfalls neu.", + "{s} de estas jugadas también están en: {names}. Allí también vuelven a ser nuevas.", + "{s} di queste mosse sono anche in: {names}. Anche lì tornano nuove.", + "{s} desses lances também estão em: {names}. Lá eles também voltam a ser novos.", + "Ulardan {s} tasi bularda ham bor: {names}. U yerda ham yangi bo‘ladi.", + "Олардың {s} жүрісі мұнда да бар: {names}. Онда да жаңа болады.", + ], + [ + "Delete “{name}”?", + "Удалить «{name}»?", + "Supprimer « {name} » ?", + "„{name}“ löschen?", + "¿Eliminar «{name}»?", + "Eliminare «{name}»?", + "Excluir “{name}”?", + "«{name}» ni o‘chirasizmi?", + "«{name}» жою керек пе?", + ], + [ + "Today: {n} to review · {m} new", + "Сегодня: {n} повторить · {m} новых", + "Aujourd’hui : {n} à réviser · {m} nouveaux", + "Heute: {n} wiederholen · {m} neu", + "Hoy: {n} para repasar · {m} nuevas", + "Oggi: {n} da ripassare · {m} nuove", + "Hoje: {n} para revisar · {m} novos", + "Bugun: {n} ta takrorlash · {m} ta yangi", + "Бүгін: {n} қайталау · {m} жаңа", + ], + [ + "Today: {n} to review", + "Сегодня: {n} повторить", + "Aujourd’hui : {n} à réviser", + "Heute: {n} wiederholen", + "Hoy: {n} para repasar", + "Oggi: {n} da ripassare", + "Hoje: {n} para revisar", + "Bugun: {n} ta takrorlash", + "Бүгін: {n} қайталау", + ], + [ + "About {t} min", + "Примерно {t} мин", + "Environ {t} min", + "Etwa {t} Min.", + "Unos {t} min", + "Circa {t} min", + "Cerca de {t} min", + "Taxminan {t} daqiqa", + "Шамамен {t} мин", + ], + [ + "Today: {m} new moves", + "Сегодня: {m} новых ходов", + "Aujourd’hui : {m} nouveaux coups", + "Heute: {m} neue Züge", + "Hoy: {m} jugadas nuevas", + "Oggi: {m} mosse nuove", + "Hoje: {m} lances novos", + "Bugun: {m} ta yangi yurish", + "Бүгін: {m} жаңа жүріс", + ], + [ + "Next review: {when} · {n} moves", + "Следующее повторение: {when} · ходов: {n}", + "Prochaine révision : {when} · {n} coups", + "Nächste Wiederholung: {when} · {n} Züge", + "Próximo repaso: {when} · {n} jugadas", + "Prossimo ripasso: {when} · {n} mosse", + "Próxima revisão: {when} · {n} lances", + "Keyingi takrorlash: {when} · {n} ta yurish", + "Келесі қайталау: {when} · {n} жүріс", + ], + [ + "Learn {m} new", + "Учить {m} новых", + "Apprendre {m} nouveaux", + "{m} neue lernen", + "Aprender {m} nuevas", + "Impara {m} nuove", + "Aprender {m} novos", + "{m} ta yangisini o‘rganish", + "{m} жаңасын үйрену", + ], + [ + "Learned {x} of {y} moves", + "Выучено {x} из {y} ходов", + "{x} coups appris sur {y}", + "{x} von {y} Zügen gelernt", + "{x} de {y} jugadas aprendidas", + "{x} mosse imparate su {y}", + "{x} de {y} lances aprendidos", + "{y} ta yurishdan {x} tasi o‘rganildi", + "{y} жүрістің {x} үйренілді", + ], + [ + "{k} in progress", + "учится: {k}", + "{k} en cours", + "{k} in Arbeit", + "{k} en curso", + "{k} in corso", + "{k} em andamento", + "o‘rganilmoqda: {k}", + "үйренілуде: {k}", + ], + [ + "Add PGN to “{name}”", + "Добавить PGN в «{name}»", + "Ajouter un PGN à « {name} »", + "PGN zu „{name}“ hinzufügen", + "Añadir un PGN a «{name}»", + "Aggiungi un PGN a «{name}»", + "Adicionar PGN a “{name}”", + "«{name}» ga PGN qo‘shish", + "«{name}» ішіне PGN қосу", + ], + [ + "{m} new moves · {v} new lines", + "Новых ходов: {m} · новых вариантов: {v}", + "{m} nouveaux coups · {v} nouvelles lignes", + "{m} neue Züge · {v} neue Varianten", + "{m} jugadas nuevas · {v} líneas nuevas", + "{m} mosse nuove · {v} linee nuove", + "{m} lances novos · {v} linhas novas", + "Yangi yurishlar: {m} · yangi variantlar: {v}", + "Жаңа жүрістер: {m} · жаңа нұсқалар: {v}", + ], + [ + "{g} games · {v} lines · {y} your moves", + "Партий: {g} · вариантов: {v} · ваших ходов: {y}", + "{g} parties · {v} lignes · {y} de vos coups", + "{g} Partien · {v} Varianten · {y} eigene Züge", + "{g} partidas · {v} líneas · {y} jugadas tuyas", + "{g} partite · {v} linee · {y} tue mosse", + "{g} partidas · {v} linhas · {y} lances seus", + "Partiyalar: {g} · variantlar: {v} · yurishlaringiz: {y}", + "Партиялар: {g} · нұсқалар: {v} · сіздің жүрістеріңіз: {y}", + ], + [ + "Game {n}: could not be read", + "Партия {n}: не удалось прочитать", + "Partie {n} : illisible", + "Partie {n}: nicht lesbar", + "Partida {n}: no se pudo leer", + "Partita {n}: illeggibile", + "Partida {n}: não foi possível ler", + "{n}-partiya: o‘qib bo‘lmadi", + "{n}-партия: оқу мүмкін болмады", + ], + [ + "Game {n}: {message}", + "Партия {n}: {message}", + "Partie {n} : {message}", + "Partie {n}: {message}", + "Partida {n}: {message}", + "Partita {n}: {message}", + "Partida {n}: {message}", + "{n}-partiya: {message}", + "{n}-партия: {message}", + ], + [ + "Game {n} has no moves", + "В партии {n} нет ходов", + "La partie {n} n’a pas de coups", + "Partie {n} hat keine Züge", + "La partida {n} no tiene jugadas", + "La partita {n} non ha mosse", + "A partida {n} não tem lances", + "{n}-partiyada yurishlar yo‘q", + "{n}-партияда жүріс жоқ", + ], [ "Your turn: play a repertoire move.", "Ваш ход: сыграйте ход из репертуара.", @@ -20437,12 +21757,10 @@ mod tests { include_str!("chatgpt.rs"), include_str!("san.rs"), include_str!("prep_ui.rs"), - include_str!("learning_training.rs"), - include_str!("learning_context_controls.rs"), - include_str!("learning_branches.rs"), - include_str!("learning_charts.rs"), - include_str!("learning_dashboard.rs"), - include_str!("repertoire_editor.rs"), + include_str!("opening_layout.rs"), + include_str!("opening_lines.rs"), + include_str!("opening_session.rs"), + include_str!("repertoire_ui.rs"), ]; let mut chars = std::collections::BTreeSet::new(); for row in ROWS.iter() { @@ -20515,14 +21833,10 @@ mod tests { include_str!("chatgpt.rs"), include_str!("san.rs"), include_str!("prep_ui.rs"), - include_str!("learning_training.rs"), - include_str!("learning_context_controls.rs"), - include_str!("learning_branches.rs"), - include_str!("learning_charts.rs"), - include_str!("learning_dashboard.rs"), - include_str!("repertoire_editor.rs"), + include_str!("opening_layout.rs"), + include_str!("opening_lines.rs"), + include_str!("opening_session.rs"), include_str!("repertoire_ui.rs"), - include_str!("repertoire_training.rs"), ]; let mut missing = Vec::new(); let mut found = 0; diff --git a/apps/desktop/src/learning_branches.rs b/apps/desktop/src/learning_branches.rs deleted file mode 100644 index 1886709..0000000 --- a/apps/desktop/src/learning_branches.rs +++ /dev/null @@ -1,763 +0,0 @@ -use std::collections::HashMap; - -use egui::{Align, Layout, RichText, Sense, Ui}; -use egui_extras::{Column, TableBuilder}; -use trainer::repertoire::{BranchLearningAnalytics, RepertoireId}; - -use crate::i18n::tr; - -const HEADER_HEIGHT: f32 = 40.0; -const ROW_HEIGHT: f32 = 32.0; -const BODY_TEXT_SIZE: f32 = 14.0; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct BranchSelection { - pub repertoire_id: RepertoireId, - pub branch_root: Vec, -} - -pub fn show( - ui: &mut egui::Ui, - rows: &[BranchLearningAnalytics], - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - selected: &mut Option, -) { - ui.style_mut().interaction.selectable_labels = false; - if rows.is_empty() { - *selected = None; - ui.label(tr("No branches in this scope")); - return; - } - if selected - .as_ref() - .is_none_or(|selection| !rows.iter().any(|row| selection == &selection_for(row))) - { - *selected = Some(selection_for(&rows[0])); - } - - ui.add( - egui::Label::new(tr( - "Continuations to review. Shared moves may appear in several variations.", - )) - .wrap(), - ); - ui.add_space(6.0); - let include_repertoire = include_repertoire_names(rows); - let mut clicked = None; - show_table( - ui, - rows, - names, - labels, - include_repertoire, - selected.as_ref(), - &mut clicked, - ); - if let Some(selection) = clicked { - *selected = Some(selection); - } - - if let Some(selection) = selected.as_ref() - && let Some(row) = rows.iter().find(|row| selection == &selection_for(row)) - { - ui.separator(); - show_details(ui, row, names, labels, include_repertoire); - } -} - -fn selection_for(row: &BranchLearningAnalytics) -> BranchSelection { - BranchSelection { - repertoire_id: row.repertoire_id.clone(), - branch_root: row.branch_root.clone(), - } -} - -fn include_repertoire_names(rows: &[BranchLearningAnalytics]) -> bool { - rows.first().is_some_and(|first| { - rows.iter() - .any(|row| row.repertoire_id != first.repertoire_id) - }) -} - -fn san_path( - row: &BranchLearningAnalytics, - labels: &HashMap<(RepertoireId, Vec), Vec>, -) -> String { - let labels = labels.get(&(row.repertoire_id.clone(), row.branch_root.clone())); - row.branch_root - .iter() - .enumerate() - .map(|(index, uci)| { - let label = labels.and_then(|labels| labels.get(index)).unwrap_or(uci); - crate::san::show(label).into_owned() - }) - .collect::>() - .join(" ") -} - -fn branch_text( - row: &BranchLearningAnalytics, - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - include_repertoire: bool, -) -> String { - let path = san_path(row, labels); - if !include_repertoire { - return if path.is_empty() { - "—".to_owned() - } else { - path - }; - } - let name = names - .get(&row.repertoire_id) - .map_or_else(|| row.repertoire_id.as_str(), String::as_str); - if path.is_empty() { - name.to_owned() - } else { - format!("{name} · {path}") - } -} - -#[allow(clippy::too_many_arguments)] -fn show_table( - ui: &mut Ui, - rows: &[BranchLearningAnalytics], - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - include_repertoire: bool, - selected: Option<&BranchSelection>, - clicked: &mut Option, -) { - let numeric_width = (ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4 / 3.0; - TableBuilder::new(ui) - .id_salt("learning_branches") - .striped(true) - .sense(Sense::click()) - .max_scroll_height(192.0) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().clip(true)) - .column(Column::exact(numeric_width).clip(true)) - .column(Column::exact(numeric_width).clip(true)) - .column(Column::exact(numeric_width).clip(true)) - .header(HEADER_HEIGHT, |mut header| { - for (index, key) in ["Variation start", "Learnt", "Due now", "Accuracy"] - .into_iter() - .enumerate() - { - header.col(|ui| { - header_cell(ui, tr(key), index > 0); - }); - } - }) - .body(|body| { - body.rows(ROW_HEIGHT, rows.len(), |mut table_row| { - let row = &rows[table_row.index()]; - let selection = selection_for(row); - table_row.set_selected(selected == Some(&selection)); - table_row.col(|ui| { - let text = branch_text(row, names, labels, include_repertoire); - text_cell(ui, &text, false).on_hover_text(text); - }); - for value in [ - format!("{} / {}", row.summary.learnt, row.summary.total), - row.summary.due.to_string(), - format_percent(row.summary.accuracy_percent), - ] { - table_row.col(|ui| { - text_cell(ui, &value, true); - }); - } - if table_row.response().clicked() { - *clicked = Some(selection); - } - }); - }); -} - -fn show_details( - ui: &mut Ui, - row: &BranchLearningAnalytics, - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - include_repertoire: bool, -) { - let branch = branch_text(row, names, labels, include_repertoire); - ui.add(egui::Label::new(RichText::new(&branch).strong().size(BODY_TEXT_SIZE)).wrap()) - .on_hover_text(branch); - ui.add_space(4.0); - let details = [ - ( - "Learnt moves", - format!("{} / {}", row.summary.learnt, row.summary.total), - ), - ("Due now", row.summary.due.to_string()), - ("Not practised yet", row.summary.unseen.to_string()), - ("Accuracy", format_percent(row.summary.accuracy_percent)), - ]; - show_details_rows(ui, &details); -} - -fn show_details_rows(ui: &mut Ui, details: &[(&'static str, String)]) { - let label_width = (ui.available_width() * 0.36).clamp(110.0, 160.0); - TableBuilder::new(ui) - .id_salt("learning_branches_details") - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Min)) - .column(Column::exact(label_width).clip(true)) - .column(Column::remainder().at_least(80.0).clip(true)) - .body(|body| { - body.rows(36.0, details.len(), |mut row| { - let (label, value) = &details[row.index()]; - row.col(|ui| { - ui.add( - egui::Label::new(RichText::new(tr(label)).weak().size(BODY_TEXT_SIZE)) - .wrap(), - ); - }); - row.col(|ui| { - ui.add(egui::Label::new(RichText::new(value).size(BODY_TEXT_SIZE)).wrap()); - }); - }); - }); -} - -fn header_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response { - ui.add(egui::Label::new(RichText::new(text).strong().size(BODY_TEXT_SIZE)).wrap()) -} - -fn text_cell(ui: &mut Ui, text: &str, _numeric: bool) -> egui::Response { - ui.add(egui::Label::new(RichText::new(text).size(BODY_TEXT_SIZE)).truncate()) -} - -fn format_percent(value: Option) -> String { - value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")) -} - -#[cfg(test)] -mod tests { - use trainer::repertoire::{LearningAggregate, Repertoire}; - - use super::*; - - const BASE: i64 = 1_800_000_000; - - struct Fixture { - rows: Vec, - names: HashMap, - labels: HashMap<(RepertoireId, Vec), Vec>, - } - - fn fixture() -> Fixture { - let first = Repertoire::default().id; - let second = Repertoire::default().id; - let branch_root = vec!["e2e4".to_owned(), "e7e5".to_owned()]; - let summary = LearningAggregate { - total: 8, - unseen: 2, - learning: 2, - learnt: 4, - uncertain: 1, - learnt_confident: 3, - due: 3, - learnt_percent: Some(50.0), - accuracy_correct: 6, - accuracy_wrong: 2, - accuracy_attempts: 8, - accuracy_percent: Some(75.0), - ..LearningAggregate::default() - }; - let rows = vec![ - BranchLearningAnalytics { - repertoire_id: first.clone(), - branch_root: branch_root.clone(), - summary: summary.clone(), - last_independent_at: Some(BASE), - }, - BranchLearningAnalytics { - repertoire_id: second.clone(), - branch_root: branch_root.clone(), - summary, - last_independent_at: Some(BASE), - }, - ]; - let names = HashMap::from([ - (first.clone(), "First".to_owned()), - (second.clone(), "Second".to_owned()), - ]); - let labels = HashMap::from([ - ( - (first, branch_root.clone()), - vec!["1.e4".to_owned(), "1...e5".to_owned()], - ), - ((second, branch_root), vec!["1.e4".to_owned()]), - ]); - Fixture { - rows, - names, - labels, - } - } - - #[allow(clippy::too_many_arguments)] - fn render( - ctx: &egui::Context, - width: f32, - height: f32, - time: f64, - events: Vec, - rows: &[BranchLearningAnalytics], - names: &HashMap, - labels: &HashMap<(RepertoireId, Vec), Vec>, - selected: &mut Option, - ) -> Vec { - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - show(ui, rows, names, labels, selected); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - shapes - } - - fn has_text(shapes: &[egui::epaint::ClippedShape], expected: &str) -> bool { - shapes.iter().any(|clipped| match &clipped.shape { - egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected, - _ => false, - }) - } - - fn has_translated_text(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> bool { - crate::i18n::all_languages(key) - .into_iter() - .any(|translation| has_text(shapes, translation)) - } - - fn text_position(shapes: &[egui::epaint::ClippedShape], expected: &str) -> Option { - shapes.iter().find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text().replace('\n', " ") == expected => { - Some(text.pos + egui::vec2(8.0, 6.0)) - } - _ => None, - }) - } - - fn text_occurrences(shapes: &[egui::epaint::ClippedShape], expected: &str) -> usize { - shapes - .iter() - .filter(|clipped| match &clipped.shape { - egui::Shape::Text(text) => text.galley.text().replace('\n', " ") == expected, - _ => false, - }) - .count() - } - - fn click(position: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] - } - - fn assert_bounds(shapes: &[egui::epaint::ClippedShape], width: f32, height: f32) { - for clipped in shapes { - let bounds = clipped.shape.visual_bounding_rect(); - if bounds.is_finite() && bounds.is_positive() { - assert!( - bounds.min.x >= -0.5 - && bounds.min.y >= -0.5 - && bounds.max.x <= width + 0.5 - && bounds.max.y <= height + 0.5, - "shape outside {width}x{height}: {bounds:?}" - ); - } - } - } - - #[test] - fn summarized_shared_rows_are_not_deduplicated_and_labels_fall_back_to_uci() { - let fixture = fixture(); - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - 1200.0, - 800.0, - 0.0, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, Some(selection_for(&fixture.rows[0]))); - assert!(has_text(&shapes, "First · 1.e4 1...e5")); - assert!(has_text(&shapes, "Second · 1.e4 e7e5")); - - let names = fixture.names.clone(); - let shapes = render( - &ctx, - 1200.0, - 800.0, - 1.0, - Vec::new(), - &fixture.rows[..1], - &names, - &fixture.labels, - &mut selected, - ); - assert!(has_text(&shapes, "1.e4 1...e5")); - assert!(!has_text(&shapes, "First · 1.e4 1...e5")); - } - - #[test] - fn unified_layout_stays_in_bounds_in_light_and_dark() { - let fixture = fixture(); - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let mut selected = None; - for pass in 0..2 { - let shapes = render( - &ctx, - width, - height, - pass as f64, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert!(!shapes.is_empty()); - assert_bounds(&shapes, width, height); - for key in [ - "Variation start", - "Learnt", - "Due now", - "Accuracy", - "Learnt moves", - "Not practised yet", - ] { - assert!( - has_translated_text(&shapes, key), - "missing header/detail {key}" - ); - } - } - } - } - } - - #[test] - fn headers_fit_accepted_matrix_in_russian_and_german() { - let cases = [ - ["Начало варианта", "Изучено", "Повторить", "Точность"], - ["Variantenanfang", "Gelernt", "Wiederholen", "Genauigkeit"], - ]; - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for (width, height) in [(960.0, 600.0), (1400.0, 900.0)] { - for headers in &cases { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - ..Default::default() - }, - |ui| { - let numeric_width = - (ui.available_width() - 3.0 * ui.spacing().item_spacing.x) * 0.4 - / 3.0; - let mut table = TableBuilder::new(ui) - .id_salt("learning_branches_wide_header_test") - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(120.0).clip(true)); - for _ in 0..3 { - table = table.column(Column::exact(numeric_width).clip(true)); - } - table.header(HEADER_HEIGHT, |mut header| { - for (index, key) in headers.iter().enumerate() { - header.col(|ui| { - header_cell(ui, tr(key), index > 0); - }); - } - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - assert_bounds(&shapes, width, height); - for expected in headers { - let (rect, clip, lines) = shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) - if text.galley.text().replace('\n', " ") == *expected => - { - Some(( - egui::Rect::from_min_size(text.pos, text.galley.size()), - clipped.clip_rect, - text.galley.text().lines().count(), - )) - } - _ => None, - }) - .unwrap_or_else(|| { - panic!("missing full header {expected} at {width}x{height}") - }); - assert!(lines <= 2, "header wraps too much: {expected}"); - assert!( - rect.min.x >= clip.min.x - 0.1 - && rect.min.y >= clip.min.y - 0.1 - && rect.max.x <= clip.max.x + 0.1 - && rect.max.y <= clip.max.y + 0.1, - "clipped header {expected} at {width}x{height}: {rect:?} {clip:?}" - ); - } - } - } - } - } - - #[test] - fn details_are_visible_and_click_selects_the_branch() { - let fixture = fixture(); - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - 640.0, - 480.0, - 0.0, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, Some(selection_for(&fixture.rows[0]))); - let second = text_position(&shapes, "Second · 1.e4 e7e5") - .expect("second branch row should be visible"); - let shapes = render( - &ctx, - 640.0, - 480.0, - 1.0, - click(second), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, Some(selection_for(&fixture.rows[1]))); - assert!(text_occurrences(&shapes, "Second · 1.e4 e7e5") >= 2); - for key in ["Learnt moves", "Due now", "Not practised yet", "Accuracy"] { - assert!(has_translated_text(&shapes, key), "missing detail {key}"); - } - } - - #[test] - fn details_keep_long_labels_readable_at_all_widths() { - let cases: Vec> = vec![ - vec![ - ("Новый", "2".to_owned()), - ("Изучается", "1".to_owned()), - ("Изучено", "4".to_owned()), - ("Не подтверждено", "1".to_owned()), - ("К повторению", "3".to_owned()), - ("Точность", "75 %".to_owned()), - ("Последняя тренировка", "2026-11-04 08:26".to_owned()), - ], - vec![ - ("Neu", "2".to_owned()), - ("Wird gelernt", "1".to_owned()), - ("Gelernt", "4".to_owned()), - ("Nicht bestätigt", "1".to_owned()), - ("Fällig", "3".to_owned()), - ("Genauigkeit", "75 %".to_owned()), - ("Zuletzt trainiert", "2026-11-04 08:26".to_owned()), - ], - ]; - for visuals in [egui::Visuals::light(), egui::Visuals::dark()] { - for width in [320.0, 360.0, 420.0, 640.0] { - for details in &cases { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let mut expected_label_width = 0.0; - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, 700.0), - )), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - expected_label_width = - (ui.available_width() * 0.36).clamp(110.0, 160.0); - show_details_rows(ui, details); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - assert_bounds(&shapes, width, 700.0); - for (label, _) in details { - let (clip, lines) = shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) - if text.galley.text().replace('\n', " ") == *label => - { - Some((clipped.clip_rect, text.galley.text().lines().count())) - } - _ => None, - }) - .unwrap_or_else(|| panic!("missing full label {label} at {width}")); - assert!( - (clip.width() - expected_label_width).abs() < 0.1, - "label column at {width}: {clip:?}, expected {expected_label_width}: {label}" - ); - assert!(lines <= 2, "label wraps too much at {width}: {label}"); - } - assert!(has_text(&shapes, "2026-11-04 08:26")); - assert!(has_text(&shapes, "75 %")); - } - } - } - } - - #[test] - fn null_accuracy_renders_as_dashes_in_table_and_details() { - let fixture = fixture(); - let mut row = fixture.rows[0].clone(); - row.summary.accuracy_percent = None; - row.summary.learnt_percent = None; - row.last_independent_at = None; - let names = HashMap::from([(row.repertoire_id.clone(), "Only".to_owned())]); - let labels = HashMap::new(); - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - 640.0, - 480.0, - 0.0, - Vec::new(), - std::slice::from_ref(&row), - &names, - &labels, - &mut selected, - ); - let dashes = text_occurrences(&shapes, "—"); - assert!( - dashes >= 2, - "expected null accuracy in table and details: {dashes}" - ); - assert_eq!(format_percent(None), "—"); - assert_eq!(format_percent(Some(75.0)), "75 %"); - } - - #[test] - fn long_selected_notation_wraps_in_details_and_row_retains_wide_column() { - let mut fixture = fixture(); - fixture.rows.truncate(1); - fixture.rows[0].branch_root = (0..40).map(|i| format!("move{i}")).collect(); - let notation: Vec<_> = (1..=40).map(|i| format!("{i}.Nf3")).collect(); - fixture.labels.insert( - ( - fixture.rows[0].repertoire_id.clone(), - fixture.rows[0].branch_root.clone(), - ), - notation, - ); - let expected = san_path(&fixture.rows[0], &fixture.labels); - for width in [960.0, 1400.0] { - let ctx = egui::Context::default(); - let mut selected = None; - let shapes = render( - &ctx, - width, - 900.0, - 0.0, - Vec::new(), - &fixture.rows, - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_bounds(&shapes, width, 900.0); - let texts: Vec<_> = shapes - .iter() - .filter_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text() == expected => { - Some((clipped, text)) - } - _ => None, - }) - .collect(); - assert_eq!(texts.len(), 2, "table row and full selected notation"); - assert!(texts[0].0.clip_rect.width() >= width * 0.5); - assert_eq!( - texts[0].1.galley.rows.len(), - 1, - "table notation stays on one line" - ); - assert!( - texts[1].1.galley.rows.len() > 1, - "full selected notation wraps" - ); - assert!(has_text(&shapes, "4 / 8")); - } - } - - #[test] - fn empty_scope_clears_selection() { - let fixture = fixture(); - let ctx = egui::Context::default(); - let mut selected = Some(selection_for(&fixture.rows[0])); - let shapes = render( - &ctx, - 640.0, - 480.0, - 0.0, - Vec::new(), - &[], - &fixture.names, - &fixture.labels, - &mut selected, - ); - assert_eq!(selected, None); - assert!(has_translated_text(&shapes, "No branches in this scope")); - } -} diff --git a/apps/desktop/src/learning_charts.rs b/apps/desktop/src/learning_charts.rs deleted file mode 100644 index 7712335..0000000 --- a/apps/desktop/src/learning_charts.rs +++ /dev/null @@ -1,507 +0,0 @@ -use std::{collections::BTreeMap, fmt}; - -use egui::{ - Align2, Color32, FontId, Painter, Pos2, Rect, RichText, Sense, Shape, Stroke, Ui, Visuals, - pos2, vec2, -}; -use trainer::repertoire::{LearningSnapshot, ScheduledBuckets, SequenceHistograms}; - -use crate::i18n::tr; - -const CHART_HEIGHT: f32 = 180.0; -const HISTORY_DATE_HEIGHT: f32 = 18.0; -const SCHEDULED_LABEL_HEIGHT: f32 = 40.0; -const HISTOGRAM_LABEL_HEIGHT: f32 = 28.0; -const MAX_HISTOGRAM_BARS: usize = 12; -const WIDE_SEQUENCE_WIDTH: f32 = 900.0; - -#[derive(Clone, Copy)] -enum Marker { - Circle, - Square, - Diamond, -} - -type HistorySeries = (Color32, Marker, fn(&LearningSnapshot) -> usize); - -impl Marker { - fn paint(self, painter: &Painter, center: Pos2, color: Color32) { - match self { - Self::Circle => { - painter.circle_filled(center, 2.8, color); - } - Self::Square => { - painter.rect_filled(Rect::from_center_size(center, vec2(5.2, 5.2)), 0.0, color); - } - Self::Diamond => { - painter.add(Shape::convex_polygon( - vec![ - pos2(center.x, center.y - 3.4), - pos2(center.x + 3.4, center.y), - pos2(center.x, center.y + 3.4), - pos2(center.x - 3.4, center.y), - ], - color, - Stroke::NONE, - )); - } - } - } -} - -pub fn history(ui: &mut Ui, snapshots: &[LearningSnapshot]) { - if snapshots.is_empty() { - return; - } - let palette = series_palette(ui.visuals()); - history_legend(ui, &palette); - ui.add_space(4.0); - - let mut ordered = snapshots.iter().collect::>(); - ordered.sort_by_key(|snapshot| snapshot.as_of); - let (Some(first), Some(last)) = (ordered.first(), ordered.last()) else { - return; - }; - let start = first.as_of; - let end = last.as_of; - let max_value = snapshots.iter().fold(0_usize, |max, snapshot| { - max.max(snapshot.learning) - .max(snapshot.learnt) - .max(snapshot.uncertain) - }); - - let (rect, painter) = chart_area(ui); - let plot = plot_rect(&painter, rect, max_value, HISTORY_DATE_HEIGHT); - draw_axes(&painter, plot, max_value, ui.visuals()); - - let series: [HistorySeries; 3] = [ - (palette[0], Marker::Circle, |snapshot| snapshot.learning), - (palette[1], Marker::Square, |snapshot| snapshot.learnt), - (palette[2], Marker::Diamond, |snapshot| snapshot.uncertain), - ]; - for (color, marker, value) in series { - let points = ordered - .iter() - .map(|snapshot| { - pos2( - time_x(snapshot.as_of, start, end, plot.left(), plot.right()), - value_y(value(snapshot), max_value, plot.top(), plot.bottom()), - ) - }) - .collect::>(); - if points.len() >= 2 { - painter.add(Shape::line(points.clone(), Stroke::new(1.6, color))); - } - for point in points { - marker.paint(&painter, point, color); - } - } - - let text_color = ui.visuals().weak_text_color(); - if ordered.len() == 1 { - painter.text( - pos2(plot.center().x, rect.bottom()), - Align2::CENTER_BOTTOM, - &first.date, - label_font(), - text_color, - ); - } else { - painter.text( - pos2(plot.left(), rect.bottom()), - Align2::LEFT_BOTTOM, - &first.date, - label_font(), - text_color, - ); - painter.text( - pos2(plot.right(), rect.bottom()), - Align2::RIGHT_BOTTOM, - &last.date, - label_font(), - text_color, - ); - } -} - -pub fn scheduled(ui: &mut Ui, buckets: ScheduledBuckets) { - let rows = [ - (tr("Overdue").to_owned(), buckets.overdue), - (tr("Today").to_owned(), buckets.today), - (tr("Next 7 days").to_owned(), buckets.week), - (tr("Next 30 days").to_owned(), buckets.month), - (tr("Next 365 days").to_owned(), buckets.year), - (tr("Later").to_owned(), buckets.later), - ]; - let color = series_palette(ui.visuals())[0]; - bar_chart(ui, &rows, color, SCHEDULED_LABEL_HEIGHT, 56.0); -} - -pub fn sequences(ui: &mut Ui, histograms: &SequenceHistograms) { - let correct = histogram_rows(&histograms.correct_streak); - let wrong = histogram_rows(&histograms.wrong_streak); - let attempts = histogram_rows(&histograms.attempts); - let palette = series_palette(ui.visuals()); - - if ui.available_width() >= WIDE_SEQUENCE_WIDTH { - ui.columns(3, |columns| { - sequence_chart(&mut columns[0], "Correct streak", &correct, palette[1]); - sequence_chart(&mut columns[1], "Wrong streak", &wrong, palette[2]); - sequence_chart(&mut columns[2], "Attempts", &attempts, palette[0]); - }); - } else { - sequence_chart(ui, "Correct streak", &correct, palette[1]); - sequence_chart(ui, "Wrong streak", &wrong, palette[2]); - sequence_chart(ui, "Attempts", &attempts, palette[0]); - } -} - -fn history_legend(ui: &mut Ui, palette: &[Color32; 3]) { - ui.horizontal_wrapped(|ui| { - for (key, color, marker) in [ - ("Still learning", palette[0], Marker::Circle), - ("Learnt moves", palette[1], Marker::Square), - ("Long overdue learnt moves", palette[2], Marker::Diamond), - ] { - ui.horizontal(|ui| { - let (rect, _) = ui.allocate_exact_size(vec2(18.0, 12.0), Sense::hover()); - let painter = ui.painter().with_clip_rect(rect); - let y = rect.center().y; - painter.line_segment( - [pos2(rect.left(), y), pos2(rect.right(), y)], - Stroke::new(1.6, color), - ); - marker.paint(&painter, rect.center(), color); - ui.label(tr(key)); - }); - } - }); -} - -fn sequence_chart(ui: &mut Ui, title: &'static str, rows: &[(String, usize)], color: Color32) { - ui.add(egui::Label::new(RichText::new(tr(title)).strong()).truncate()); - ui.add_space(4.0); - bar_chart(ui, rows, color, HISTOGRAM_LABEL_HEIGHT, 38.0); - ui.add_space(10.0); -} - -fn chart_area(ui: &mut Ui) -> (Rect, Painter) { - let width = ui.available_width().max(1.0); - let (rect, _) = ui.allocate_exact_size(vec2(width, CHART_HEIGHT), Sense::hover()); - let painter = ui.painter().with_clip_rect(rect); - (rect, painter) -} - -fn plot_rect(painter: &Painter, rect: Rect, max_value: usize, label_height: f32) -> Rect { - let text_color = Color32::TRANSPARENT; - let y_label_width = [max_value.to_string(), "0".to_owned()] - .into_iter() - .map(|label| { - painter - .layout_no_wrap(label, label_font(), text_color) - .size() - .x - }) - .fold(0.0_f32, f32::max); - let reserved = (y_label_width + 8.0).min((rect.width() - 32.0).max(0.0)); - let right = (rect.right() - 4.0).max(rect.left()); - let left = (rect.left() + reserved).min(right); - let top = (rect.top() + 6.0).min(rect.bottom()); - let bottom = (rect.bottom() - label_height).max(top).min(rect.bottom()); - Rect::from_min_max(pos2(left, top), pos2(right, bottom)) -} - -fn draw_axes(painter: &Painter, plot: Rect, max_value: usize, visuals: &Visuals) { - let grid_color = visuals.weak_text_color().gamma_multiply(0.18); - for y in [plot.top(), plot.center().y, plot.bottom()] { - painter.line_segment( - [pos2(plot.left(), y), pos2(plot.right(), y)], - Stroke::new(1.0, grid_color), - ); - } - let axis_color = visuals.weak_text_color().gamma_multiply(0.55); - painter.line_segment( - [plot.left_top(), plot.left_bottom()], - Stroke::new(1.0, axis_color), - ); - painter.line_segment( - [plot.left_bottom(), plot.right_bottom()], - Stroke::new(1.0, axis_color), - ); - let text_color = visuals.weak_text_color(); - painter.text( - pos2(plot.left() - 6.0, plot.top()), - Align2::RIGHT_TOP, - max_value, - label_font(), - text_color, - ); - painter.text( - pos2(plot.left() - 6.0, plot.bottom()), - Align2::RIGHT_BOTTOM, - 0, - label_font(), - text_color, - ); -} - -fn bar_chart( - ui: &mut Ui, - rows: &[(String, usize)], - color: Color32, - label_height: f32, - max_bar_width: f32, -) { - let max_value = rows.iter().map(|(_, count)| *count).max().unwrap_or(0); - let (rect, painter) = chart_area(ui); - let plot = plot_rect(&painter, rect, max_value, label_height); - draw_axes(&painter, plot, max_value, ui.visuals()); - if rows.is_empty() { - return; - } - - let slot_width = (plot.width() / rows.len() as f32).max(0.0); - let text_color = ui.visuals().weak_text_color(); - for (index, (label, count)) in rows.iter().enumerate() { - let center = plot.left() + (index as f32 + 0.5) * slot_width; - if *count > 0 && max_value > 0 { - let width = (slot_width - 6.0).max(0.0).min(max_bar_width); - if width > 0.0 { - let top = value_y(*count, max_value, plot.top(), plot.bottom()); - painter.rect_filled( - Rect::from_min_max( - pos2(center - width / 2.0, top), - pos2(center + width / 2.0, plot.bottom()), - ), - 0.0, - color, - ); - } - } - let galley = painter.layout(label.clone(), label_font(), text_color, slot_width.max(1.0)); - painter.galley( - pos2( - center - galley.size().x / 2.0, - rect.bottom() - galley.size().y, - ), - galley, - text_color, - ); - } -} - -fn value_y(value: usize, max_value: usize, top: f32, bottom: f32) -> f32 { - if max_value == 0 { - return bottom; - } - let fraction = (value as f64 / max_value as f64).clamp(0.0, 1.0) as f32; - bottom - (bottom - top) * fraction -} - -fn time_x(at: i64, start: i64, end: i64, left: f32, right: f32) -> f32 { - if start == end { - return (left + right) / 2.0; - } - let numerator = i128::from(at) - i128::from(start); - let denominator = i128::from(end) - i128::from(start); - let fraction = (numerator as f64 / denominator as f64).clamp(0.0, 1.0) as f32; - left + (right - left) * fraction -} - -fn histogram_rows(histogram: &BTreeMap) -> Vec<(String, usize)> { - if histogram.len() <= MAX_HISTOGRAM_BARS { - return histogram - .iter() - .map(|(value, count)| (value.to_string(), *count)) - .collect(); - } - - let mut rows = histogram - .iter() - .take(MAX_HISTOGRAM_BARS - 1) - .map(|(value, count)| (value.to_string(), *count)) - .collect::>(); - if let Some((value, _)) = histogram.iter().nth(MAX_HISTOGRAM_BARS - 1) { - let count = histogram - .iter() - .skip(MAX_HISTOGRAM_BARS - 1) - .fold(0_usize, |sum, (_, count)| sum.saturating_add(*count)); - rows.push((format!("{value}+"), count)); - } - rows -} - -fn series_palette(visuals: &Visuals) -> [Color32; 3] { - if visuals.dark_mode { - [ - Color32::from_rgb(112, 184, 232), - Color32::from_rgb(126, 200, 150), - Color32::from_rgb(232, 174, 100), - ] - } else { - [ - Color32::from_rgb(35, 105, 155), - Color32::from_rgb(45, 125, 80), - Color32::from_rgb(170, 95, 35), - ] - } -} - -fn label_font() -> FontId { - FontId::proportional(12.0) -} - -#[cfg(test)] -mod tests { - use trainer::repertoire::{LearningSide, LocalDatePolicy, StatsScope}; - - use super::*; - - fn snapshot( - at: i64, - date: &str, - learning: usize, - learnt: usize, - uncertain: usize, - ) -> LearningSnapshot { - LearningSnapshot { - date: date.to_owned(), - scope: StatsScope::new(Vec::new(), LearningSide::White, at), - as_of: at, - timezone: LocalDatePolicy::UTC, - total: learning + learnt, - unseen: 0, - learning, - learnt, - uncertain, - due: 0, - } - } - - fn input(width: f32, height: f32) -> egui::RawInput { - egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(width, height))), - time: Some(0.0), - ..Default::default() - } - } - - #[test] - fn value_scaling_has_stable_endpoints() { - assert_eq!(value_y(0, 20, 10.0, 150.0), 150.0); - assert_eq!(value_y(20, 20, 10.0, 150.0), 10.0); - assert_eq!(value_y(10, 20, 10.0, 150.0), 80.0); - } - - #[test] - fn zero_scaling_stays_on_the_baseline() { - assert_eq!(value_y(0, 0, 10.0, 150.0), 150.0); - } - - #[test] - fn one_time_point_is_centered() { - assert_eq!(time_x(42, 42, 42, 20.0, 220.0), 120.0); - } - - #[test] - fn time_scaling_handles_the_full_timestamp_range() { - assert_eq!(time_x(i64::MIN, i64::MIN, i64::MAX, 20.0, 220.0), 20.0); - assert_eq!(time_x(i64::MAX, i64::MIN, i64::MAX, 20.0, 220.0), 220.0); - let middle = time_x(0, i64::MIN, i64::MAX, 20.0, 220.0); - assert!((middle - 120.0).abs() < 0.001); - } - - #[test] - fn histogram_tail_preserves_zero_and_total() { - let histogram = (0_u64..25).map(|value| (value, 1_usize)).collect(); - let rows = histogram_rows(&histogram); - assert_eq!(rows.len(), MAX_HISTOGRAM_BARS); - assert_eq!(rows[0], ("0".to_owned(), 1)); - assert_eq!(rows.last(), Some(&("11+".to_owned(), 14))); - assert_eq!(rows.iter().map(|(_, count)| count).sum::(), 25); - } - - #[test] - fn one_snapshot_paints_a_visible_marker() { - let snapshots = [snapshot(42, "2026-11-04", 2, 3, 1)]; - let ctx = egui::Context::default(); - let output = ctx.run_ui(input(640.0, 480.0), |ui| history(ui, &snapshots)); - assert!( - output - .shapes - .iter() - .any(|clipped| matches!(&clipped.shape, Shape::Circle(_))) - ); - output.drop_without_applying_deltas(); - } - - #[test] - fn charts_render_wide_narrow_light_and_dark_without_horizontal_overflow() { - let snapshots = vec![ - snapshot(100, "2026-11-02", 8, 2, 0), - snapshot(200, "2026-11-03", 5, 5, 1), - snapshot(300, "2026-11-04", 3, 9, 2), - ]; - let scheduled_buckets = ScheduledBuckets { - overdue: 4, - today: 2, - week: 7, - month: 3, - year: 5, - later: 1, - }; - let histograms = SequenceHistograms { - correct_streak: (0_u32..18).map(|key| (key, 2)).collect(), - wrong_streak: BTreeMap::from([(0, 8), (1, 3), (2, 1)]), - attempts: (0_u64..16).map(|key| (key, 1)).collect(), - }; - - for visuals in [Visuals::light(), Visuals::dark()] { - for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] { - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - for _ in 0..2 { - let output = ctx.run_ui(input(width, height), |ui| { - history(ui, &snapshots); - ui.separator(); - scheduled(ui, scheduled_buckets); - ui.separator(); - sequences(ui, &histograms); - }); - assert!(!output.shapes.is_empty()); - for clipped in &output.shapes { - let bounds = clipped - .shape - .visual_bounding_rect() - .intersect(clipped.clip_rect); - if bounds.is_finite() && bounds.is_positive() { - assert!( - bounds.min.x >= -0.5 && bounds.max.x <= width + 0.5, - "horizontal overflow at {width}x{height}: {bounds:?}" - ); - } - } - output.drop_without_applying_deltas(); - } - } - } - } - - #[test] - fn empty_and_all_zero_inputs_render() { - let zero_histograms = SequenceHistograms { - correct_streak: BTreeMap::from([(0, 0)]), - wrong_streak: BTreeMap::from([(0, 0)]), - attempts: BTreeMap::from([(0_u64, 0)]), - }; - let ctx = egui::Context::default(); - let output = ctx.run_ui(input(640.0, 480.0), |ui| { - history(ui, &[]); - scheduled(ui, ScheduledBuckets::default()); - sequences(ui, &SequenceHistograms::default()); - sequences(ui, &zero_histograms); - }); - assert!(!output.shapes.is_empty()); - output.drop_without_applying_deltas(); - } -} diff --git a/apps/desktop/src/learning_context_controls.rs b/apps/desktop/src/learning_context_controls.rs deleted file mode 100644 index fca2448..0000000 --- a/apps/desktop/src/learning_context_controls.rs +++ /dev/null @@ -1,204 +0,0 @@ -use trainer::repertoire::LearningContextPolicy; - -use crate::i18n::tr; - -fn hint(ui: &mut egui::Ui, text: &'static str) { - ui.add(egui::Label::new(egui::RichText::new(tr(text)).weak()).wrap()); -} - -pub fn show(ui: &mut egui::Ui, policy: &mut LearningContextPolicy) -> bool { - let before = *policy; - ui.strong(tr("Moves before the task")); - hint(ui, "The app shows the moves leading to the task position."); - ui.add_space(6.0); - ui.checkbox( - &mut policy.consider_leadup_moves, - tr("Ask me to play preceding moves"), - ); - ui.add_enabled_ui( - policy.consider_leadup_moves || !policy.use_fixed_piece_speed, - |ui| { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Correct answers in a row")); - ui.add( - egui::DragValue::new(&mut policy.reinforce_minimum_correct).range(0..=u32::MAX), - ); - }); - }, - ); - hint( - ui, - "Ask until this streak is reached. This also sets the maximum acceleration point for adaptive playback.", - ); - ui.add_space(6.0); - ui.add_enabled_ui(policy.consider_leadup_moves, |ui| { - let mut enabled = policy.reinforce_minimum_days.is_some(); - if ui - .checkbox(&mut enabled, tr("Review ahead of schedule")) - .changed() - { - policy.reinforce_minimum_days = enabled.then_some(7); - } - ui.add_enabled_ui(enabled, |ui| { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Days before the due date")); - let mut days = policy.reinforce_minimum_days.unwrap_or(7); - if ui - .add(egui::DragValue::new(&mut days).range(0..=u32::MAX)) - .changed() - { - policy.reinforce_minimum_days = Some(days); - } - }); - }); - }); - hint(ui, "Also ask moves that are already due."); - ui.add_space(10.0); - ui.separator(); - ui.strong(tr("Skip a familiar opening")); - ui.horizontal_wrapped(|ui| { - ui.label(tr("Skip after this many correct answers in a row")); - ui.add( - egui::DragValue::new(&mut policy.dont_show_start_moves_threshold).range(0..=u32::MAX), - ); - }); - hint( - ui, - "Each of your opening moves must reach this streak. 0 means always show the opening.", - ); - ui.add_space(10.0); - ui.separator(); - ui.strong(tr("Playback speed")); - let mut adaptive = !policy.use_fixed_piece_speed; - if ui - .checkbox(&mut adaptive, tr("Speed up familiar moves")) - .changed() - { - policy.use_fixed_piece_speed = !adaptive; - } - hint( - ui, - "Base animation speed comes from board settings. Familiar moves play up to twice as fast.", - ); - if adaptive { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Base speed multiplier")); - ui.add(egui::DragValue::new(&mut policy.move_speed_adjustment) - .range(-2.0..=2.0).speed(0.05).fixed_decimals(2).suffix(" ×")) - .on_hover_text(tr("Range −2…2. Adaptive speed = adjustment × (1 + learned fraction), limited to 0.25×–4×: 1.5 gives 3× for a fully learned move; 0 or less gives 0.25×.")); - }); - hint(ui, "0 or less uses the minimum speed (0.25×)."); - } - ui.add_space(6.0); - hint(ui, "Learning counters do not use these playback settings."); - *policy != before -} - -#[cfg(test)] -mod tests { - use super::*; - - fn render( - ctx: &egui::Context, - width: f32, - height: f32, - container_width: f32, - time: f64, - events: Vec, - policy: &mut LearningContextPolicy, - ) -> (Vec, bool, egui::Rect) { - let mut changed = false; - let mut container = - egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(container_width, height)); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - let available = ui.available_rect_before_wrap(); - container = egui::Rect::from_min_size( - available.min, - egui::vec2(container_width, available.height()), - ); - ui.scope_builder(egui::UiBuilder::new().max_rect(container), |ui| { - ui.set_clip_rect(container); - changed = show(ui, policy); - }); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - (shapes, changed, container) - } - - fn text_rect(shapes: &[egui::epaint::ClippedShape], key: &'static str) -> Option { - let translations = crate::i18n::all_languages(key); - shapes.iter().find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) - if translations - .iter() - .any(|candidate| *candidate == text.galley.text()) => - { - Some(egui::Rect::from_min_size(text.pos, text.galley.size())) - } - _ => None, - }) - } - - fn text_position( - shapes: &[egui::epaint::ClippedShape], - key: &'static str, - ) -> Option { - text_rect(shapes, key).map(|rect| rect.min + egui::vec2(8.0, 6.0)) - } - - fn click(position: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] - } - - #[test] - fn context_options_preserve_values_until_changed_and_enable_dependencies() { - let ctx = egui::Context::default(); - let mut policy = LearningContextPolicy::default(); - let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 0.0, Vec::new(), &mut policy); - assert!(!changed); - assert_eq!(policy, LearningContextPolicy::default()); - let leadup = text_position(&shapes, "Ask me to play preceding moves").unwrap(); - let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 1.0, click(leadup), &mut policy); - assert!(changed); - assert!(policy.consider_leadup_moves); - let (shapes, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 2.0, Vec::new(), &mut policy); - assert!(!changed); - let days = text_position(&shapes, "Review ahead of schedule").unwrap(); - let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 3.0, click(days), &mut policy); - assert!(changed); - assert_eq!(policy.reinforce_minimum_days, Some(7)); - let speed = text_position(&shapes, "Speed up familiar moves").unwrap(); - let (_, changed, _) = render(&ctx, 640.0, 1000.0, 440.0, 4.0, click(speed), &mut policy); - assert!(changed); - assert!(!policy.use_fixed_piece_speed); - assert_eq!(policy.move_speed_adjustment, 1.0); - } -} diff --git a/apps/desktop/src/learning_dashboard.rs b/apps/desktop/src/learning_dashboard.rs deleted file mode 100644 index 55cad56..0000000 --- a/apps/desktop/src/learning_dashboard.rs +++ /dev/null @@ -1,1968 +0,0 @@ -use std::{ - collections::HashMap, - sync::mpsc::{self, Receiver, Sender}, - time::Duration, -}; - -use chess_core::shakmaty::{CastlingMode, Chess, fen::Fen, san::San, uci::UciMove}; -use egui::{Align, Key, Layout, Modifiers, RichText, Ui}; -use egui_extras::{Column, TableBuilder}; -use trainer::repertoire::{ - BranchLearningAnalytics, LearningAggregate, LearningItemKey, LearningSide, LearningSnapshot, - LearningStore, LearningStoreData, Library, LocalDatePolicy, MoveLearningStatus, - PersistedLearningSnapshot, RepertoireId, RepertoireTree, ScheduledBuckets, SequenceHistograms, - SrsSettings, StatsScope, aggregate_scope, branch_learning_analytics, - log_global_total_invariant, scheduled_buckets, scoped_move_learning_analytics, - sequence_histograms, -}; - -use crate::i18n::{tr, trf}; -use crate::learning_branches::BranchSelection; -use crate::settings::Settings; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum LearningDashboardAction { - Close, - OpenSettings, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -enum ScopeSelection { - Global, - Repertoire(RepertoireId), -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -enum DashboardTab { - #[default] - Summary, - Branches, - History, - Scheduled, - Sequences, - Moves, -} - -struct SummaryRow { - id: Option, - name: String, - summary: LearningAggregate, -} - -struct DashboardView { - selection: ScopeSelection, - scope: StatsScope, - summary: LearningAggregate, - branches: Vec, - history: Vec, - scheduled: ScheduledBuckets, - sequences: SequenceHistograms, - moves: Vec, -} - -struct DashboardData { - as_of: i64, - timezone: LocalDatePolicy, - summary: Vec, - views: Vec, - names: HashMap, - labels: HashMap<(RepertoireId, Vec), Vec>, -} - -#[cfg(test)] -std::thread_local! { - static GLOBAL_TOTAL_INVARIANT_CALLS: std::cell::Cell = - const { std::cell::Cell::new(0) }; -} - -fn log_dashboard_global_total_invariant(global_total: usize, summary: &[SummaryRow]) { - log_global_total_invariant( - global_total, - summary - .iter() - .filter(|row| row.id.is_some()) - .map(|row| row.summary.total), - ); - #[cfg(test)] - GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.set(calls.get() + 1)); -} - -struct MoveRow { - key: LearningItemKey, - san: String, - status: MoveLearningStatus, - resistant: bool, - accuracy_percent: Option, - independent_attempts: u64, - correct_count: u64, - wrong_count: u64, - correct_streak: u32, - wrong_streak: u32, - next_review_at: Option, - review_in_seconds: Option, - overdue_seconds: Option, - uncertain_grace_seconds: Option, - response_time_median_ms: Option, - wrong_moves: Vec, - memberships: Vec, -} - -struct WrongMoveRow { - san: String, - count: u64, - last_at: i64, -} - -struct MembershipRow { - repertoire: String, - branch: Vec, -} - -enum Event { - Loaded(u64, Box>), - Snapshot(u64, Box>), -} - -pub struct LearningDashboardUi { - library: Library, - learning_store: LearningStore, - selection: ScopeSelection, - side: LearningSide, - tab: DashboardTab, - data: Option, - loading: bool, - error: Option, - snapshot_pending: bool, - snapshot_message: Option, - snapshot_error: Option, - automatic_snapshot_scope: Option, - selected_move: Option, - selected_branch: Option, - generation: u64, - tx: Sender, - rx: Receiver, -} - -impl LearningDashboardUi { - pub fn new(library: Library, learning_store: LearningStore) -> Self { - Self::with_selection( - library, - learning_store, - ScopeSelection::Global, - LearningSide::White, - ) - } - - pub fn new_for_repertoire( - library: Library, - learning_store: LearningStore, - repertoire: RepertoireId, - side: LearningSide, - ) -> Self { - let selection = if library.repertoire(&repertoire).is_some() { - ScopeSelection::Repertoire(repertoire) - } else { - ScopeSelection::Global - }; - Self::with_selection(library, learning_store, selection, side) - } - - fn with_selection( - library: Library, - learning_store: LearningStore, - selection: ScopeSelection, - side: LearningSide, - ) -> Self { - let (tx, rx) = mpsc::channel(); - let mut this = Self { - library, - learning_store, - selection, - side, - tab: match std::env::var("CP_LEARNING_DASHBOARD_TAB").as_deref() { - Ok("branches") => DashboardTab::Branches, - Ok("history") => DashboardTab::History, - Ok("scheduled") => DashboardTab::Scheduled, - Ok("sequences") => DashboardTab::Sequences, - Ok("moves") => DashboardTab::Moves, - _ => DashboardTab::Summary, - }, - data: None, - loading: false, - error: None, - snapshot_pending: false, - snapshot_message: None, - snapshot_error: None, - automatic_snapshot_scope: None, - selected_move: None, - selected_branch: None, - generation: 0, - tx, - rx, - }; - this.reload(); - this - } - - #[cfg(test)] - pub fn selected_repertoire(&self) -> Option<&RepertoireId> { - match &self.selection { - ScopeSelection::Global => None, - ScopeSelection::Repertoire(id) => Some(id), - } - } - - #[cfg(test)] - pub fn selected_side(&self) -> LearningSide { - self.side - } - - #[cfg(test)] - pub fn wait_until_idle_for_test(&mut self) { - while self.loading || self.snapshot_pending { - let event = self - .rx - .recv_timeout(Duration::from_secs(5)) - .expect("learning dashboard background work timed out"); - self.tx.send(event).unwrap(); - self.poll(); - } - } - - pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec { - crate::san::set(settings.move_notation); - self.poll(); - let mut actions = Vec::new(); - if !ui.ctx().egui_wants_keyboard_input() - && !crate::app::overlay_open(ui.ctx()) - && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)) - { - actions.push(LearningDashboardAction::Close); - } - if self.loading || self.snapshot_pending { - ui.ctx().request_repaint_after(Duration::from_millis(100)); - } - - 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); - } - }); - egui::CentralPanel::default().show(ui, |ui| { - ui.add_space(4.0); - self.scope_controls(ui); - - 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; - } - 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 - } - - fn reload(&mut self) { - self.load(false); - } - - fn refresh(&mut self) { - self.load(true); - } - - fn load(&mut self, preserve_data: bool) { - self.generation = self.generation.wrapping_add(1); - let generation = self.generation; - self.loading = true; - self.error = None; - if !preserve_data { - self.data = None; - } - let library = self.library.clone(); - let store = self.learning_store.clone(); - let side = self.side; - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("learning-dashboard", move || { - let result = store - .load() - .map_err(|error| error.to_string()) - .and_then(|data| { - let as_of = now(); - DashboardData::build(&library, &data, side, as_of, local_date_policy(as_of)) - }); - let _ = tx.send(Event::Loaded(generation, Box::new(result))); - }) { - self.loading = false; - self.error = Some(error.to_string()); - } - } - - fn poll(&mut self) { - while let Ok(event) = self.rx.try_recv() { - match event { - Event::Loaded(generation, result) if generation == self.generation => { - self.loading = false; - match *result { - Ok(data) => { - self.data = Some(data); - self.error = None; - self.ensure_snapshot_after_load(); - } - Err(error) => { - self.data = None; - self.error = Some(error); - } - } - } - Event::Snapshot(generation, result) if generation == self.generation => { - self.snapshot_pending = false; - match *result { - Ok(saved) => { - self.snapshot_error = None; - self.snapshot_message = Some(if saved.recorded { - trf( - "Snapshot captured: {date}", - &[("date", &saved.snapshot.date)], - ) - } else { - trf( - "Snapshot already exists for this date and scope: {date}", - &[("date", &saved.snapshot.date)], - ) - }); - if saved.recorded { - self.refresh(); - } - } - Err(error) => { - self.snapshot_message = None; - self.snapshot_error = Some(error); - } - } - } - _ => {} - } - } - } - - fn ensure_snapshot_after_load(&mut self) { - if self.snapshot_pending { - return; - } - let Some((scope, timezone)) = self.selected_capture() else { - return; - }; - if self - .automatic_snapshot_scope - .as_ref() - .is_some_and(|attempted| same_scope(attempted, &scope)) - { - return; - } - self.automatic_snapshot_scope = Some(scope.clone()); - self.capture_snapshot(scope, timezone); - } - - fn scope_controls(&mut self, ui: &mut Ui) { - let previous_side = self.side; - let previous_selection = self.selection.clone(); - let enabled = !self.loading && !self.snapshot_pending; - ui.add_enabled_ui(enabled, |ui| { - ui.horizontal_wrapped(|ui| { - 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"), - ); - for repertoire in &self.library.repertoires { - ui.selectable_value( - &mut self.selection, - ScopeSelection::Repertoire(repertoire.id.clone()), - &repertoire.name, - ); - } - }); - ui.label(RichText::new(tr("Side")).weak()); - egui::ComboBox::from_id_salt("learning_dashboard_side") - .selected_text(side_label(self.side)) - .show_ui(ui, |ui| { - ui.selectable_value(&mut self.side, LearningSide::White, tr("White")); - ui.selectable_value(&mut self.side, LearningSide::Black, tr("Black")); - }); - }); - }); - if previous_selection != self.selection { - self.selected_branch = None; - self.snapshot_message = None; - self.snapshot_error = None; - } - if previous_side != self.side { - self.selected_move = None; - self.selected_branch = None; - self.snapshot_message = None; - self.snapshot_error = None; - self.reload(); - } else if previous_selection != self.selection { - self.ensure_snapshot_after_load(); - } - } - - fn selected_capture(&self) -> Option<(StatsScope, LocalDatePolicy)> { - let data = self.data.as_ref()?; - let view = data - .views - .iter() - .find(|view| view.selection == self.selection)?; - Some((view.scope.clone(), data.timezone)) - } - - fn capture_line(&mut self, ui: &mut Ui) { - 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); - } - }); - } - } - - fn capture_snapshot(&mut self, scope: StatsScope, timezone: LocalDatePolicy) { - self.snapshot_pending = true; - self.snapshot_message = None; - self.snapshot_error = None; - let generation = self.generation; - let library = self.library.clone(); - let store = self.learning_store.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("learning-dashboard-snapshot", move || { - let result = capture_snapshot(&store, &library, &scope, timezone); - let _ = tx.send(Event::Snapshot(generation, Box::new(result))); - }) { - self.snapshot_pending = false; - self.snapshot_error = Some(error.to_string()); - } - } - - fn tabs(&mut self, ui: &mut Ui) { - ui.horizontal_wrapped(|ui| { - for (tab, label) in [ - (DashboardTab::Summary, tr("Overview")), - (DashboardTab::History, tr("Progress over time")), - (DashboardTab::Scheduled, tr("Scheduled")), - (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").to_owned(), - ScopeSelection::Repertoire(id) => self - .library - .repertoire(id) - .map(|repertoire| repertoire.name.clone()) - .unwrap_or_else(|| tr("The selected scope is no longer available").to_owned()), - } - } -} - -impl DashboardData { - fn build( - library: &Library, - data: &LearningStoreData, - side: LearningSide, - as_of: i64, - timezone: LocalDatePolicy, - ) -> Result { - let ids = library - .repertoires - .iter() - .map(|repertoire| repertoire.id.clone()) - .collect::>(); - let labels = membership_labels(library); - let names = library - .repertoires - .iter() - .map(|repertoire| (repertoire.id.clone(), repertoire.name.clone())) - .collect(); - let global_scope = StatsScope::new(ids, side, as_of); - let global = DashboardView::build( - library, - data, - ScopeSelection::Global, - global_scope, - timezone, - &labels, - )?; - let global_summary = global.summary.clone(); - let mut views = vec![global]; - let mut summary = Vec::with_capacity(library.repertoires.len() + 1); - for repertoire in &library.repertoires { - let scope = StatsScope::for_repertoire(repertoire.id.clone(), side, as_of); - let view = DashboardView::build( - library, - data, - ScopeSelection::Repertoire(repertoire.id.clone()), - scope, - timezone, - &labels, - )?; - summary.push(SummaryRow { - id: Some(repertoire.id.clone()), - name: repertoire.name.clone(), - summary: view.summary.clone(), - }); - views.push(view); - } - let global_total = global_summary.total; - summary.push(SummaryRow { - id: None, - name: String::new(), - summary: global_summary, - }); - log_dashboard_global_total_invariant(global_total, &summary); - Ok(Self { - as_of, - timezone, - summary, - views, - names, - labels, - }) - } -} - -impl DashboardView { - fn build( - library: &Library, - data: &LearningStoreData, - selection: ScopeSelection, - scope: StatsScope, - timezone: LocalDatePolicy, - labels: &HashMap<(RepertoireId, Vec), Vec>, - ) -> Result { - let settings = SrsSettings::default(); - let scoped = aggregate_scope(library, &data.learning, &scope, &settings) - .map_err(|error| error.to_string())?; - let scheduled = scheduled_buckets(scoped.items.iter(), scope.as_of, timezone); - let sequences = sequence_histograms(scoped.items.iter()); - let branches = branch_learning_analytics(library, &data.learning, &scope, &settings) - .map_err(|error| error.to_string())?; - let analytics = scoped_move_learning_analytics(library, &data.learning, &scope, &settings) - .map_err(|error| error.to_string())?; - let names = library - .repertoires - .iter() - .map(|repertoire| (repertoire.id.clone(), repertoire.name.clone())) - .collect::>(); - let moves = analytics - .into_iter() - .map(|analytics| { - let mut wrong_moves = analytics - .wrong_move_histogram - .iter() - .map(|(uci, stats)| WrongMoveRow { - san: san_from_fen4(&analytics.key.position_fen4, uci) - .unwrap_or_else(|| "—".to_owned()), - count: stats.count, - last_at: stats.last_at, - }) - .collect::>(); - wrong_moves.sort_by(|left, right| { - right - .count - .cmp(&left.count) - .then_with(|| right.last_at.cmp(&left.last_at)) - .then_with(|| left.san.cmp(&right.san)) - }); - let memberships = analytics - .memberships - .iter() - .map(|membership| MembershipRow { - repertoire: names - .get(&membership.repertoire_id) - .cloned() - .unwrap_or_else(|| "—".to_owned()), - branch: labels - .get(&(membership.repertoire_id.clone(), membership.path.clone())) - .cloned() - .unwrap_or_default(), - }) - .collect(); - MoveRow { - san: san_from_fen4(&analytics.key.position_fen4, &analytics.key.expected_uci) - .unwrap_or_else(|| "—".to_owned()), - key: analytics.key, - status: analytics.status, - resistant: analytics.resistant, - accuracy_percent: analytics.accuracy_percent, - independent_attempts: analytics.independent_attempts, - correct_count: analytics.correct_count, - wrong_count: analytics.wrong_count, - correct_streak: analytics.correct_streak, - wrong_streak: analytics.wrong_streak, - next_review_at: analytics.next_review_at, - review_in_seconds: analytics.review_in_seconds, - overdue_seconds: analytics.overdue_seconds, - uncertain_grace_seconds: analytics.uncertain_grace_seconds, - response_time_median_ms: analytics.response_time_median_ms, - wrong_moves, - memberships, - } - }) - .collect(); - let history = data - .snapshots - .iter() - .filter(|snapshot| same_scope(&snapshot.scope, &scope)) - .cloned() - .collect(); - Ok(Self { - selection, - scope, - summary: scoped.summary, - branches, - history, - scheduled, - sequences, - moves, - }) - } -} - -fn capture_snapshot( - store: &LearningStore, - library: &Library, - scope: &StatsScope, - timezone: LocalDatePolicy, -) -> Result { - store - .record_snapshot(library, scope, &SrsSettings::default(), timezone) - .map_err(|error| error.to_string()) -} - -fn same_scope(left: &StatsScope, right: &StatsScope) -> bool { - let mut left = left.clone(); - let mut right = right.clone(); - left.as_of = 0; - right.as_of = 0; - left == right -} - -fn membership_labels(library: &Library) -> HashMap<(RepertoireId, Vec), Vec> { - let mut result = HashMap::new(); - for repertoire in &library.repertoires { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let game = tree.game(); - for node in game.attached_nodes() { - let Some(path) = tree.path(node) else { - continue; - }; - let labels = game - .path(node) - .into_iter() - .skip(1) - .filter_map(|id| game.move_label(id)) - .collect::>(); - result.insert((repertoire.id.clone(), path.to_vec()), labels); - } - } - result -} - -fn san_from_fen4(position_fen4: &str, uci: &str) -> Option { - let fen = format!("{position_fen4} 0 1").parse::().ok()?; - let position = fen.into_position::(CastlingMode::Standard).ok()?; - let mv = uci.parse::().ok()?.to_move(&position).ok()?; - Some(San::from_move(&position, mv).to_string()) -} - -fn loading_body(ui: &mut Ui) { - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), 160.0), - Layout::top_down(Align::Min), - |ui| { - ui.add_space(24.0); - ui.horizontal(|ui| { - ui.spinner(); - ui.label(tr("Loading learning statistics…")); - }); - }, - ); -} - -fn error_body(ui: &mut Ui, error: &str) { - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), 120.0), - Layout::top_down(Align::Min), - |ui| { - ui.add_space(12.0); - ui.colored_label(ui.visuals().error_fg_color, error); - }, - ); -} - -fn show_summary(ui: &mut Ui, data: &DashboardData, view: &DashboardView) { - 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(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(32.0, data.summary.len(), |mut row| { - let item = &data.summary[row.index()]; - let global = item.id.is_none(); - row.col(|ui| { - 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.")); - }); - 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); }); - } - }); - }); -} - -fn show_history(ui: &mut Ui, view: &DashboardView) { - if view.history.is_empty() { - ui.label(tr( - "Progress history will appear after your first daily snapshot.", - )); - return; - } - crate::learning_charts::history(ui, &view.history); - ui.add_space(8.0); - 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) - .max_scroll_height(360.0) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(90.0).clip(true)); - for _ in 1..headers.len() { - table = table.column(Column::exact(number_width)); - } - table - .header(40.0, |mut header| { - for (index, key) in headers.into_iter().enumerate() { - header.col(|ui| { - header_cell(ui, tr(key), index > 0); - }); - } - }) - .body(|body| { - body.rows(24.0, view.history.len(), |mut row| { - let snapshot = &view.history[row.index()]; - row.col(|ui| { - text_cell(ui, &snapshot.date, false, false).on_hover_text(format!( - "{}: {}", - tr("Calculated at"), - format_time(Some(snapshot.as_of)) - )); - }); - let values = [snapshot.learnt, snapshot.unseen, snapshot.due]; - for value in values { - row.col(|ui| { - text_cell(ui, &value.to_string(), false, true); - }); - } - }); - }); -} - -fn show_scheduled(ui: &mut Ui, view: &DashboardView) { - let buckets = view.scheduled; - crate::learning_charts::scheduled(ui, buckets); - ui.add_space(8.0); - let rows = [ - (tr("Overdue").to_owned(), buckets.overdue), - (tr("Today").to_owned(), buckets.today), - (tr("Next 7 days").to_owned(), buckets.week), - (tr("Next 30 days").to_owned(), buckets.month), - (tr("Next 365 days").to_owned(), buckets.year), - (tr("Later").to_owned(), buckets.later), - ]; - distribution_table( - ui, - "learning_dashboard_scheduled", - "Scheduled", - "Scheduled", - &rows, - buckets.introduced(), - ) - .on_hover_text(tr( - "Today ends at local midnight; the other buckets use fixed 7, 30 and 365-day ranges.", - )); - ui.label(format!("{}: {}", tr("Introduced"), buckets.introduced())); -} - -fn show_sequences(ui: &mut Ui, view: &DashboardView) { - if view.moves.is_empty() { - ui.label(tr("No moves in this scope")); - return; - } - crate::learning_charts::sequences(ui, &view.sequences); - let correct = histogram_rows(&view.sequences.correct_streak); - let wrong = histogram_rows(&view.sequences.wrong_streak); - let attempts = histogram_rows(&view.sequences.attempts); - let total = view.moves.len(); - if ui.available_width() >= 900.0 { - ui.columns(3, |columns| { - distribution_table( - &mut columns[0], - "learning_dashboard_correct_sequences", - "Correct streak", - "Length / attempts", - &correct, - total, - ); - distribution_table( - &mut columns[1], - "learning_dashboard_wrong_sequences", - "Wrong streak", - "Length / attempts", - &wrong, - total, - ); - distribution_table( - &mut columns[2], - "learning_dashboard_attempt_sequences", - "Attempts", - "Length / attempts", - &attempts, - total, - ); - }); - } else { - distribution_table( - ui, - "learning_dashboard_correct_sequences", - "Correct streak", - "Length / attempts", - &correct, - total, - ); - distribution_table( - ui, - "learning_dashboard_wrong_sequences", - "Wrong streak", - "Length / attempts", - &wrong, - total, - ); - distribution_table( - ui, - "learning_dashboard_attempt_sequences", - "Attempts", - "Length / attempts", - &attempts, - total, - ); - } -} - -fn histogram_rows( - histogram: &std::collections::BTreeMap, -) -> Vec<(String, usize)> { - histogram - .iter() - .map(|(value, count)| (value.to_string(), *count)) - .collect() -} - -fn distribution_table( - ui: &mut Ui, - id: &'static str, - title: &'static str, - first_header: &'static str, - rows: &[(String, usize)], - total: usize, -) -> egui::Response { - let response = ui.strong(tr(title)); - TableBuilder::new(ui) - .id_salt(id) - .striped(true) - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(100.0).clip(true)) - .column(Column::exact(70.0)) - .header(28.0, |mut header| { - header.col(|ui| { - header_cell(ui, tr(first_header), false); - }); - header.col(|ui| { - header_cell(ui, tr("Items"), true); - }); - }) - .body(|body| { - body.rows(24.0, rows.len() + 1, |mut row| { - if row.index() == rows.len() { - row.col(|ui| { - text_cell(ui, tr("Total"), true, false); - }); - row.col(|ui| { - text_cell(ui, &total.to_string(), true, true); - }); - return; - } - let (value, count) = &rows[row.index()]; - row.col(|ui| { - text_cell(ui, value, false, false); - }); - row.col(|ui| { - text_cell(ui, &count.to_string(), false, true); - }); - }); - }); - ui.add_space(10.0); - response -} - -fn show_moves(ui: &mut Ui, view: &DashboardView, selected: &mut Option) { - if view.moves.is_empty() { - ui.label(tr("No moves in this scope")); - *selected = None; - return; - } - if selected - .as_ref() - .is_none_or(|key| !view.moves.iter().any(|row| &row.key == key)) - { - *selected = Some(view.moves[0].key.clone()); - } - let mut clicked = None; - let compact = ui.available_width() < 700.0; - TableBuilder::new(ui) - .id_salt("learning_dashboard_moves") - .striped(true) - .sense(egui::Sense::click()) - .max_scroll_height(if compact { 180.0 } else { 300.0 }) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(72.0).clip(true)) - .column(Column::exact(if compact { 68.0 } else { 100.0 })) - .column(Column::exact(if compact { 58.0 } else { 76.0 })) - .column(Column::exact(if compact { 58.0 } else { 76.0 })) - .column(Column::exact(if compact { 108.0 } else { 142.0 })) - .header(30.0, |mut header| { - for (index, key) in ["Move", "Status", "Accuracy", "Streak", "Next review"] - .into_iter() - .enumerate() - { - header.col(|ui| { - header_cell(ui, tr(key), index > 0).on_hover_text(if key == "Streak" { - format!("{} / {}", tr("Correct streak"), tr("Wrong streak")) - } else { - tr(key).to_owned() - }); - }); - } - }) - .body(|body| { - body.rows(24.0, view.moves.len(), |mut row| { - let move_row = &view.moves[row.index()]; - row.set_selected(selected.as_ref() == Some(&move_row.key)); - row.col(|ui| { - text_cell(ui, &crate::san::show(&move_row.san), false, false); - }); - row.col(|ui| { - text_cell( - ui, - &move_status_label(move_row.status, move_row.resistant), - false, - false, - ); - }); - row.col(|ui| { - text_cell(ui, &format_percent(move_row.accuracy_percent), false, true); - }); - row.col(|ui| { - text_cell( - ui, - &format!("{} / {}", move_row.correct_streak, move_row.wrong_streak), - false, - true, - ) - .on_hover_text(format!( - "{} / {}", - tr("Correct streak"), - tr("Wrong streak") - )); - }); - row.col(|ui| { - text_cell(ui, &format_time(move_row.next_review_at), false, true); - }); - if row.response().clicked() { - clicked = Some(move_row.key.clone()); - } - }); - }); - if let Some(key) = clicked { - *selected = Some(key); - } - let Some(selected) = selected.as_ref() else { - return; - }; - let Some(move_row) = view.moves.iter().find(|row| &row.key == selected) else { - return; - }; - ui.separator(); - show_move_details(ui, move_row); -} - -fn show_move_details(ui: &mut Ui, move_row: &MoveRow) { - ui.strong(crate::san::show(&move_row.san)); - let narrow = ui.available_width() < 700.0; - let details = [ - ( - "Status", - move_status_label(move_row.status, move_row.resistant), - "The current learning status of this move.", - ), - ( - "Accuracy", - format_percent(move_row.accuracy_percent), - "Independent correct answers divided by all independent attempts.", - ), - ( - "Attempts", - format!( - "{} · {} {} · {} {}", - move_row.independent_attempts, - move_row.correct_count, - tr("Correct"), - move_row.wrong_count, - tr("Wrong") - ), - "Only independent attempts count; previews, automatic context and replays are excluded.", - ), - ( - "Correct streak", - move_row.correct_streak.to_string(), - "Consecutive independent correct answers.", - ), - ( - "Wrong streak", - move_row.wrong_streak.to_string(), - "Consecutive independent wrong answers.", - ), - ( - "Next review", - format_time(move_row.next_review_at), - "The scheduled review time, or a dash for an unseen move.", - ), - ( - "Review in", - format_duration(move_row.review_in_seconds), - "Time remaining until the scheduled review.", - ), - ( - "Overdue by", - format_duration(move_row.overdue_seconds), - "Elapsed time since the scheduled review.", - ), - ( - "Median response", - format_median(move_row.response_time_median_ms), - "Median response time over independent attempts.", - ), - ( - "Uncertain grace", - format_duration(move_row.uncertain_grace_seconds), - "The overdue grace period before a learnt move becomes uncertain.", - ), - ]; - egui::Grid::new("learning_dashboard_move_details") - .num_columns(if narrow { 2 } else { 4 }) - .spacing([12.0, 5.0]) - .show(ui, |ui| { - for (index, (label, value, tooltip)) in details.into_iter().enumerate() { - ui.label(RichText::new(tr(label)).weak()) - .on_hover_text(tr(tooltip)); - ui.label(value).on_hover_text(tr(tooltip)); - if narrow || index % 2 == 1 { - ui.end_row(); - } - } - }); - ui.add_space(8.0); - ui.strong(tr("Wrong answers")); - if move_row.wrong_moves.is_empty() { - ui.label(tr("No wrong answers")); - } else { - TableBuilder::new(ui) - .id_salt("learning_dashboard_wrong_moves") - .striped(true) - .vscroll(false) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::remainder().at_least(90.0).clip(true)) - .column(Column::exact(70.0)) - .column(Column::exact(150.0)) - .header(28.0, |mut header| { - header.col(|ui| { - header_cell(ui, tr("Move"), false); - }); - header.col(|ui| { - header_cell(ui, tr("Count"), true); - }); - header.col(|ui| { - header_cell(ui, tr("Last at"), true); - }); - }) - .body(|body| { - body.rows(24.0, move_row.wrong_moves.len(), |mut row| { - let wrong = &move_row.wrong_moves[row.index()]; - row.col(|ui| { - text_cell(ui, &crate::san::show(&wrong.san), false, false); - }); - row.col(|ui| { - text_cell(ui, &wrong.count.to_string(), false, true); - }); - row.col(|ui| { - text_cell(ui, &format_time(Some(wrong.last_at)), false, true); - }); - }); - }); - } - ui.add_space(8.0); - ui.strong(tr("Found in")); - for membership in &move_row.memberships { - let branch = membership - .branch - .iter() - .map(|label| crate::san::show(label)) - .collect::>() - .join(" "); - let text = if branch.is_empty() { - membership.repertoire.clone() - } else { - format!("{} · {branch}", membership.repertoire) - }; - ui.add(egui::Label::new(&text).truncate()) - .on_hover_text(tr( - "Repertoires and branches that contain this learning item.", - )) - .on_hover_text(text); - } -} - -fn move_status_label(status: MoveLearningStatus, resistant: bool) -> String { - let status = match status { - MoveLearningStatus::Unseen => tr("Unseen"), - MoveLearningStatus::Learning => tr("Learning"), - MoveLearningStatus::LearntFresh => tr("Learnt fresh"), - MoveLearningStatus::Uncertain => tr("Uncertain"), - }; - if resistant { - format!("{status} · {}", tr("Resistant")) - } else { - status.to_owned() - } -} - -fn header_cell(ui: &mut Ui, text: &str, numeric: bool) -> egui::Response { - if numeric { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(egui::Label::new(RichText::new(text).strong()).truncate()) - }) - .inner - } else { - ui.add(egui::Label::new(RichText::new(text).strong()).truncate()) - } -} - -fn text_cell(ui: &mut Ui, text: &str, strong: bool, numeric: bool) -> egui::Response { - let text = if strong { - RichText::new(text).strong() - } else { - RichText::new(text) - }; - if numeric { - let size = egui::vec2(ui.available_width(), ui.available_height()); - ui.allocate_ui_with_layout(size, Layout::right_to_left(Align::Center), |ui| { - ui.add(egui::Label::new(text).truncate()) - }) - .inner - } else { - ui.add(egui::Label::new(text).truncate()) - } -} - -fn side_label(side: LearningSide) -> &'static str { - tr(match side { - LearningSide::White => "White", - LearningSide::Black => "Black", - }) -} - -fn format_percent(value: Option) -> String { - value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")) -} - -fn format_median(value: Option) -> String { - value.map_or_else(|| "—".to_owned(), |value| format!("{value:.0} ms")) -} - -fn format_duration(value: Option) -> String { - let Some(seconds) = value else { - return "—".to_owned(); - }; - let seconds = seconds.max(0); - let days = seconds / 86_400; - let hours = seconds % 86_400 / 3_600; - let minutes = seconds % 3_600 / 60; - let seconds = seconds % 60; - if days > 0 { - format!("{days} d {hours} h") - } else if hours > 0 { - format!("{hours} h {minutes} min") - } else if minutes > 0 { - format!("{minutes} min {seconds} s") - } else { - format!("{seconds} s") - } -} - -fn format_time(at: Option) -> String { - at.and_then(|at| chrono::DateTime::from_timestamp(at, 0)) - .map(|at| { - at.with_timezone(&chrono::Local) - .format("%Y-%m-%d %H:%M") - .to_string() - }) - .unwrap_or_else(|| "—".to_owned()) -} - -fn local_date_policy(as_of: i64) -> LocalDatePolicy { - let offset = chrono::DateTime::from_timestamp(as_of, 0) - .map(|date| { - date.with_timezone(&chrono::Local) - .offset() - .local_minus_utc() - }) - .unwrap_or(0); - LocalDatePolicy::fixed(offset) -} - -fn now() -> i64 { - web_time::SystemTime::now() - .duration_since(web_time::UNIX_EPOCH) - .map_or(0, |duration| duration.as_secs() as i64) -} - -#[cfg(test)] -mod tests { - use std::collections::BTreeMap; - use std::path::PathBuf; - use std::sync::atomic::{AtomicU64, Ordering}; - - use trainer::repertoire::{LearningData, LearningItem, WrongMoveStats, active_learning_keys}; - - use super::*; - - const BASE: i64 = 1_800_000_000; - const DAY: i64 = 86_400; - static NEXT_DIR: AtomicU64 = AtomicU64::new(1); - - struct TestDir(PathBuf); - - impl TestDir { - fn new(name: &str) -> Self { - let sequence = NEXT_DIR.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "cp-learning-dashboard-{}-{sequence}-{name}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn store(&self) -> LearningStore { - LearningStore::new(self.0.join("learning.json")) - } - } - - impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { - let game = chess_core::parse_str(pgn).game; - library.create(name, &game).unwrap() - } - - fn key(library: &Library, id: &RepertoireId, expected: &str) -> LearningItemKey { - active_learning_keys( - library, - &StatsScope::for_repertoire(id.clone(), LearningSide::White, BASE), - ) - .unwrap() - .into_iter() - .find(|key| key.expected_uci == expected) - .unwrap() - } - - fn introduced(key: LearningItemKey, streak: u32, next: i64) -> LearningItem { - let mut item = LearningItem::new(key); - item.introduced = true; - item.correct_streak = streak; - item.correct_count = u64::from(streak); - item.next_review_at = Some(next); - item.previous_interval_seconds = Some(DAY); - item - } - - fn build(library: &Library, data: &LearningStoreData) -> Result { - DashboardData::build( - library, - data, - LearningSide::White, - BASE, - LocalDatePolicy::UTC, - ) - } - - fn loaded_dashboard( - library: Library, - learning_store: LearningStore, - selection: ScopeSelection, - data: DashboardData, - ) -> LearningDashboardUi { - let automatic_snapshot_scope = data - .views - .iter() - .find(|view| view.selection == selection) - .map(|view| view.scope.clone()); - let (tx, rx) = mpsc::channel(); - LearningDashboardUi { - library, - learning_store, - selection, - side: data.views[0].scope.side, - tab: DashboardTab::Summary, - data: Some(data), - loading: false, - error: None, - snapshot_pending: false, - snapshot_message: None, - snapshot_error: None, - automatic_snapshot_scope, - selected_move: None, - selected_branch: None, - generation: 0, - tx, - rx, - } - } - - fn render_dashboard( - dashboard: &mut LearningDashboardUi, - ctx: &egui::Context, - settings: &Settings, - width: f32, - height: f32, - ) -> (egui::Rect, egui::FullOutput) { - let mut content = None; - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - ..Default::default() - }, - |ui| { - let available = ui.available_rect_before_wrap(); - assert!(dashboard.show(ui, settings).is_empty()); - let rect = ui.min_rect(); - assert!(rect.min.x >= available.min.x, "{rect:?} {available:?}"); - assert!(rect.min.y >= available.min.y, "{rect:?} {available:?}"); - assert!( - rect.max.x <= available.max.x + 0.1, - "{rect:?} {available:?}" - ); - assert!( - rect.max.y <= available.max.y + 0.1, - "{rect:?} {available:?}" - ); - content = Some(rect); - }, - ); - (content.unwrap(), output) - } - - fn assert_narrow_summary(shapes: &[egui::epaint::ClippedShape]) { - let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0)); - for expected in [ - "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", - "Global total", - ] { - assert!(!shapes.iter().any(|clipped| matches!(&clipped.shape, egui::Shape::Text(text) if text.galley.text() == excluded)), "unexpected technical or unrelated text {excluded}"); - } - for clipped in shapes { - if let egui::Shape::Text(text) = &clipped.shape { - let rect = egui::Rect::from_min_size(text.pos, text.galley.size()); - assert!( - rect.min.x >= screen.min.x - && rect.min.y >= screen.min.y - && rect.max.x <= screen.max.x + 0.1 - && rect.max.y <= screen.max.y + 0.1, - "text outside 640x480: {rect:?} {}", - text.galley.text() - ); - } - } - } - - #[test] - fn mixed_summary_and_global_union_are_deduplicated() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let second = add_repertoire(&mut library, "Vienna", "1. e4 e5 2. Nc3 Nf6 *"); - let shared = key(&library, &first, "e2e4"); - assert_eq!(shared, key(&library, &second, "e2e4")); - let mut learning = LearningData::default(); - let mut shared_item = introduced(shared, 3, BASE - 10 * DAY); - shared_item.wrong_move_histogram = BTreeMap::from([( - "d2d4".to_owned(), - WrongMoveStats { - count: 2, - last_at: BASE - DAY, - }, - )]); - shared_item.independent_response_times_ms = vec![100, 300, 200]; - learning.items.push(shared_item); - learning - .items - .push(introduced(key(&library, &first, "g1f3"), 1, BASE + DAY)); - learning - .items - .push(LearningItem::new(key(&library, &second, "b1c3"))); - let data = LearningStoreData { - learning, - ..LearningStoreData::default() - }; - let dashboard = build(&library, &data).unwrap(); - let first_summary = &dashboard.summary[0].summary; - let second_summary = &dashboard.summary[1].summary; - let global = &dashboard.summary[2].summary; - assert_eq!((first_summary.total, first_summary.unseen), (2, 0)); - assert_eq!((first_summary.learning, first_summary.learnt), (1, 1)); - assert_eq!((first_summary.uncertain, first_summary.due), (1, 1)); - assert_eq!((second_summary.total, second_summary.unseen), (2, 1)); - assert_eq!((global.total, global.unseen), (3, 1)); - assert_eq!((global.learning, global.learnt), (1, 1)); - assert_eq!( - global.total, - global.unseen + global.learning + global.learnt - ); - assert!(global.uncertain <= global.learnt); - assert!(global.total <= first_summary.total + second_summary.total); - assert!(global.total < first_summary.total + second_summary.total); - - let global_view = &dashboard.views[0]; - assert_eq!(global_view.moves.len(), 3); - assert!(global_view.moves.iter().all(|row| row.san != "—")); - assert!(global_view.moves.iter().any(|row| row.san == "e4")); - assert!(global_view.sequences.attempts.contains_key(&0)); - for total in [ - global_view.sequences.correct_streak.values().sum::(), - global_view.sequences.wrong_streak.values().sum::(), - global_view.sequences.attempts.values().sum::(), - ] { - assert_eq!(total, global.total); - } - let e4 = global_view - .moves - .iter() - .find(|row| row.san == "e4") - .unwrap(); - assert_eq!(e4.wrong_moves[0].san, "d4"); - assert_eq!(e4.response_time_median_ms, Some(200.0)); - assert_eq!(e4.memberships.len(), 2); - assert!( - e4.memberships - .iter() - .all(|membership| membership.branch.iter().any(|label| label.contains("e4"))) - ); - } - - #[test] - fn global_total_invariant_runs_on_empty_build_without_changing_data() { - GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.set(0)); - - let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap(); - - assert_eq!(GLOBAL_TOTAL_INVARIANT_CALLS.with(|calls| calls.get()), 1); - 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); - assert!(dashboard.summary[0].id.is_none()); - assert_eq!(dashboard.summary[0].summary, LearningAggregate::default()); - assert_eq!(dashboard.views.len(), 1); - assert_eq!(dashboard.views[0].summary, LearningAggregate::default()); - assert!(dashboard.names.is_empty()); - assert!(dashboard.labels.is_empty()); - } - - #[test] - fn empty_scope_has_no_false_percentages_or_buckets() { - let dashboard = build(&Library::default(), &LearningStoreData::default()).unwrap(); - assert_eq!(dashboard.summary.len(), 1); - let global = &dashboard.summary[0].summary; - assert_eq!(global.total, 0); - assert_eq!(global.learnt_percent, None); - assert_eq!(global.confident_percent, None); - assert_eq!(format_percent(global.learnt_percent), "—"); - let view = &dashboard.views[0]; - assert!(view.moves.is_empty()); - assert!(view.history.is_empty()); - assert_eq!(view.scheduled.introduced(), 0); - assert!(view.sequences.correct_streak.is_empty()); - assert!(view.sequences.wrong_streak.is_empty()); - assert!(view.sequences.attempts.is_empty()); - } - - #[test] - fn scheduled_buckets_partition_introduced_items() { - let mut library = Library::default(); - let id = add_repertoire( - &mut library, - "Spanish", - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 *", - ); - let schedules = [ - ("e2e4", Some(BASE - 1)), - ("g1f3", Some(BASE + 60)), - ("f1b5", Some(BASE + 2 * DAY)), - ("b5a4", Some(BASE + 10 * DAY)), - ("e1g1", Some(BASE + 60 * DAY)), - ("f1e1", Some(BASE + 400 * DAY)), - ]; - let mut learning = LearningData::default(); - for (expected, next) in schedules { - let mut item = LearningItem::new(key(&library, &id, expected)); - item.introduced = true; - item.next_review_at = next; - learning.items.push(item); - } - learning - .items - .push(LearningItem::new(key(&library, &id, "a4b3"))); - let dashboard = build( - &library, - &LearningStoreData { - learning, - ..LearningStoreData::default() - }, - ) - .unwrap(); - let view = &dashboard.views[1]; - assert_eq!(view.summary.total, 7); - assert_eq!(view.summary.unseen, 1); - assert_eq!( - view.scheduled, - ScheduledBuckets { - overdue: 1, - today: 1, - week: 1, - month: 1, - year: 1, - later: 1, - } - ); - assert_eq!( - view.scheduled.introduced(), - view.summary.total - view.summary.unseen - ); - } - - #[test] - fn snapshot_capture_deduplicates_same_date_and_scope() { - let dir = TestDir::new("duplicate"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 *"); - let scope = StatsScope::for_repertoire(id, LearningSide::White, BASE); - let first = capture_snapshot(&store, &library, &scope, LocalDatePolicy::UTC).unwrap(); - assert!(first.recorded); - let mut repeated_scope = scope.clone(); - repeated_scope.as_of += 60; - let second = - capture_snapshot(&store, &library, &repeated_scope, LocalDatePolicy::UTC).unwrap(); - assert!(!second.recorded); - assert_eq!(first.snapshot.date, second.snapshot.date); - assert_eq!(store.load().unwrap().snapshots.len(), 1); - } - - #[test] - fn history_preserves_old_snapshots_after_new_capture() { - let dir = TestDir::new("history"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 *"); - let scope = StatsScope::for_repertoire(id, LearningSide::White, BASE); - let old = capture_snapshot(&store, &library, &scope, LocalDatePolicy::UTC).unwrap(); - let mut next_scope = scope.clone(); - next_scope.as_of += DAY; - let new = capture_snapshot(&store, &library, &next_scope, LocalDatePolicy::UTC).unwrap(); - assert!(new.recorded); - let stored = store.load().unwrap(); - assert_eq!(stored.snapshots.len(), 2); - let dashboard = build(&library, &stored).unwrap(); - let history = &dashboard.views[1].history; - assert_eq!(history.len(), 2); - assert_eq!(history[0].date, old.snapshot.date); - assert_eq!(history[0].as_of, old.snapshot.as_of); - assert_eq!(history[1].date, new.snapshot.date); - assert!(history[0].as_of < history[1].as_of); - } - - #[test] - fn automatic_snapshot_runs_once_per_scope_and_reopening_does_not_write() { - let dir = TestDir::new("automatic"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 *"); - add_repertoire(&mut library, "Queen's pawn", "1. d4 d5 *"); - let mut dashboard = LearningDashboardUi::new_for_repertoire( - library.clone(), - store.clone(), - id.clone(), - LearningSide::Black, - ); - dashboard.wait_until_idle_for_test(); - - let stored = store.load().unwrap(); - assert_eq!(stored.snapshots.len(), 1); - assert_eq!(stored.snapshots[0].scope.side, LearningSide::Black); - assert_eq!(stored.snapshots[0].scope.repertoire_ids.len(), 1); - assert!(stored.snapshots[0].scope.repertoire_ids.contains(&id)); - let before_reopen = std::fs::read(store.path()).unwrap(); - let mut reopened = LearningDashboardUi::new_for_repertoire( - library, - store.clone(), - id.clone(), - LearningSide::Black, - ); - reopened.wait_until_idle_for_test(); - assert_eq!(std::fs::read(store.path()).unwrap(), before_reopen); - - reopened.selection = ScopeSelection::Global; - reopened.ensure_snapshot_after_load(); - reopened.wait_until_idle_for_test(); - let stored = store.load().unwrap(); - assert_eq!(stored.snapshots.len(), 2); - assert!( - stored - .snapshots - .iter() - .any(|snapshot| snapshot.scope.repertoire_ids.len() == 2) - ); - let before_existing = std::fs::read(store.path()).unwrap(); - reopened.selection = ScopeSelection::Repertoire(id); - reopened.ensure_snapshot_after_load(); - reopened.wait_until_idle_for_test(); - assert_eq!(std::fs::read(store.path()).unwrap(), before_existing); - } - - #[test] - fn snapshot_refresh_preserves_the_visible_summary_and_its_height() { - let dir = TestDir::new("refresh"); - let store = dir.store(); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let data = build(&library, &LearningStoreData::default()).unwrap(); - let scope = data.views[1].scope.clone(); - let mut dashboard = loaded_dashboard( - library.clone(), - store.clone(), - ScopeSelection::Repertoire(id), - data, - ); - let settings = Settings::default(); - let ctx = egui::Context::default(); - let (before, output) = render_dashboard(&mut dashboard, &ctx, &settings, 1000.0, 700.0); - output.drop_without_applying_deltas(); - let saved = capture_snapshot(&store, &library, &scope, LocalDatePolicy::UTC).unwrap(); - assert!(saved.recorded); - - dashboard - .tx - .send(Event::Snapshot(dashboard.generation, Box::new(Ok(saved)))) - .unwrap(); - dashboard.poll(); - assert!(dashboard.loading); - assert!(dashboard.data.is_some()); - let (after, output) = render_dashboard(&mut dashboard, &ctx, &settings, 1000.0, 700.0); - - assert_eq!(after, before); - assert!(output.shapes.iter().any(|clipped| { - 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…") - })); - output.drop_without_applying_deltas(); - dashboard.wait_until_idle_for_test(); - assert_eq!(store.load().unwrap().snapshots.len(), 1); - } - - #[test] - fn every_tab_renders_at_both_window_sizes() { - let dir = TestDir::new("layout"); - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let mut learning = LearningData::default(); - let mut item = introduced(key(&library, &id, "e2e4"), 3, BASE + DAY); - item.wrong_move_histogram = BTreeMap::from([( - "d2d4".to_owned(), - WrongMoveStats { - count: 1, - last_at: BASE - DAY, - }, - )]); - learning.items.push(item); - let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, BASE); - let snapshot = LearningSnapshot::capture( - &library, - &learning, - &scope, - &SrsSettings::default(), - LocalDatePolicy::UTC, - ) - .unwrap(); - let stored = LearningStoreData { - learning, - snapshots: vec![snapshot], - ..LearningStoreData::default() - }; - let data = build(&library, &stored).unwrap(); - let mut dashboard = - loaded_dashboard(library, dir.store(), ScopeSelection::Repertoire(id), data); - let settings = Settings::default(); - let ctx = egui::Context::default(); - for (width, height) in [(1400.0, 900.0), (960.0, 600.0), (640.0, 480.0)] { - for tab in [ - DashboardTab::Summary, - DashboardTab::Branches, - DashboardTab::History, - DashboardTab::Scheduled, - DashboardTab::Sequences, - DashboardTab::Moves, - ] { - dashboard.tab = tab; - let (_, output) = render_dashboard(&mut dashboard, &ctx, &settings, width, height); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - if width == 640.0 && tab == DashboardTab::Summary { - assert_narrow_summary(&shapes); - } - } - } - } - - #[test] - fn dashboard_stays_full_when_training_depth_is_limited() { - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - library.repertoire_mut(&id).unwrap().set_max_plies(2); - let dashboard = build(&library, &LearningStoreData::default()).unwrap(); - let view = &dashboard.views[1]; - assert_eq!(view.scope.max_depth, None); - assert_eq!(view.summary.total, 2); - assert!(!view.branches.is_empty()); - - let training_scope = - StatsScope::for_repertoire(id, LearningSide::White, BASE).with_max_depth(Some(2)); - let training = aggregate_scope( - &library, - &LearningData::default(), - &training_scope, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(training.summary.total, 1); - } -} diff --git a/apps/desktop/src/learning_training.rs b/apps/desktop/src/learning_training.rs deleted file mode 100644 index bc13807..0000000 --- a/apps/desktop/src/learning_training.rs +++ /dev/null @@ -1,4139 +0,0 @@ -use std::{ - collections::{BTreeMap, BTreeSet, VecDeque}, - sync::{ - atomic::{AtomicU64, Ordering}, - mpsc, - }, - time::Duration, -}; - -use chess_core::shakmaty::{ - CastlingMode, Chess, Color, Move, Position, Square, fen::Fen, uci::UciMove, -}; -use chess_core::{Game, NodeId}; -use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; -use trainer::repertoire::{ - AttemptApplication, LearningContextPolicy, LearningContextStep, LearningData, LearningItemKey, - LearningPresentation, LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, - LearningSide, LearningStore, Library, PersistedSessionAttempt, QueueMode, RepertoireId, - SrsSettings, StatsScope, TrainingAttempt, TrainingEventType, TrainingMode, - active_learning_keys, fen4, -}; -use web_time::{Instant, SystemTime, UNIX_EPOCH}; - -use crate::assets::Sound; -use crate::board::{Arrow, BoardState, BoardView}; -use crate::i18n::{tr, trf}; -use crate::repertoire_training::{BoardAnnotations, pgn_annotations_at}; -use crate::settings::Settings; - -const WRONG_SHOWN: Duration = Duration::from_millis(400); -const DEFAULT_ANIMATION: Duration = Duration::from_millis(250); -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - -pub enum LearningTrainingAction { - Back, - OpenSettings, - Sound(Sound), - Toast(String), -} - -#[derive(Clone)] -struct VisualMove { - #[allow(dead_code)] - uci: String, - before: Chess, - after: Chess, - from: Square, - to: Square, -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum PlayOutcome { - CorrectIndependent, - WrongIndependent, - WrongReplay, - ReplayAfterError, - PreviewedReplay, -} - -#[derive(Clone)] -enum CommitKind { - Context, - ReusedContext, - Play { - visual: Box, - outcome: PlayOutcome, - shown_prefix: ShownPrefix, - }, - Preview, -} - -#[derive(Clone)] -struct ShownPrefix { - repertoire_id: RepertoireId, - path: Vec, -} - -#[derive(Clone)] -struct PendingCommit { - attempts: Vec, - kind: CommitKind, -} - -enum Playback { - Automatic { - current: Box, - remaining: VecDeque, - started_at: Instant, - duration: Duration, - completed: usize, - total: usize, - }, - Paused { - remaining: VecDeque, - completed: usize, - }, - Wrong { - visual: Box, - until: Instant, - }, - Alternative { - visual: Box, - until: Instant, - }, - Accepted { - started_at: Instant, - duration: Duration, - independent_success: bool, - }, -} - -pub struct LearningTrainingUi { - library: Library, - store: LearningStore, - session: LearningSessionSnapshot, - learning: LearningData, - presentation: Option, - completed_attempt_ids: BTreeSet, - pending_commit: Option, - commit_in_flight: Option>>, - #[cfg(test)] - synchronous_commits: bool, - save_error: Option, - error: Option, - board: BoardState, - board_position: Chess, - // Parsed once in the training-start worker, never in a frame or save callback. - annotation_games: BTreeMap, - repertoire_answers: BTreeSet, - // The visible node is independent of the session's already-advanced target. - displayed_node: Option<(RepertoireId, NodeId)>, - board_shown: bool, - pending_automatic: Option>, - shown_prefix: Option, - playback: Option, - pause_requested: bool, - stopped: bool, - needs_prepare: bool, - animation: Duration, - ready_since: Option, - last_move: Option<(Square, Square)>, - flipped: bool, - message: Option, - confirm_discard: bool, - discard_requested: bool, - pending_sounds: Vec, - #[cfg(test)] - visual_log: Vec, -} - -impl LearningTrainingUi { - #[allow(dead_code)] - pub fn new( - library: Library, - store: LearningStore, - scope: StatsScope, - settings: SrsSettings, - introduce_new: bool, - flipped: bool, - ) -> Result { - Self::new_with_policy( - library, - store, - scope, - settings, - introduce_new, - flipped, - QueueMode::SpacedRepetition, - LearningContextPolicy::default(), - ) - } - - #[allow(dead_code)] - pub fn new_with_mode( - library: Library, - store: LearningStore, - scope: StatsScope, - settings: SrsSettings, - introduce_new: bool, - flipped: bool, - mode: QueueMode, - ) -> Result { - Self::new_with_policy( - library, - store, - scope, - settings, - introduce_new, - flipped, - mode, - LearningContextPolicy::default(), - ) - } - - #[allow(clippy::too_many_arguments)] - pub fn new_with_policy( - library: Library, - store: LearningStore, - scope: StatsScope, - settings: SrsSettings, - introduce_new: bool, - flipped: bool, - mode: QueueMode, - context_policy: LearningContextPolicy, - ) -> Result { - if introduce_new && mode != QueueMode::SpacedRepetition { - return Err(format!("new learning items require SRS, not {mode:?}")); - } - let data = store.load().map_err(|error| error.to_string())?; - let existing = if introduce_new { - None - } else { - data.session_snapshots - .iter() - .filter(|session| { - (mode != QueueMode::SpacedRepetition - || session.phase != LearningSessionPhase::Finished) - && compatible(session, &scope, mode) - }) - .max_by_key(|session| session.revision) - .cloned() - }; - let mut session = match existing { - Some(session) => { - let mut session = session - .resume(&library) - .map_err(|error| error.to_string())?; - if session.phase == LearningSessionPhase::Finished - && matches!(mode, QueueMode::ReviewInOrder | QueueMode::LeastRecent) - { - session - .start_next_pass(&library, &data.learning) - .map_err(|error| error.to_string())?; - } - session - } - None => { - let mut session = LearningSessionSnapshot::new_with_mode( - unique_id("learning-session"), - &library, - &data.learning, - scope, - settings, - mode, - ) - .map_err(|error| error.to_string())?; - session.context_policy = context_policy; - if introduce_new { - session - .introduce_new(&library, &data.learning) - .map_err(|error| error.to_string())?; - } - session - } - }; - store - .save_session(&mut session) - .map_err(|error| error.to_string())?; - let completed_attempt_ids = data - .learning - .attempts - .iter() - .filter(|attempt| attempt.session_id == session.id()) - .map(|attempt| attempt.client_attempt_id.clone()) - .collect(); - let flipped = match session.stats_scope.side { - LearningSide::White => flipped, - LearningSide::Black => !flipped, - }; - let repertoire_answers = active_learning_keys(&library, &session.stats_scope) - .map_err(|error| error.to_string())?; - let annotation_games = session - .queue - .iter() - .map(|target| target.repertoire_id.clone()) - .collect::>() - .into_iter() - .filter_map(|id| { - library - .repertoire(&id) - .map(|repertoire| (id, repertoire.game())) - }) - .collect(); - Ok(Self { - library, - store, - session, - learning: data.learning, - presentation: None, - completed_attempt_ids, - pending_commit: None, - commit_in_flight: None, - #[cfg(test)] - synchronous_commits: false, - save_error: None, - error: None, - board: BoardState::default(), - board_position: Chess::default(), - annotation_games, - repertoire_answers, - displayed_node: None, - board_shown: false, - pending_automatic: None, - shown_prefix: None, - playback: None, - pause_requested: false, - stopped: false, - needs_prepare: true, - animation: DEFAULT_ANIMATION, - ready_since: None, - last_move: None, - flipped, - message: None, - confirm_discard: false, - discard_requested: false, - pending_sounds: Vec::new(), - #[cfg(test)] - visual_log: Vec::new(), - }) - } - - #[allow(dead_code)] - pub fn learning_data(&self) -> &LearningData { - &self.learning - } - - pub fn has_unsaved(&self) -> bool { - self.pending_commit.is_some() || self.save_error.is_some() - } - - pub fn target_available(&self) -> bool { - self.session.current_target().is_some() - } - - pub fn is_finished(&self) -> bool { - self.session.phase == LearningSessionPhase::Finished - && self.playback.is_none() - && !self.has_unsaved() - } - - #[allow(dead_code)] - pub fn session_id(&self) -> &str { - self.session.id() - } - - fn can_input(&self) -> bool { - !self.has_unsaved() - && !self.stopped - && self.error.is_none() - && !self.needs_prepare - && self.playback.is_none() - && self.session.current_target().is_some() - && matches!( - self.session.phase, - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent - | LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay - ) - } - - fn can_hint(&self) -> bool { - self.can_input() && self.session.phase == LearningSessionPhase::AwaitingIndependent - } - - fn tick_at(&mut self, now: Instant, animation: Duration, happened_at: i64) { - self.animation = animation; - self.poll_commit(now); - if self.stopped || self.has_unsaved() { - return; - } - if self.board_shown - && let Some(steps) = self.pending_automatic.take() - { - self.start_next_automatic(steps, now, 0); - } - if self.needs_prepare { - self.prepare_presentation(now); - } - loop { - if self.stopped || self.has_unsaved() || self.error.is_some() { - return; - } - if self.needs_prepare { - self.prepare_presentation(now); - continue; - } - let Some(deadline) = self.playback_deadline() else { - return; - }; - if now < deadline { - return; - } - match self.playback { - Some(Playback::Wrong { .. } | Playback::Alternative { .. }) => { - self.finish_temporary_move(now); - } - Some(Playback::Accepted { .. }) => self.finish_accepted(now), - Some(Playback::Automatic { .. }) => { - let id = unique_id(self.session.id()); - self.advance_context_with_id_at(id, now, happened_at); - } - Some(Playback::Paused { .. }) | None => return, - } - if !animation.is_zero() { - return; - } - } - } - - fn playback_deadline(&self) -> Option { - match &self.playback { - Some(Playback::Automatic { - started_at, - duration, - .. - }) - | Some(Playback::Accepted { - started_at, - duration, - .. - }) => Some(*started_at + *duration), - Some(Playback::Wrong { until, .. } | Playback::Alternative { until, .. }) => { - Some(*until) - } - Some(Playback::Paused { .. }) | None => None, - } - } - - fn prepare_presentation(&mut self, now: Instant) { - let presentation = match self - .session - .presentation_with_learning(&self.library, &self.learning) - { - Ok(presentation) => presentation, - Err(error) => { - self.error = Some(error.to_string()); - self.needs_prepare = false; - self.ready_since = None; - return; - } - }; - self.error = None; - self.needs_prepare = false; - self.presentation = Some(presentation.clone()); - let Some(ref current) = presentation.current_position else { - self.ready_since = None; - self.pending_automatic = None; - if self.session.queue.is_empty() && self.message.is_none() { - self.message = - Some(tr("No due moves. New items are introduced only on request.").to_owned()); - } - return; - }; - // A following task may extend the line that is already on the board. Keep - // its context journal, but do not rewind and animate those same moves again. - // The complete path and repertoire must match; a transposed FEN is not enough. - if self.reuse_shown_context(&presentation, now) { - return; - } - self.shown_prefix = None; - if !presentation.automatic_context.is_empty() { - let mut steps = VecDeque::new(); - for step in presentation.automatic_context { - match VisualMove::from_context(&step) { - Ok(_) => steps.push_back(step), - Err(error) => { - self.error = Some(error); - self.ready_since = None; - return; - } - } - } - self.ready_since = None; - let Some(first) = steps.front() else { - self.error = Some("automatic context has no visual step".to_owned()); - return; - }; - self.board_position = match parse_position(&first.from) { - Ok(position) => position, - Err(error) => { - self.error = Some(error); - return; - } - }; - self.set_displayed_context(self.session.context_index); - self.board_shown = false; - self.pending_automatic = Some(steps); - self.playback = None; - self.last_move = None; - return; - } - self.pending_automatic = None; - let position = match parse_position(current) { - Ok(position) => position, - Err(error) => { - self.error = Some(error); - self.ready_since = None; - return; - } - }; - if fen4(&self.board_position) != current.fen4 { - self.last_move = None; - } - self.board_position = position; - self.set_displayed_context(self.session.context_index); - self.playback = None; - match self.session.phase { - LearningSessionPhase::AwaitingIndependent => { - self.ready_since = Some(now); - self.message = Some(tr("Your turn: play a repertoire move.").to_owned()); - } - LearningSessionPhase::AwaitingContextIndependent => { - self.ready_since = Some(now); - self.message = Some(format!( - "{} · {}", - tr("Automatic move/context"), - tr("Your turn: play a repertoire move.") - )); - } - LearningSessionPhase::AwaitingReplayAfterError => { - self.ready_since = None; - self.message = Some(tr("Wrong move. Replay the revealed move; it will not count as an independent success.").to_owned()); - } - LearningSessionPhase::PreviewedReplay => { - self.ready_since = None; - self.message = Some( - tr("PREVIEWED · replay the shown move; this is not an independent success.") - .to_owned(), - ); - } - phase => { - self.ready_since = None; - self.error = Some(format!( - "learning session has no playable position in {phase:?}" - )); - } - } - } - - fn reuse_shown_context(&mut self, presentation: &LearningPresentation, at: Instant) -> bool { - let Some(prefix) = &self.shown_prefix else { - return false; - }; - let Some(target) = self.session.current_target() else { - return false; - }; - let Some(remaining) = prefix.path.len().checked_sub(self.session.context_index) else { - return false; - }; - if remaining == 0 - || target.repertoire_id != prefix.repertoire_id - || !presentation.target_path.starts_with(&prefix.path) - // An independent context question must still be asked. Only reuse a - // prefix that the core explicitly allows to be automatic in full. - || presentation.automatic_context.len() < remaining - || presentation.automatic_context[remaining - 1].to.fen4 != fen4(&self.board_position) - { - return false; - } - // These moves are already visible. Preserve each AUTO_CONTEXT event, - // but commit the whole prefix once instead of rereading/writing all - // history and rebuilding the presentation once per old move. - let mut next_session = self.session.clone(); - let mut attempts = Vec::with_capacity(remaining); - let happened_at = now(); - for _ in 0..remaining { - let id = unique_id(next_session.id()); - match next_session.advance_context_with_learning( - &self.library, - &self.learning, - id, - happened_at, - ) { - Ok(attempt) => attempts.push(attempt), - Err(error) => { - self.error = Some(error.to_string()); - return true; - } - } - } - self.session = next_session; - self.ready_since = None; - self.pending_commit = Some(PendingCommit { - attempts, - kind: CommitKind::ReusedContext, - }); - self.persist_pending(at); - true - } - - fn start_next_automatic( - &mut self, - mut remaining: VecDeque, - now: Instant, - completed: usize, - ) { - let Some(step) = remaining.pop_front() else { - self.needs_prepare = true; - self.prepare_presentation(now); - return; - }; - let total = completed.saturating_add(remaining.len()).saturating_add(1); - let current = match VisualMove::from_context(&step) { - Ok(current) => current, - Err(error) => { - self.error = Some(error); - return; - } - }; - self.board_position = current.after.clone(); - self.set_displayed_context(self.session.context_index + 1); - self.last_move = Some((current.from, current.to)); - self.message = None; - self.playback = Some(Playback::Automatic { - current: Box::new(current.clone()), - remaining, - started_at: now, - duration: self.animation.div_f32(step.speed_factor.max(0.01) as f32), - completed, - total, - }); - #[cfg(test)] - self.visual_log.push(current.uci.clone()); - self.queue_sound(Sound::Move); - } - - fn advance_context_with_id_at( - &mut self, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if self.has_unsaved() - || !matches!(self.playback, Some(Playback::Automatic { .. })) - || self.completed_attempt_ids.contains(&client_attempt_id) - { - return false; - } - let attempt = match self.session.advance_context_with_learning( - &self.library, - &self.learning, - client_attempt_id, - happened_at, - ) { - Ok(attempt) => attempt, - Err(error) => { - self.error = Some(error.to_string()); - return false; - } - }; - self.begin_commit(attempt, CommitKind::Context, now); - true - } - - fn finish_context(&mut self, now: Instant) { - let Some(Playback::Automatic { - remaining, - completed, - .. - }) = self.playback.take() - else { - self.error = Some("automatic context is missing its visual step".to_owned()); - return; - }; - let completed = completed + 1; - if self.pause_requested && !remaining.is_empty() { - self.pause_requested = false; - self.message = Some(tr("Paused").to_owned()); - self.playback = Some(Playback::Paused { - remaining, - completed, - }); - return; - } - self.pause_requested = false; - self.start_next_automatic(remaining, now, completed); - } - - fn is_autoplay(&self) -> bool { - matches!( - &self.playback, - Some(Playback::Automatic { .. } | Playback::Paused { .. }) - ) - } - - fn autoplay_paused(&self) -> bool { - matches!(&self.playback, Some(Playback::Paused { .. })) - } - - fn request_pause(&mut self) -> bool { - let active = matches!(&self.playback, Some(Playback::Automatic { .. })); - if active { - self.pause_requested = true; - } - active - } - - fn continue_autoplay(&mut self, now: Instant) -> bool { - if self.stopped || self.has_unsaved() { - return false; - } - let Some(Playback::Paused { - remaining, - completed, - }) = self.playback.take() - else { - return false; - }; - self.pause_requested = false; - self.start_next_automatic(remaining, now, completed); - true - } - - fn stop_autoplay(&mut self, actions: &mut Vec) -> bool { - if !self.is_autoplay() { - return false; - } - if self.has_unsaved() { - self.request_back(actions); - return true; - } - self.pause_requested = false; - let playback = self.playback.take(); - if let Some(Playback::Automatic { current, .. }) = playback { - self.board_position = current.before.clone(); - } - self.last_move = None; - self.ready_since = None; - self.stopped = true; - actions.push(LearningTrainingAction::Back); - true - } - - fn play_move_at(&mut self, mv: Move, now: Instant, happened_at: i64) -> bool { - let id = unique_id(self.session.id()); - self.play_move_with_id_at(mv, id, now, happened_at) - } - - fn play_move_with_id_at( - &mut self, - mv: Move, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { - return false; - } - let Some(expected_uci) = self.session.current_expected_uci().map(str::to_owned) else { - return false; - }; - let before = self.board_position.clone(); - let uci = mv.to_uci(CastlingMode::Standard).to_string(); - let visual = VisualMove::new(uci.clone(), before, mv); - let phase = self.session.phase; - let independent = matches!( - phase, - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent - ); - let Some(target) = self.session.current_target() else { - return false; - }; - let Some(prefix) = target.path.get(..self.session.context_index) else { - return false; - }; - let mut path = prefix.to_vec(); - path.push(uci.clone()); - let shown_prefix = ShownPrefix { - repertoire_id: target.repertoire_id.clone(), - path, - }; - if !independent && uci != expected_uci { - let key = LearningItemKey::new(target.key.user_id.clone(), fen4(&visual.before), &uci); - if self.repertoire_answers.contains(&key) { - let already_completed = self.session.completed_keys.contains(&key); - self.show_repertoire_alternative(visual, &shown_prefix, already_completed, now); - return true; - } - self.set_displayed_path(Some(&shown_prefix)); - self.start_playback(visual, PlayOutcome::WrongReplay, now); - return true; - } - let response_time_ms = independent.then(|| { - self.ready_since.map_or(0, |ready| { - u64::try_from(now.saturating_duration_since(ready).as_millis()).unwrap_or(u64::MAX) - }) - }); - let attempt = match self.session.play_uci_with_learning_answers( - &self.library, - &self.learning, - &self.repertoire_answers, - &uci, - client_attempt_id, - happened_at, - response_time_ms, - ) { - Ok(attempt) => attempt, - Err(LearningSessionError::RepertoireAlternative { already_completed }) => { - self.show_repertoire_alternative(visual, &shown_prefix, already_completed, now); - return true; - } - Err(error) => { - self.error = Some(error.to_string()); - return false; - } - }; - let outcome = match attempt.event_type { - TrainingEventType::CorrectIndependent => PlayOutcome::CorrectIndependent, - TrainingEventType::IncorrectIndependent => PlayOutcome::WrongIndependent, - TrainingEventType::ReplayAfterError => PlayOutcome::ReplayAfterError, - TrainingEventType::AutoContext => PlayOutcome::PreviewedReplay, - TrainingEventType::Previewed | TrainingEventType::IllegalMove => { - self.error = Some("legal board input produced a non-play event".to_owned()); - return false; - } - }; - // The legal move is visible immediately, including while its event is - // being saved. Input stays blocked until persistence acknowledges it. - // In particular a dropped piece must not jump back to its source square. - self.board_position = visual.after.clone(); - self.set_displayed_path(Some(&shown_prefix)); - self.last_move = Some((visual.from, visual.to)); - self.begin_commit( - attempt, - CommitKind::Play { - visual: Box::new(visual), - outcome, - shown_prefix, - }, - now, - ); - true - } - - fn play_uci_with_id_at( - &mut self, - uci: &str, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { - return false; - } - let mv = uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&self.board_position).ok()); - let Some(mv) = mv else { - self.message = Some(tr("Illegal move in the current position").to_owned()); - return false; - }; - self.play_move_with_id_at(mv, client_attempt_id, now, happened_at) - } - - fn start_playback(&mut self, visual: VisualMove, outcome: PlayOutcome, now: Instant) { - self.ready_since = None; - self.board_position = visual.after.clone(); - self.last_move = Some((visual.from, visual.to)); - match outcome { - PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { - self.message = Some(tr("Wrong move. Replay the revealed move; it will not count as an independent success.").to_owned()); - self.playback = Some(Playback::Wrong { - visual: Box::new(visual), - until: now + WRONG_SHOWN, - }); - self.queue_sound(Sound::Wrong); - } - PlayOutcome::CorrectIndependent - | PlayOutcome::ReplayAfterError - | PlayOutcome::PreviewedReplay => { - self.message = Some( - tr(match outcome { - PlayOutcome::CorrectIndependent => "Correct independent answer.", - PlayOutcome::ReplayAfterError => { - "REPLAY_AFTER_ERROR · not an independent success." - } - PlayOutcome::PreviewedReplay => { - "PREVIEWED · shown move completed; no independent success recorded." - } - PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { - "Wrong move. Replay the revealed move; it will not count as an independent success." - } - }) - .to_owned(), - ); - self.playback = Some(Playback::Accepted { - started_at: now, - duration: self.animation, - independent_success: outcome == PlayOutcome::CorrectIndependent, - }); - self.queue_sound(Sound::Move); - } - } - } - - fn show_repertoire_alternative( - &mut self, - visual: VisualMove, - shown_prefix: &ShownPrefix, - already_completed: bool, - now: Instant, - ) { - self.ready_since = None; - self.board_position = visual.after.clone(); - self.set_displayed_path(Some(shown_prefix)); - self.last_move = Some((visual.from, visual.to)); - self.message = Some( - tr(if already_completed { - "This repertoire move has already been reviewed in this session." - } else { - "This move is in your repertoire, but is not a task in this session." - }) - .to_owned(), - ); - self.playback = Some(Playback::Alternative { - visual: Box::new(visual), - until: now + WRONG_SHOWN.max(self.animation), - }); - } - - fn finish_temporary_move(&mut self, now: Instant) { - let (visual, explanation) = match self.playback.take() { - Some(Playback::Wrong { visual, .. }) => (visual, None), - Some(Playback::Alternative { visual, .. }) => (visual, self.message.clone()), - _ => return, - }; - self.board_position = visual.before; - self.last_move = None; - self.needs_prepare = true; - self.prepare_presentation(now); - if let Some(explanation) = explanation { - self.message = Some(format!( - "{explanation} {}", - self.message.as_deref().unwrap_or_default() - )); - } - } - - fn finish_accepted(&mut self, now: Instant) { - let Some(Playback::Accepted { - independent_success, - .. - }) = self.playback.take() - else { - return; - }; - if independent_success && self.session.phase == LearningSessionPhase::Finished { - self.queue_sound(Sound::Success); - } - self.needs_prepare = true; - self.prepare_presentation(now); - } - - fn request_hint_with_id_at( - &mut self, - client_attempt_id: String, - now: Instant, - happened_at: i64, - ) -> bool { - if !self.can_hint() || self.completed_attempt_ids.contains(&client_attempt_id) { - return false; - } - let attempt = match self.session.preview(client_attempt_id, happened_at) { - Ok(Some(attempt)) => attempt, - Ok(None) => return false, - Err(error) => { - self.error = Some(error.to_string()); - return false; - } - }; - self.board.clear(); - self.begin_commit(attempt, CommitKind::Preview, now); - true - } - - fn begin_commit(&mut self, attempt: TrainingAttempt, kind: CommitKind, now: Instant) { - if self.pending_commit.is_some() { - self.save_error = - Some("another learning event is still waiting to be saved".to_owned()); - return; - } - self.pending_commit = Some(PendingCommit { - attempts: vec![attempt], - kind, - }); - self.persist_pending(now); - } - - fn persist_pending(&mut self, _now: Instant) { - let Some(pending) = self.pending_commit.clone() else { - return; - }; - if self.commit_in_flight.is_some() { - return; - } - #[cfg(test)] - if self.synchronous_commits { - let result = self - .store - .apply_attempts_and_session(pending.attempts.clone(), &mut self.session) - .map_err(|error| error.to_string()); - self.finish_commit(result, _now); - return; - } - let store = self.store.clone(); - let mut session = self.session.clone(); - let (tx, rx) = mpsc::channel(); - self.commit_in_flight = Some(rx); - self.save_error = None; - if let Err(error) = crate::platform::spawn("learning-save-attempt", move || { - let result = store - .apply_attempts_and_session(pending.attempts, &mut session) - .map_err(|error| error.to_string()); - let _ = tx.send(result); - }) { - self.commit_in_flight = None; - self.save_error = Some(error.to_string()); - self.ready_since = None; - } - } - - fn poll_commit(&mut self, now: Instant) { - let Some(receiver) = &self.commit_in_flight else { - return; - }; - let result = match receiver.try_recv() { - Ok(result) => result, - Err(mpsc::TryRecvError::Empty) => return, - Err(mpsc::TryRecvError::Disconnected) => { - Err("learning save worker disconnected".to_owned()) - } - }; - self.commit_in_flight = None; - self.finish_commit(result, now); - } - - fn finish_commit(&mut self, result: Result, now: Instant) { - let Some(pending) = self.pending_commit.clone() else { - return; - }; - match result { - Ok(persisted) => { - let duplicate = persisted.application == AttemptApplication::Duplicate; - self.learning = persisted.learning; - self.session = persisted.session; - self.completed_attempt_ids.extend( - pending - .attempts - .iter() - .map(|attempt| attempt.client_attempt_id.clone()), - ); - self.pending_commit = None; - self.save_error = None; - self.confirm_discard = false; - if duplicate { - self.playback = None; - self.shown_prefix = None; - self.pause_requested = false; - self.ready_since = None; - self.needs_prepare = true; - self.prepare_presentation(now); - return; - } - match pending.kind { - CommitKind::Context => self.finish_context(now), - CommitKind::ReusedContext => self.needs_prepare = true, - CommitKind::Play { - visual, - outcome, - shown_prefix, - } => { - self.shown_prefix = (!matches!( - outcome, - PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay - )) - .then_some(shown_prefix); - self.start_playback(*visual, outcome, now); - } - CommitKind::Preview => { - self.needs_prepare = true; - self.prepare_presentation(now); - } - } - } - Err(error) => { - self.save_error = Some(error.to_string()); - self.ready_since = None; - } - } - } - - fn retry_pending(&mut self, now: Instant) { - if self.pending_commit.is_some() { - self.persist_pending(now); - } - } - - fn queue_sound(&mut self, sound: Sound) { - if sound == Sound::Move && self.pending_sounds.last() == Some(&Sound::Move) { - return; - } - self.pending_sounds.push(sound); - } - - fn request_back(&mut self, actions: &mut Vec) { - if self.has_unsaved() { - self.confirm_discard = true; - } else { - actions.push(LearningTrainingAction::Back); - } - } - - fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { - if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { - return; - } - let autoplay = self.is_autoplay(); - let mut command = None; - ui.input_mut(|input| { - if autoplay - && (input.consume_key(Modifiers::NONE, Key::Space) - || input.consume_key(Modifiers::NONE, Key::P)) - { - command = Some("toggle-pause"); - } else if autoplay && input.consume_key(Modifiers::NONE, Key::Escape) { - command = Some("stop"); - } else if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) - || (!self.board.is_busy() && input.consume_key(Modifiers::NONE, Key::Escape)) - { - command = Some("back"); - } else if input.consume_key(Modifiers::NONE, Key::F) { - command = Some("flip"); - } else if input.consume_key(Modifiers::NONE, Key::H) { - command = Some("hint"); - } else if input.consume_key(Modifiers::NONE, Key::L) - || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) - { - command = Some("engine"); - } else if self.is_finished() && input.consume_key(Modifiers::NONE, Key::Enter) { - command = Some("back"); - } - }); - match command { - Some("toggle-pause") => { - if self.autoplay_paused() { - self.continue_autoplay(Instant::now()); - } else { - self.request_pause(); - } - } - Some("stop") => { - self.stop_autoplay(actions); - } - Some("back") => self.request_back(actions), - Some("flip") => self.flipped = !self.flipped, - Some("hint") => { - let id = unique_id(self.session.id()); - self.request_hint_with_id_at(id, Instant::now(), now()); - } - Some("engine") => actions.push(LearningTrainingAction::Toast( - tr("The engine is off while training").to_owned(), - )), - _ => {} - } - } - - fn board_animation_seconds(&self, settings: &Settings) -> f32 { - if self.pending_automatic.is_some() { - return 0.0; - } - match &self.playback { - Some(Playback::Automatic { duration, .. }) => duration.as_secs_f32(), - _ => settings.animation.seconds(), - } - } - - fn set_displayed_context(&mut self, played: usize) { - let prefix = self.session.current_target().and_then(|target| { - Some(ShownPrefix { - repertoire_id: target.repertoire_id.clone(), - path: target.path.get(..played)?.to_vec(), - }) - }); - self.set_displayed_path(prefix.as_ref()); - } - - fn set_displayed_path(&mut self, prefix: Option<&ShownPrefix>) { - self.displayed_node = prefix.and_then(|prefix| { - let game = self.annotation_games.get(&prefix.repertoire_id)?; - let mut at = NodeId::ROOT; - for uci in &prefix.path { - let mv = uci - .parse::() - .ok()? - .to_move(game.position(at)?) - .ok()?; - at = game.find_child(at, mv)?; - } - Some((prefix.repertoire_id.clone(), at)) - }); - } - - fn displayed_annotations(&self) -> BoardAnnotations { - let Some((id, at)) = &self.displayed_node else { - return BoardAnnotations::default(); - }; - let Some(game) = self.annotation_games.get(id) else { - return BoardAnnotations::default(); - }; - // A visual wrong move outside the source tree must never inherit the - // expected move's badge or arrows merely because the task advanced. - if game - .position(*at) - .is_none_or(|position| position != &self.board_position) - { - return BoardAnnotations::default(); - } - pgn_annotations_at(game, *at) - } - - fn board_ui(&mut self, ui: &mut Ui, settings: &Settings) { - let interactive = self.can_input(); - let annotations = self.displayed_annotations(); - let mut arrows = annotations.arrows; - if self.playback.is_none() - && let Some(uci) = self - .presentation - .as_ref() - .and_then(|presentation| presentation.revealed_move.as_deref()) - && let Some(mv) = uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&self.board_position).ok()) - { - arrows.push(Arrow { - from: mv.from().unwrap_or_else(|| mv.to()), - to: crate::board::ui_target(&mv), - color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), - weight: 1.0, - }); - } - let alert = match &self.playback { - Some(Playback::Wrong { visual, .. }) => Some((visual.from, visual.to)), - _ => None, - }; - let area = ui.available_rect_before_wrap(); - let side = area.width().min(area.height()).max(1.0).floor(); - let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); - let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); - let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - let played = BoardView { - pos: &self.board_position, - orientation: if self.flipped { - Color::Black - } else { - Color::White - }, - last_move: self.last_move, - arrows: &arrows, - circles: &annotations.circles, - badge: annotations.badge, - interactive, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: self.board_animation_seconds(settings), - premove: None, - auto_queen: false, - alert, - } - .show(ui, &mut self.board); - if let Some(mv) = played { - self.play_move_at(mv, Instant::now(), now()); - } - }); - self.board_shown = true; - } - - fn status_card(&mut self, ui: &mut Ui) { - let alert = matches!(self.playback, Some(Playback::Wrong { .. })); - card(ui, alert).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.set_clip_rect(ui.max_rect()); - if self.is_finished() { - ui.label(RichText::new(tr("Training complete")).strong().size(17.0)); - } else if let Some(Playback::Automatic { - completed, total, .. - }) = &self.playback - { - ui.label( - RichText::new(trf( - "Automatic context · {current} of {total}", - &[("current", &(completed + 1)), ("total", total)], - )) - .strong(), - ); - } else if let Some(Playback::Paused { - remaining, - completed, - }) = &self.playback - { - let progress = trf( - "Automatic context · {current} of {total}", - &[ - ("current", completed), - ("total", &completed.saturating_add(remaining.len())), - ], - ); - ui.label(RichText::new(format!("{} · {progress}", tr("Paused"))).strong()); - } else if self.session.phase == LearningSessionPhase::PreviewedReplay { - ui.label(RichText::new(tr("Hint")).strong()); - } else if self.session.phase == LearningSessionPhase::AwaitingReplayAfterError { - ui.label(RichText::new(tr("Mistake")).strong()); - } - if self.can_input() { - let count = self - .session - .pending_answers_for_position(&fen4(&self.board_position)) - .len(); - if count > 1 { - ui.label(trf( - "Repertoire answers remaining here: {count}", - &[("count", &count)], - )); - } - } - if let Some(error) = self.error.clone().or_else(|| self.save_error.clone()) { - ui.colored_label( - ui.visuals().error_fg_color, - if self.save_error.is_some() { - tr("Could not save") - } else { - tr("Mistake") - }, - ); - egui::CollapsingHeader::new(tr("Details")).show(ui, |ui| { - egui::ScrollArea::vertical() - .max_height(120.0) - .show(ui, |ui| { - ui.add(egui::Label::new(error).wrap()); - }); - }); - } else if let Some(message) = &self.message - && !(self.autoplay_paused() && message == tr("Paused")) - { - ui.add(egui::Label::new(message).wrap()); - } - }); - } - - fn side(&mut self, ui: &mut Ui, actions: &mut Vec) { - let rect = ui.available_rect_before_wrap(); - let footer = egui::Rect::from_min_max( - egui::pos2(rect.left(), (rect.bottom() - 44.0).max(rect.top())), - rect.max, - ); - let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); - ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { - ui.set_clip_rect(body); - self.side_body(ui, actions); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { - ui.separator(); - if ui - .add_sized( - [30.0, 30.0], - egui::Button::new(RichText::new("🔃").size(18.0)), - ) - .on_hover_text(tr("Flip board (F)")) - .clicked() - { - self.flipped = !self.flipped; - } - }); - } - - fn side_body(&mut self, ui: &mut Ui, actions: &mut Vec) { - ui.spacing_mut().item_spacing.y = 6.0; - fixed_block(ui, 44.0, |ui| { - let (done, total) = main_task_progress(&self.session); - ui.add( - egui::Label::new( - RichText::new(trf( - "Tasks: {done} of {total}", - &[("done", &done), ("total", &total)], - )) - .strong() - .size(15.0), - ) - .truncate(), - ); - let side = tr(match self.session.stats_scope.side { - LearningSide::White => "White", - LearningSide::Black => "Black", - }); - ui.add( - egui::Label::new(format!( - "{} · {side}", - queue_mode_label(self.session.session.mode) - )) - .truncate(), - ); - }); - let button_width = ((ui.available_width() - 8.0) / 2.0).clamp(80.0, 180.0); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - let save_failed = self.pending_commit.is_some() && self.save_error.is_some(); - if save_failed { - if ui - .add_sized([button_width, 30.0], egui::Button::new(tr("Retry"))) - .clicked() - { - self.retry_pending(Instant::now()); - } - } else if self.is_autoplay() { - let paused = self.autoplay_paused(); - let label = if paused { tr("Continue") } else { tr("Pause") }; - if ui - .add_sized([button_width, 30.0], egui::Button::new(label)) - .on_hover_text("Space / P") - .clicked() - { - if paused { - self.continue_autoplay(Instant::now()); - } else { - self.request_pause(); - } - } - } else if self.is_finished() { - if crate::widgets::primary_wide(ui, tr("Back to repertoire"), button_width) - .on_hover_text("Enter") - .clicked() - { - self.request_back(actions); - } - } else if ui - .add_enabled( - self.can_hint(), - egui::Button::new(tr("Hint")).min_size(vec2(button_width, 30.0)), - ) - .clicked() - { - let id = unique_id(self.session.id()); - self.request_hint_with_id_at(id, Instant::now(), now()); - } - if save_failed { - let label = if self.confirm_discard { - tr("Exit") - } else { - tr("Back to repertoire") - }; - if ui - .add_sized([button_width, 30.0], egui::Button::new(label)) - .clicked() - { - if self.confirm_discard { - self.discard_requested = true; - } else { - self.confirm_discard = true; - } - } - } else if self.is_autoplay() { - if ui - .add_sized([button_width, 30.0], egui::Button::new(tr("Stop"))) - .on_hover_text("Escape") - .clicked() - { - self.stop_autoplay(actions); - } - } else { - ui.allocate_space(vec2(button_width, 30.0)); - } - }); - ui.add_space(2.0); - self.status_card(ui); - if self.confirm_discard && self.has_unsaved() { - ui.add( - egui::Label::new( - RichText::new(tr( - "Only the events that could not be saved will be discarded", - )) - .weak(), - ) - .wrap(), - ); - } - } - - pub fn show( - &mut self, - ui: &mut egui::Ui, - settings: &Settings, - name: &str, - ) -> Vec { - let animation = Duration::from_secs_f32(settings.animation.seconds()); - self.tick_at(Instant::now(), animation, now()); - if self.commit_in_flight.is_some() { - ui.ctx().request_repaint_after(Duration::from_millis(16)); - } else if let Some(deadline) = self.playback_deadline() { - ui.ctx() - .request_repaint_after(deadline.saturating_duration_since(Instant::now())); - } else if self.needs_prepare || self.pending_automatic.is_some() { - ui.ctx().request_repaint(); - } - let mut actions = Vec::new(); - self.keyboard(ui, &mut actions); - egui::Panel::top("learning_training_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}"), name); - if back { - self.request_back(&mut actions); - } - if settings { - actions.push(LearningTrainingAction::OpenSettings); - } - }); - let available = ui.available_rect_before_wrap(); - let background = ui.visuals().window_fill(); - ui.painter_at(available) - .rect_filled(available, 0.0, background); - let width = available.width(); - let height = available.height(); - let stacked = width < 900.0 && height > width; - if stacked { - 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(), available.bottom() - panel_height), - ); - let side_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| { - egui::CentralPanel::default().show(ui, |ui| self.board_ui(ui, settings)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(side_rect), |ui| { - ui.set_clip_rect(side_rect); - egui::Frame::side_top_panel(ui.style()).show(ui, |ui| self.side(ui, &mut actions)); - }); - } else { - let side = 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.side(ui, &mut actions)); - crate::widgets::check_panel("learning_training_side", &side.response); - egui::CentralPanel::default().show(ui, |ui| self.board_ui(ui, settings)); - } - actions.extend( - self.pending_sounds - .drain(..) - .map(LearningTrainingAction::Sound), - ); - if self.has_unsaved() && !self.discard_requested { - actions.retain(|action| !matches!(action, LearningTrainingAction::Back)); - } - if std::mem::take(&mut self.discard_requested) { - actions.push(LearningTrainingAction::Back); - } - actions - } - - pub fn debug_settle(&mut self) { - // Only this explicit QA hook waits. Normal frames poll workers without blocking. - let deadline = Instant::now() + Duration::from_secs(10); - loop { - if self.commit_in_flight.is_some() { - self.poll_commit(Instant::now()); - if Instant::now() >= deadline { - return; - } - if self.commit_in_flight.is_some() { - std::thread::sleep(Duration::from_millis(1)); - continue; - } - } - if self.has_unsaved() { - return; - } - if self.pending_automatic.is_some() { - self.board_shown = true; - } - let at = self - .playback_deadline() - .map_or_else(Instant::now, |at| at.max(Instant::now())); - self.tick_at(at, Duration::ZERO, now()); - if self.commit_in_flight.is_none() - && self.pending_automatic.is_none() - && !self.needs_prepare - && self.playback_deadline().is_none() - { - return; - } - if Instant::now() >= deadline { - return; - } - } - } - - pub fn debug_hint(&mut self) { - if self.needs_prepare { - self.debug_settle(); - } - let id = unique_id(self.session.id()); - self.request_hint_with_id_at(id, Instant::now(), now()); - } - - pub fn debug_moves(&mut self, moves: &str) { - if self.needs_prepare { - self.debug_settle(); - } - for text in moves.split_whitespace() { - match text { - "hint" => self.debug_hint(), - "settle" | "wait" => self.debug_settle(), - _ => { - let id = unique_id(self.session.id()); - self.play_uci_with_id_at(text, id, Instant::now(), now()); - } - } - } - } -} - -impl VisualMove { - fn from_context(step: &LearningContextStep) -> Result { - let before = parse_position(&step.from)?; - let mv = step - .uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&before).ok()) - .ok_or_else(|| format!("automatic context move {} is not legal", step.uci))?; - Ok(Self::new(step.uci.clone(), before, mv)) - } - - fn new(uci: String, before: Chess, mv: Move) -> Self { - let from = mv.from().unwrap_or_else(|| mv.to()); - let to = crate::board::ui_target(&mv); - let mut after = before.clone(); - after.play_unchecked(mv); - Self { - uci, - before, - after, - from, - to, - } - } -} - -fn parse_position(position: &trainer::repertoire::LearningPosition) -> Result { - position - .fen - .parse::() - .map_err(|error| error.to_string())? - .into_position(CastlingMode::Standard) - .map_err(|error| error.to_string()) -} - -fn main_task_progress(session: &LearningSessionSnapshot) -> (usize, usize) { - let total = session.queue.len(); - (total.saturating_sub(session.remaining()), total) -} - -pub fn queue_mode_label(mode: QueueMode) -> &'static str { - tr(match mode { - QueueMode::SpacedRepetition | QueueMode::Practice => "On schedule", - QueueMode::ReviewInOrder => "Review in order", - QueueMode::LeastRecent => "Least recent and unseen first", - }) -} - -fn compatible(session: &LearningSessionSnapshot, scope: &StatsScope, mode: QueueMode) -> bool { - let expected_side = match scope.side { - LearningSide::White => TrainingMode::White, - LearningSide::Black => TrainingMode::Black, - }; - session.session.mode == mode - && session.session.side == expected_side - && session.stats_scope.repertoire_ids == scope.repertoire_ids - && session.stats_scope.side == scope.side - && session.stats_scope.max_depth == scope.max_depth - && session.stats_scope.only_active == scope.only_active - && session.stats_scope.branch_root == scope.branch_root - && session.stats_scope.learning_priority == scope.learning_priority -} - -fn unique_id(prefix: &str) -> String { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |duration| duration.as_nanos()); - let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); - format!("{prefix}-{nanos:x}-{}-{sequence:x}", std::process::id()) -} - -fn now() -> i64 { - chrono::Local::now().timestamp() -} - -fn fixed_block(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui)) { - let width = ui.available_width().max(1.0); - let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); - let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect)); - child.set_clip_rect(rect); - add(&mut child); -} - -fn card(ui: &Ui, alert: bool) -> egui::Frame { - egui::Frame::new() - .inner_margin(egui::Margin::symmetric(10, 6)) - .corner_radius(4) - .stroke(egui::Stroke::new( - if alert { 1.5 } else { 1.0 }, - if alert { - ui.visuals().error_fg_color - } else { - ui.visuals().widgets.noninteractive.bg_stroke.color - }, - )) -} - -#[cfg(test)] -mod tests { - use std::path::PathBuf; - - use super::*; - use trainer::repertoire::{ - LearningItemKey, LearningPriority, LearningStoreData, active_learning_memberships, - }; - - #[test] - fn status_growth_does_not_move_training_controls() { - let mut positions = Vec::new(); - for message in [ - "Your turn", - "Hint\nReplay the shown move\nNo independent success", - ] { - let ctx = egui::Context::default(); - let output = ctx.run_ui(egui::RawInput::default(), |ui| { - egui::CentralPanel::default().show(ui, |ui| { - fixed_block(ui, 144.0, |ui| { - ui.label(message); - }); - positions.push(ui.button("Hint").rect.top()); - }); - }); - output.drop_without_applying_deltas(); - } - assert_eq!(positions[0], positions[1]); - assert!(positions[0] >= 144.0); - } - - const NOW: i64 = 1_800_000_000; - static NEXT_TEST: AtomicU64 = AtomicU64::new(1); - - struct TestDir(PathBuf); - - impl TestDir { - fn new(name: &str) -> Self { - let path = std::env::temp_dir().join(format!( - "cp-learning-training-{}-{}-{name}", - std::process::id(), - NEXT_TEST.fetch_add(1, Ordering::Relaxed) - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn store(&self) -> LearningStore { - LearningStore::new(self.0.join("learning.json")) - } - } - - impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - struct Fixture { - _dir: TestDir, - library: Library, - scope: StatsScope, - store: LearningStore, - ui: LearningTrainingUi, - } - - impl Fixture { - fn new(pgn: &str, side: LearningSide, due: &[&str], name: &str) -> Self { - Self::with_introduction(pgn, side, due, name, false) - } - - fn with_introduction( - pgn: &str, - side: LearningSide, - due: &[&str], - name: &str, - introduce_new: bool, - ) -> Self { - let dir = TestDir::new(name); - let mut library = Library::default(); - let id = library - .create("Test", &chess_core::parse_str(pgn).game) - .unwrap(); - let scope = StatsScope::for_repertoire(id, side, NOW); - let mut learning = LearningData::default(); - for expected in due { - let key = key_for(&library, &scope, expected); - let item = learning.ensure_item(key); - item.introduced = true; - item.next_review_at = Some(NOW); - } - let bytes = serde_json::to_vec_pretty(&LearningStoreData { - learning, - ..LearningStoreData::default() - }) - .unwrap(); - std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); - let store = dir.store(); - let mut ui = LearningTrainingUi::new( - library.clone(), - store.clone(), - scope.clone(), - SrsSettings::default(), - introduce_new, - false, - ) - .unwrap(); - ui.board_shown = true; - ui.synchronous_commits = true; - Self { - _dir: dir, - library, - scope, - store, - ui, - } - } - - fn with_mode( - pgn: &str, - side: LearningSide, - history: &[(&str, i64)], - name: &str, - mode: QueueMode, - priority: LearningPriority, - ) -> Self { - let dir = TestDir::new(name); - let mut library = Library::default(); - let id = library - .create("Test", &chess_core::parse_str(pgn).game) - .unwrap(); - let scope = StatsScope::for_repertoire(id, side, NOW).with_learning_priority(priority); - let mut learning = LearningData::default(); - for (expected, reviewed_at) in history { - let key = key_for(&library, &scope, expected); - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 1; - item.correct_count = 1; - item.last_review_at = Some(*reviewed_at); - item.last_correct_at = Some(*reviewed_at); - item.next_review_at = Some(NOW + 10 * 24 * 60 * 60); - item.previous_interval_seconds = Some(24 * 60 * 60); - } - let bytes = serde_json::to_vec_pretty(&LearningStoreData { - learning, - ..LearningStoreData::default() - }) - .unwrap(); - std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); - let store = dir.store(); - let mut ui = LearningTrainingUi::new_with_mode( - library.clone(), - store.clone(), - scope.clone(), - SrsSettings::default(), - false, - false, - mode, - ) - .unwrap(); - ui.board_shown = true; - ui.synchronous_commits = true; - Self { - _dir: dir, - library, - scope, - store, - ui, - } - } - - fn attempts(&self) -> Vec { - self.store.load().unwrap().learning.attempts - } - } - - fn key_for(library: &Library, scope: &StatsScope, expected: &str) -> LearningItemKey { - active_learning_memberships(library, scope) - .unwrap() - .into_iter() - .find(|membership| membership.key.expected_uci == expected) - .unwrap() - .key - } - - fn normal() -> Duration { - Duration::from_millis(250) - } - - fn answer_current(f: &mut Fixture, at: Instant, happened_at: i64, id: &str) { - let expected = f.ui.session.current_expected_uci().unwrap().to_owned(); - assert!(f.ui.play_uci_with_id_at(&expected, id.to_owned(), at, happened_at,)); - tick_with_prime(&mut f.ui, at, Duration::ZERO, happened_at); - } - - #[test] - fn new_session_saves_custom_policy_and_resume_keeps_persisted_policy() { - let f = Fixture::new( - "1. e4 *", - LearningSide::White, - &[], - "context-policy-persistence", - ); - assert_eq!( - f.ui.session.context_policy, - LearningContextPolicy::default() - ); - let policy = LearningContextPolicy { - reinforce_minimum_correct: 6, - reinforce_minimum_days: Some(21), - dont_show_start_moves_threshold: 9, - use_fixed_piece_speed: false, - move_speed_adjustment: 1.5, - consider_leadup_moves: true, - }; - let started = LearningTrainingUi::new_with_policy( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - true, - false, - QueueMode::SpacedRepetition, - policy, - ) - .unwrap(); - assert_eq!(started.session.context_policy, policy); - let read_store = || { - let bytes = std::fs::read(f.store.path()).unwrap(); - serde_json::from_slice::(&bytes).unwrap() - }; - assert_eq!( - read_store() - .session_snapshot(started.session_id()) - .unwrap() - .context_policy, - policy - ); - - let resumed = LearningTrainingUi::new_with_policy( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::SpacedRepetition, - LearningContextPolicy { - reinforce_minimum_correct: 99, - ..LearningContextPolicy::default() - }, - ) - .unwrap(); - assert_eq!(resumed.session_id(), started.session_id()); - assert_eq!(resumed.session.context_policy, policy); - assert_eq!( - read_store() - .session_snapshot(started.session_id()) - .unwrap() - .context_policy, - policy - ); - } - - fn board_frame(f: &mut Fixture, ctx: &egui::Context, time: f64, settings: &Settings) { - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(800.0, 800.0), - )), - time: Some(time), - ..Default::default() - }, - |ui| f.ui.board_ui(ui, settings), - ) - .drop_without_applying_deltas(); - } - - fn tick_with_prime( - ui: &mut LearningTrainingUi, - at: Instant, - animation: Duration, - happened_at: i64, - ) { - ui.tick_at(at, animation, happened_at); - if ui.pending_automatic.is_none() { - return; - } - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let settings = Settings::default(); - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(800.0, 800.0), - )), - time: Some(0.0), - ..Default::default() - }, - |root| ui.board_ui(root, &settings), - ) - .drop_without_applying_deltas(); - assert!(ui.board_shown); - assert!(ui.board.animation_at(0.0).is_none()); - ui.tick_at(at, animation, happened_at); - } - - fn automatic_duration(f: &Fixture) -> Duration { - match &f.ui.playback { - Some(Playback::Automatic { duration, .. }) => *duration, - _ => panic!("automatic playback expected"), - } - } - - fn assert_current_slide( - f: &Fixture, - time: f64, - expected_duration: Duration, - from: Square, - to: Square, - ) { - let (duration, slides, remaining) = - f.ui.board - .animation_at(time) - .expect("the current BoardView transition"); - assert_eq!(remaining, 1.0, "the first visual frame must be at from"); - assert!( - (duration - f64::from(expected_duration.as_secs_f32())).abs() < 1e-6, - "animation {duration} does not match scheduler {}", - expected_duration.as_secs_f32() - ); - assert!( - slides - .iter() - .any(|(_, slide_from, slide_to)| *slide_from == from && *slide_to == to), - "missing {from}{to} in {slides:?}" - ); - } - - fn assert_adaptive_board_slides(f: &mut Fixture, first_ms: u128, last_ms: u128) { - let ctx = egui::Context::default(); - let settings = Settings::default(); - let start = Instant::now(); - f.ui.board_shown = false; - f.ui.tick_at(start, normal(), NOW); - board_frame(f, &ctx, 0.0, &settings); - assert!(f.ui.board.animation_at(0.0).is_none()); - - f.ui.tick_at(start, normal(), NOW); - let first = automatic_duration(f); - assert_eq!(first.as_millis(), first_ms); - assert_eq!(f.ui.playback_deadline(), Some(start + first)); - assert_eq!(f.ui.session.context_index, 0); - board_frame(f, &ctx, 0.01, &settings); - assert_current_slide(f, 0.01, first, Square::E2, Square::E4); - assert!(f.ui.message.is_none()); - - tick_with_prime(&mut f.ui, start + first, normal(), NOW); - let last = automatic_duration(f); - assert_eq!(last.as_millis(), last_ms); - assert_eq!(f.ui.session.context_index, 1); - board_frame(f, &ctx, 0.02, &settings); - assert_current_slide(f, 0.02, last, Square::E7, Square::E5); - assert!(f.ui.message.is_none()); - - tick_with_prime(&mut f.ui, start + first + last, normal(), NOW); - assert_eq!(f.ui.session.context_index, 2); - assert!(f.ui.can_input()); - board_frame(f, &ctx, 10.0, &settings); - assert!( - f.ui.board.animation_at(10.0).is_none(), - "the final position must not start a settings-duration slide" - ); - assert_eq!(f.attempts().len(), 2); - } - - #[test] - fn adaptive_board_animation_matches_actual_slides_and_starts_at_from() { - let mut fast = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "adaptive-fast", - ); - let e4 = key_for(&fast.library, &fast.scope, "e2e4"); - fast.ui.learning.ensure_item(e4).correct_streak = 3; - fast.ui.session.context_policy.use_fixed_piece_speed = false; - fast.ui.session.context_policy.move_speed_adjustment = 1.5; - assert_adaptive_board_slides(&mut fast, 83, 166); - - let mut slow = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "adaptive-slow", - ); - slow.ui.session.context_policy.use_fixed_piece_speed = false; - slow.ui.session.context_policy.move_speed_adjustment = 0.0; - assert_adaptive_board_slides(&mut slow, 1000, 1000); - } - - #[test] - fn next_target_continues_the_shown_line_without_reverse_slide() { - fn settle_to_input(f: &mut Fixture, at: Instant) { - let mut at = at; - for _ in 0..32 { - if f.ui.can_input() { - return; - } - let next = f.ui.playback_deadline().unwrap_or(at); - tick_with_prime(&mut f.ui, next, normal(), NOW); - at = next; - } - panic!("training did not reach independent input"); - } - - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::Black, - &["e7e5", "b8c6", "a7a6"], - "next-target-prime", - ); - f.ui.session.context_policy.use_fixed_piece_speed = false; - f.ui.session.context_policy.move_speed_adjustment = 0.0; - let start = Instant::now(); - settle_to_input(&mut f, start); - assert_eq!(f.ui.session.current_expected_uci(), Some("e7e5")); - answer_current( - &mut f, - start + Duration::from_secs(1), - NOW, - "first-target-e5", - ); - - settle_to_input(&mut f, start + Duration::from_secs(1) + normal()); - assert_eq!(f.ui.session.current_expected_uci(), Some("b8c6")); - answer_current( - &mut f, - start + Duration::from_secs(3), - NOW + 1, - "second-target-nc6", - ); - - let prime_at = start + Duration::from_secs(3) + normal(); - // Every old move keeps its event, but a long visible prefix requires - // only one store transaction before the next opponent move. - let before_reuse = f.store.load().unwrap(); - for _ in 0..8 { - f.ui.tick_at(prime_at, normal(), NOW); - if f.ui.pending_automatic.is_some() { - break; - } - } - assert!(f.ui.pending_automatic.is_some()); - let after_reuse = f.store.load().unwrap(); - assert_eq!(after_reuse.revision, before_reuse.revision + 1); - let added = &after_reuse.learning.attempts[before_reuse.learning.attempts.len()..]; - assert_eq!(added.len(), 4); - assert!( - added - .iter() - .all(|event| event.event_type == TrainingEventType::AutoContext) - ); - assert_eq!(f.ui.session.context_index, 4); - assert!(!f.ui.board_shown); - let ctx = egui::Context::default(); - let settings = Settings::default(); - board_frame(&mut f, &ctx, 10.0, &settings); - assert!( - f.ui.board.animation_at(10.0).is_none(), - "prime must not animate the previous target backwards" - ); - - f.ui.tick_at(prime_at, normal(), NOW); - let duration = automatic_duration(&f); - assert_eq!(duration, Duration::from_millis(1000)); - board_frame(&mut f, &ctx, 10.01, &settings); - assert_current_slide(&f, 10.01, duration, Square::F1, Square::B5); - let (_, slides, _) = f.ui.board.animation_at(10.01).unwrap(); - assert!( - slides - .iter() - .all(|(_, from, to)| !(*from == Square::F3 && *to == Square::G1)), - "next target started with a reverse slide: {slides:?}" - ); - assert!(matches!( - f.ui.playback, - Some(Playback::Automatic { total: 1, .. }) - )); - } - - fn emitted_sounds(f: &mut Fixture, ctx: &egui::Context, settings: &Settings) -> Vec { - let mut sounds = Vec::new(); - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - vec2(960.0, 600.0), - )), - ..Default::default() - }, - |ui| { - sounds.extend( - f.ui.show(ui, settings, "Test") - .into_iter() - .filter_map(|action| { - if let LearningTrainingAction::Sound(sound) = action { - Some(sound) - } else { - None - } - }), - ); - }, - ) - .drop_without_applying_deltas(); - sounds - } - - #[test] - fn accepted_move_emits_once_and_next_task_only_animates_the_opponent_reply() { - for side in [LearningSide::White, LearningSide::Black] { - for animation in [ - crate::settings::Animation::Normal, - crate::settings::Animation::Off, - ] { - for replay in [false, true] { - let (due, reply, wrong) = match side { - LearningSide::White => (["e2e4", "g1f3"], "e7e5", "d2d4"), - LearningSide::Black => (["e7e5", "b8c6"], "g1f3", "d7d5"), - }; - let mut f = - Fixture::new("1. e4 e5 2. Nf3 Nc6 *", side, &due, "continuous-feedback"); - tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); - let ctx = egui::Context::default(); - let settings = Settings { - animation, - ..Settings::default() - }; - let at = Instant::now() + Duration::from_secs(60); - let duration = Duration::from_secs_f32(animation.seconds()); - f.ui.animation = duration; - f.ui.pending_sounds.clear(); - f.ui.visual_log.clear(); - if replay { - assert!(f.ui.play_uci_with_id_at( - wrong, - "wrong".into(), - at - WRONG_SHOWN, - NOW - )); - f.ui.tick_at(at, duration, NOW); - assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Wrong]); - } - assert!(f.ui.play_uci_with_id_at(due[0], "accepted".into(), at, NOW)); - let accepted_position = fen4(&f.ui.board_position); - assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); - for _ in 0..8 { - f.ui.tick_at(at + duration, duration, NOW); - assert_eq!( - fen4(&f.ui.board_position), - accepted_position, - "accepted move must not rewind" - ); - if f.ui.pending_automatic.is_some() { - break; - } - } - assert!(f.ui.pending_automatic.is_some()); - // The prime frame is silent; a separate later frame emits the - // opponent move, so queue coalescing cannot conceal a duplicate. - assert!(emitted_sounds(&mut f, &ctx, &settings).is_empty()); - assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); - assert_eq!(f.ui.visual_log, [reply]); - f.ui.debug_settle(); - assert_eq!(f.ui.session.current_expected_uci(), Some(due[1])); - let attempts = f.attempts(); - assert_eq!( - attempts - .iter() - .filter(|event| event.event_type.is_independent()) - .count(), - 1 - ); - assert!(attempts.iter().any(|event| event.expected_uci == due[0] - && event.event_type == TrainingEventType::AutoContext)); - assert_eq!( - attempts - .iter() - .filter(|event| event.event_type == TrainingEventType::ReplayAfterError) - .count(), - usize::from(replay) - ); - } - } - } - } - - #[test] - fn shown_context_requires_the_same_history_and_never_bypasses_a_question() { - let mut f = Fixture::new( - "1. Nf3 Nf6 2. g3 g6 3. Bg2 *", - LearningSide::White, - &["f1g2"], - "context-identity", - ); - let presentation = - f.ui.session - .presentation_with_learning(&f.library, &f.ui.learning) - .unwrap(); - f.ui.board_position = parse_position(&presentation.automatic_context[3].to).unwrap(); - let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); - // Even with an identical final position, a different move order must not - // reuse context. A matching FEN alone cannot establish repetition history. - f.ui.shown_prefix = Some(ShownPrefix { - repertoire_id: id.clone(), - path: vec!["g2g3".into(), "g7g6".into(), "g1f3".into(), "g8f6".into()], - }); - assert!(!f.ui.reuse_shown_context(&presentation, Instant::now())); - assert!(f.attempts().is_empty()); - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "context-question", - ); - let presentation = - f.ui.session - .presentation_with_learning(&f.library, &f.ui.learning) - .unwrap(); - f.ui.board_position = parse_position(&presentation.automatic_context[1].to).unwrap(); - f.ui.shown_prefix = Some(ShownPrefix { - repertoire_id: f.ui.session.current_target().unwrap().repertoire_id.clone(), - path: vec!["e2e4".into(), "e7e5".into()], - }); - f.ui.session.context_policy.consider_leadup_moves = true; - let question = - f.ui.session - .presentation_with_learning(&f.library, &f.ui.learning) - .unwrap(); - assert_eq!( - question.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert!(!f.ui.reuse_shown_context(&question, Instant::now())); - f.ui.prepare_presentation(Instant::now()); - assert!(f.ui.can_input()); - assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); - assert!(f.attempts().is_empty()); - } - - fn assert_annotation_badge(ui: &LearningTrainingUi, text: &str, square: Square) { - let annotation = ui.displayed_annotations(); - let badge = annotation.badge.expect("PGN move badge"); - assert_eq!(badge.text, text); - assert_eq!(badge.square, square); - } - - #[test] - fn pgn_annotations_follow_visible_user_and_automatic_moves_not_the_next_task() { - let mut f = Fixture::new( - "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} 2. Nf3! {[%csl Gf3]} Nc6 *", - LearningSide::White, - &["e2e4", "g1f3"], - "visible-pgn-annotations", - ); - let original = - f.ui.library - .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) - .unwrap() - .pgn - .clone(); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().arrows.is_empty()); - // A hint reveals the expected move, not that future node's annotations. - assert!(f.ui.request_hint_with_id_at("annotation-hint".into(), start, NOW)); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().arrows.is_empty()); - assert!(f.ui.play_uci_with_id_at("e2e4", "annotation-e4".into(), start, NOW)); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - assert_annotation_badge(&f.ui, "!!", Square::E4); - let annotation = f.ui.displayed_annotations(); - assert_eq!(annotation.arrows.len(), 2); - assert_eq!(annotation.circles.len(), 2); - assert!( - annotation - .arrows - .iter() - .any(|arrow| arrow.from == Square::E2 - && arrow.to == Square::E4 - && arrow.color == crate::game_view::shape_color(chess_core::ShapeColor::Red)) - ); - // Verify the helper's data actually reaches the rendered BoardView. - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let output = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &Settings::default()); - assert!(output.shapes.iter().any( - |shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "!!") - )); - output.drop_without_applying_deltas(); - f.ui.tick_at(start + normal(), normal(), NOW); - assert_annotation_badge(&f.ui, "!!", Square::E4); - assert!(f.ui.visual_log.is_empty(), "reused e4 must not play again"); - for _ in 0..8 { - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - if matches!(f.ui.playback, Some(Playback::Automatic { .. })) { - break; - } - } - assert_eq!(f.ui.visual_log, ["e7e5"]); - assert_annotation_badge(&f.ui, "?!", Square::E5); - assert_eq!(f.ui.displayed_annotations().arrows[0].from, Square::G1); - f.ui.tick_at(f.ui.playback_deadline().unwrap(), normal(), NOW); - assert!(f.ui.can_input()); - assert_annotation_badge(&f.ui, "?!", Square::E5); - assert!( - f.ui.displayed_annotations().circles.is_empty(), - "future Nf3 circle leaked before the answer" - ); - assert!(f.ui.play_uci_with_id_at( - "g1f3", - "annotation-nf3".into(), - start + Duration::from_secs(1), - NOW - )); - assert_annotation_badge(&f.ui, "!", Square::F3); - assert_eq!(f.ui.displayed_annotations().circles[0].0, Square::F3); - f.ui.debug_settle(); - assert_annotation_badge(&f.ui, "!", Square::F3); - assert_eq!( - f.ui.library - .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) - .unwrap() - .pgn, - original - ); - } - - #[test] - fn pgn_annotations_clear_for_wrong_moves_and_survive_failed_async_save_and_retry() { - let mut f = Fixture::new( - "1. e4!! {[%csl Ge4]} *", - LearningSide::White, - &["e2e4"], - "annotations-retry", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.play_uci_with_id_at("d2d4", "annotations-wrong".into(), start, NOW)); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().circles.is_empty()); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert!(f.ui.can_input()); - assert!(f.ui.displayed_annotations().badge.is_none()); - // Another wrong move during replay must not inherit the revealed e4 badge. - assert!(f.ui.play_uci_with_id_at( - "d2d4", - "annotations-wrong-replay".into(), - start + WRONG_SHOWN, - NOW - )); - assert!(f.ui.displayed_annotations().badge.is_none()); - f.ui.tick_at(start + WRONG_SHOWN * 2, normal(), NOW); - let store = f.ui.store.clone(); - f.ui.synchronous_commits = false; - f.ui.store = LearningStore::with_legacy(store.path(), store.path()); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "annotations-replay".into(), - start + WRONG_SHOWN * 2, - NOW - )); - assert!(f.ui.has_unsaved()); - assert_annotation_badge(&f.ui, "!!", Square::E4); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert_annotation_badge(&f.ui, "!!", Square::E4); - f.ui.store = store; - f.ui.retry_pending(Instant::now()); - wait_for_commit(&mut f.ui); - assert_annotation_badge(&f.ui, "!!", Square::E4); - assert_eq!( - f.attempts() - .iter() - .filter(|attempt| attempt.event_type.is_independent()) - .count(), - 1 - ); - assert_eq!( - f.attempts().last().unwrap().event_type, - TrainingEventType::ReplayAfterError - ); - } - - #[test] - fn alternative_answer_credits_actual_move_and_completed_answer_is_silent_and_neutral() { - let mut f = Fixture::new( - "1. e4! (1. d4!! {[%csl Gd4]}) *", - LearningSide::White, - &["e2e4", "d2d4"], - "alternative-answers", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - let original = f.ui.session.current_expected_uci().unwrap().to_owned(); - let (played, badge, square) = if original == "e2e4" { - ("d2d4", "!!", Square::D4) - } else { - ("e2e4", "!", Square::E4) - }; - let initial_position = f.ui.board_position.clone(); - assert_eq!( - f.ui.session - .pending_answers_for_position(&fen4(&initial_position)) - .len(), - 2 - ); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let output = ctx.run_ui(egui::RawInput::default(), |ui| f.ui.status_card(ui)); - assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, - egui::Shape::Text(text) if text.galley.text().contains("2")))); - output.drop_without_applying_deltas(); - assert!(f.ui.play_uci_with_id_at(played, "actual-alternative".into(), start, NOW)); - assert_annotation_badge(&f.ui, badge, square); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.attempts()[0].expected_uci, played); - assert_eq!( - f.attempts()[0].event_type, - TrainingEventType::CorrectIndependent - ); - assert_eq!(f.ui.session.current_expected_uci(), Some(original.as_str())); - assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); - f.ui.tick_at(start + normal(), normal(), NOW); - assert_eq!(f.ui.board_position, initial_position); - assert!(f.ui.play_uci_with_id_at( - played, - "repeat-alternative".into(), - start + normal(), - NOW - )); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert_annotation_badge(&f.ui, badge, square); - assert!(f.ui.message.as_deref().unwrap().contains(tr( - "This repertoire move has already been reviewed in this session." - ))); - assert!(f.ui.save_error.is_none() && f.ui.error.is_none()); - assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); - f.ui.tick_at(start + normal() + WRONG_SHOWN, normal(), NOW); - assert_eq!(f.ui.board_position, initial_position); - assert!(f.ui.can_input()); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.ui.session.remaining(), 1); - assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); - } - - #[test] - fn move_input_uses_the_startup_answer_snapshot_in_independent_and_replay_phases() { - let mut f = Fixture::new( - "1. e4 (1. d4) *", - LearningSide::White, - &["e2e4"], - "cached-repertoire-answers", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - let key = key_for(&f.library, &f.scope, "d2d4"); - assert!(f.ui.repertoire_answers.contains(&key)); - // The production library is immutable for the UI's lifetime. Change it - // only here to detect any accidental rebuilding in the input hot path. - let id = f.scope.repertoire_ids.iter().next().unwrap(); - f.ui.library - .repertoire_mut(id) - .unwrap() - .set_prefix_disabled(&["d2d4".to_owned()], true) - .unwrap(); - assert!( - !active_learning_keys(&f.ui.library, &f.scope) - .unwrap() - .contains(&key) - ); - assert!(f.ui.play_uci_with_id_at("d2d4", "cached-independent".into(), start, NOW)); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert!(f.attempts().is_empty()); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert!(f.ui.request_hint_with_id_at("cached-preview".into(), start + WRONG_SHOWN, NOW)); - assert!(f.ui.play_uci_with_id_at("d2d4", "cached-replay".into(), start + WRONG_SHOWN, NOW)); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.attempts()[0].event_type, TrainingEventType::Previewed); - assert!(f.ui.pending_sounds.is_empty()); - } - - #[test] - fn known_unscheduled_answer_during_hint_is_neutral_but_outside_move_still_wrong() { - let mut f = Fixture::new( - "1. e4! (1. d4!! {[%csl Gd4]}) *", - LearningSide::White, - &["e2e4"], - "hint-alternative", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.request_hint_with_id_at("preview-alternative".into(), start, NOW)); - let attempts = f.attempts().len(); - let snapshot = f.ui.session.clone(); - assert!(f.ui.play_uci_with_id_at("d2d4", "unscheduled-alternative".into(), start, NOW)); - assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); - assert_annotation_badge(&f.ui, "!!", Square::D4); - assert_eq!(f.ui.session, snapshot); - assert!(f.ui.pending_sounds.is_empty()); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert_eq!(f.attempts().len(), attempts); - assert!(f.ui.can_input()); - assert!(f.ui.message.as_deref().unwrap().contains(tr( - "This move is in your repertoire, but is not a task in this session." - ))); - assert!(f.ui.play_uci_with_id_at( - "g1f3", - "outside-repertoire".into(), - start + WRONG_SHOWN, - NOW - )); - assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); - assert_eq!(f.ui.pending_sounds, [Sound::Wrong]); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert_eq!(f.attempts().len(), attempts); - } - - #[test] - fn authored_wrong_branch_has_its_own_annotations_only_after_it_is_played() { - let mut f = Fixture::new( - "1. e4! (1. d4?? {[%csl Rd4]}) e5 *", - LearningSide::White, - &["e2e4"], - "wrong-branch-annotations", - ); - let start = Instant::now(); - f.ui.tick_at(start, normal(), NOW); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.play_uci_with_id_at("d2d4", "authored-wrong-branch".into(), start, NOW)); - assert_annotation_badge(&f.ui, "??", Square::D4); - assert_eq!( - f.ui.displayed_annotations().circles[0], - ( - Square::D4, - crate::game_view::shape_color(chess_core::ShapeColor::Red) - ) - ); - f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); - assert!(f.ui.displayed_annotations().badge.is_none()); - assert!(f.ui.displayed_annotations().circles.is_empty()); - } - - #[test] - fn pgn_annotation_cursor_distinguishes_transposed_paths_and_repertoire_sources() { - let mut f = Fixture::new( - "1. Nf3 (1. g3 g6 2. Nf3 Nf6? {[%csl Rf6]} 3. Bg2) Nf6 2. g3 g6! {[%csl Gg6]} 3. Bg2 *", - LearningSide::White, - &["f1g2"], - "annotations-transposition", - ); - let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); - let mut position_keys = Vec::new(); - for (path, badge, square) in [ - (["g1f3", "g8f6", "g2g3", "g7g6"], "!", Square::G6), - (["g2g3", "g7g6", "g1f3", "g8f6"], "?", Square::F6), - ] { - f.ui.set_displayed_path(Some(&ShownPrefix { - repertoire_id: id.clone(), - path: path.map(str::to_owned).to_vec(), - })); - let (_, node) = f.ui.displayed_node.as_ref().expect("exact PGN branch"); - f.ui.board_position = f.ui.annotation_games[&id].position(*node).unwrap().clone(); - position_keys.push(fen4(&f.ui.board_position)); - assert_annotation_badge(&f.ui, badge, square); - assert_eq!(f.ui.displayed_annotations().circles[0].0, square); - } - assert_eq!( - position_keys[0], position_keys[1], - "fixture must really transpose" - ); - let other_id = - f.ui.library - .create("Other annotations", &Game::new()) - .unwrap(); - f.ui.annotation_games.insert( - other_id.clone(), - chess_core::parse_str("1. Nf3 Nf6 2. g3 g6?? {[%csl Yg6]} *").game, - ); - f.ui.set_displayed_path(Some(&ShownPrefix { - repertoire_id: other_id.clone(), - path: ["g1f3", "g8f6", "g2g3", "g7g6"].map(str::to_owned).to_vec(), - })); - let (_, node) = f.ui.displayed_node.as_ref().unwrap(); - f.ui.board_position = f.ui.annotation_games[&other_id] - .position(*node) - .unwrap() - .clone(); - assert_annotation_badge(&f.ui, "??", Square::G6); - } - - #[test] - fn debug_moves_settles_prime_between_targets() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::Black, - &["e7e5", "b8c6", "a7a6"], - "debug-prime-between-targets", - ); - f.ui.debug_moves("e7e5 settle b8c6 settle"); - assert!(f.ui.can_input()); - assert_eq!(f.ui.session.current_expected_uci(), Some("a7a6")); - f.ui.debug_moves("a7a6 settle"); - assert!(f.ui.is_finished()); - assert_eq!( - f.attempts() - .iter() - .filter(|attempt| attempt.event_type.is_independent()) - .count(), - 3 - ); - } - - #[test] - fn reinforcement_does_not_count_as_completed_main_target() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["g1f3"], - "reinforcement-progress", - ); - f.ui.session.context_policy.consider_leadup_moves = true; - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - answer_current(&mut f, start, NOW, "weak-e4-reinforcement"); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - assert!(f.ui.session.completed_keys.contains(&e4)); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - assert_eq!(main_task_progress(&f.ui.session), (0, 1)); - - answer_current(&mut f, start, NOW + 1, "main-nf3-target"); - assert_eq!(main_task_progress(&f.ui.session), (1, 1)); - } - - #[test] - fn automatic_context_has_three_separate_normal_timed_steps() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "context-normal", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert_eq!(f.ui.visual_log, ["e2e4"]); - assert_eq!(f.ui.session.context_index, 0); - assert!(!f.ui.can_input()); - - tick_with_prime(&mut f.ui, start + Duration::from_millis(249), normal(), NOW); - assert_eq!(f.ui.session.context_index, 0); - assert!(f.attempts().is_empty()); - - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert_eq!(f.ui.session.context_index, 1); - - tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); - tick_with_prime(&mut f.ui, start + normal() * 3, normal(), NOW); - assert_eq!(f.ui.session.context_index, 3); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingIndependent - ); - assert!(f.ui.can_input()); - assert_eq!(f.attempts().len(), 3); - assert_eq!( - trainer::repertoire::fen4(&f.ui.board_position), - key_for(&f.library, &f.scope, "b8c6").position_fen4 - ); - } - - #[test] - fn pause_after_second_step_resumes_with_third_without_duplicate() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "pause-after-second", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - - assert!(f.ui.request_pause()); - assert!(f.ui.pause_requested); - assert!(matches!(f.ui.playback, Some(Playback::Automatic { .. }))); - assert_eq!(f.attempts().len(), 1); - tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); - assert!(f.ui.autoplay_paused()); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - assert_eq!(f.attempts().len(), 2); - assert!(!f.ui.can_input()); - - tick_with_prime(&mut f.ui, start + normal() * 10, normal(), NOW); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.attempts().len(), 2); - assert!(f.ui.continue_autoplay(start + normal() * 20)); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); - assert_eq!(f.ui.session.context_index, 2); - assert_eq!(f.attempts().len(), 2); - tick_with_prime(&mut f.ui, start + normal() * 20, normal(), NOW); - assert_eq!(f.attempts().len(), 2); - - tick_with_prime(&mut f.ui, start + normal() * 21, normal(), NOW); - assert_eq!(f.ui.session.context_index, 3); - assert_eq!(f.attempts().len(), 3); - assert!(f.ui.can_input()); - assert!(f.ui.playback.is_none()); - } - - #[test] - fn autoplay_keyboard_controls_stop_without_new_attempts() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "autoplay-keyboard-stop", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - let ctx = egui::Context::default(); - let press = |key: Key, - training: &mut LearningTrainingUi, - actions: &mut Vec| { - ctx.run_ui( - egui::RawInput { - events: vec![egui::Event::Key { - key, - physical_key: None, - pressed: true, - repeat: false, - modifiers: Modifiers::NONE, - }], - time: Some(0.0), - ..Default::default() - }, - |ui| training.keyboard(ui, actions), - ) - .drop_without_applying_deltas(); - }; - let mut actions = Vec::new(); - press(Key::P, &mut f.ui, &mut actions); - assert!(f.ui.pause_requested); - assert!(actions.is_empty()); - - tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); - assert!(f.ui.autoplay_paused()); - assert_eq!(f.attempts().len(), 1); - press(Key::Space, &mut f.ui, &mut actions); - assert!(matches!(f.ui.playback, Some(Playback::Automatic { .. }))); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.attempts().len(), 1); - - press(Key::Escape, &mut f.ui, &mut actions); - assert!(matches!(actions.as_slice(), [LearningTrainingAction::Back])); - assert!(f.ui.stopped); - assert!(f.ui.playback.is_none()); - assert!(!f.ui.can_input()); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); - tick_with_prime(&mut f.ui, start + normal() * 20, normal(), NOW); - assert_eq!(f.attempts().len(), 1); - let data = f.store.load().unwrap(); - assert_eq!(data.learning.attempts.len(), 1); - assert_eq!( - data.session_snapshot(f.ui.session_id()) - .unwrap() - .context_index, - 1 - ); - } - - #[test] - fn animation_off_commits_every_context_step_without_skipping_store_calls() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "context-off", - ); - tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); - assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); - assert_eq!(f.ui.session.context_index, 3); - assert!(f.ui.can_input()); - let attempts = f.attempts(); - assert_eq!(attempts.len(), 3); - assert_eq!( - attempts - .iter() - .map(|attempt| attempt.actual_uci.as_deref()) - .collect::>(), - [Some("e2e4"), Some("e7e5"), Some("g1f3")] - ); - assert!(attempts.iter().all(|attempt| { - attempt.event_type == TrainingEventType::AutoContext - && attempt.response_time_ms.is_none() - })); - } - - #[test] - fn legal_input_is_ignored_during_autoplay() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "autoplay-input", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(!f.ui.play_uci_with_id_at( - "e7e5", - "blocked-input".to_owned(), - start + Duration::from_millis(20), - NOW, - )); - assert_eq!(f.ui.session.context_index, 0); - assert!(f.attempts().is_empty()); - assert_eq!(f.ui.visual_log, ["e2e4"]); - } - - #[test] - fn wrong_answer_replays_without_a_second_independent_error() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "wrong-replay"); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(f.ui.play_uci_with_id_at( - "d2d4", - "wrong-d4".to_owned(), - start + Duration::from_millis(1500), - NOW, - )); - assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); - tick_with_prime( - &mut f.ui, - start + Duration::from_millis(1500) + WRONG_SHOWN, - normal(), - NOW, - ); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingReplayAfterError - ); - assert_eq!( - f.ui.presentation.as_ref().unwrap().revealed_move.as_deref(), - Some("e2e4") - ); - - assert!(f.ui.play_uci_with_id_at( - "d2d4", - "wrong-replay-d4".to_owned(), - start + Duration::from_secs(3), - NOW, - )); - assert_eq!(f.attempts().len(), 1); - tick_with_prime( - &mut f.ui, - start + Duration::from_secs(3) + WRONG_SHOWN, - normal(), - NOW, - ); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "replay-e4".to_owned(), - start + Duration::from_secs(4), - NOW, - )); - tick_with_prime( - &mut f.ui, - start + Duration::from_secs(4) + normal(), - normal(), - NOW, - ); - assert!(f.ui.is_finished()); - let attempts = f.attempts(); - assert_eq!(attempts.len(), 2); - assert_eq!( - attempts[0].event_type, - TrainingEventType::IncorrectIndependent - ); - assert_eq!(attempts[0].response_time_ms, Some(1500)); - assert_eq!(attempts[1].event_type, TrainingEventType::ReplayAfterError); - assert_eq!(attempts[1].response_time_ms, None); - let item = f - .store - .load() - .unwrap() - .learning - .item(&key_for(&f.library, &f.scope, "e2e4")) - .unwrap() - .clone(); - assert_eq!(item.wrong_count, 1); - assert_eq!(item.correct_count, 0); - } - - #[test] - fn preview_is_idempotent_and_shown_move_is_not_success() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "preview"); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(f.ui.request_hint_with_id_at( - "preview-e4".to_owned(), - start + Duration::from_millis(100), - NOW, - )); - assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); - assert!(!f.ui.request_hint_with_id_at( - "preview-e4-again".to_owned(), - start + Duration::from_millis(200), - NOW, - )); - assert_eq!(f.attempts().len(), 1); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "play-preview-e4".to_owned(), - start + Duration::from_secs(1), - NOW, - )); - tick_with_prime( - &mut f.ui, - start + Duration::from_secs(1) + normal(), - normal(), - NOW, - ); - assert!(f.ui.is_finished()); - assert!( - f.ui.message - .as_deref() - .is_some_and(|text| text.contains("PREVIEWED")) - ); - let data = f.store.load().unwrap(); - assert_eq!(data.learning.attempts.len(), 2); - assert_eq!( - data.learning.attempts[0].event_type, - TrainingEventType::Previewed - ); - assert_eq!( - data.learning.attempts[1].event_type, - TrainingEventType::AutoContext - ); - let item = data - .learning - .item(&key_for(&f.library, &f.scope, "e2e4")) - .unwrap(); - assert_eq!(item.correct_count, 0); - assert_eq!(item.wrong_count, 0); - assert!(item.independent_response_times_ms.is_empty()); - } - - #[test] - fn duplicate_store_response_does_not_advance_the_ui_twice() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "duplicate", - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - assert!(f.ui.advance_context_with_id_at( - "duplicate-context".to_owned(), - start + normal(), - NOW, - )); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.attempts().len(), 1); - - f.ui.completed_attempt_ids.remove("duplicate-context"); - assert!(f.ui.advance_context_with_id_at( - "duplicate-context".to_owned(), - start + normal() * 2, - NOW, - )); - assert_eq!(f.ui.session.context_index, 1); - assert_eq!(f.attempts().len(), 1); - assert!(!f.ui.visual_log.contains(&"g1f3".to_owned())); - } - - #[test] - fn store_error_is_visible_blocking_and_retryable() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "store-error"); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, normal(), NOW); - let valid_store = f.ui.store.clone(); - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - assert!(f.ui.play_uci_with_id_at( - "e2e4", - "save-error-e4".to_owned(), - start + Duration::from_millis(100), - NOW, - )); - assert!(f.ui.has_unsaved()); - assert!(f.ui.save_error.is_some()); - assert!(!f.ui.can_input()); - assert!(!f.ui.is_finished()); - assert!(f.attempts().is_empty()); - assert!(!f.ui.play_uci_with_id_at( - "d2d4", - "blocked-after-save-error".to_owned(), - start + Duration::from_millis(200), - NOW, - )); - - f.ui.store = valid_store; - f.ui.retry_pending(start + Duration::from_millis(300)); - assert!(!f.ui.has_unsaved()); - assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); - tick_with_prime( - &mut f.ui, - start + Duration::from_millis(300) + normal(), - normal(), - NOW, - ); - assert!(f.ui.is_finished()); - assert_eq!(f.attempts().len(), 1); - } - - #[test] - fn reload_resumes_preview_and_partially_presented_context() { - let mut preview = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "resume-preview"); - let start = Instant::now(); - tick_with_prime(&mut preview.ui, start, normal(), NOW); - preview - .ui - .request_hint_with_id_at("resume-preview-event".to_owned(), start, NOW); - let id = preview.ui.session_id().to_owned(); - let resumed = LearningTrainingUi::new( - preview.library.clone(), - preview.store.clone(), - preview.scope.clone(), - SrsSettings::default(), - false, - false, - ) - .unwrap(); - assert_eq!(resumed.session_id(), id); - assert_eq!(resumed.session.phase, LearningSessionPhase::PreviewedReplay); - assert_eq!(preview.store.load().unwrap().learning.attempts.len(), 1); - - let mut context = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - &["b8c6"], - "resume-context", - ); - tick_with_prime(&mut context.ui, start, normal(), NOW); - tick_with_prime(&mut context.ui, start + normal(), normal(), NOW); - assert_eq!(context.ui.session.context_index, 1); - let id = context.ui.session_id().to_owned(); - drop(context.ui); - let mut resumed = LearningTrainingUi::new( - context.library.clone(), - context.store.clone(), - context.scope.clone(), - SrsSettings::default(), - false, - false, - ) - .unwrap(); - assert_eq!(resumed.session_id(), id); - assert_eq!(resumed.session.context_index, 1); - resumed.synchronous_commits = true; - tick_with_prime(&mut resumed, start + normal() * 2, Duration::ZERO, NOW); - assert_eq!(resumed.session.context_index, 3); - assert_eq!(context.store.load().unwrap().learning.attempts.len(), 3); - } - - #[test] - fn new_items_require_the_explicit_introduction_flag() { - let due = Fixture::new("1. e4 *", LearningSide::White, &[], "due-empty"); - assert!(due.ui.session.queue.is_empty()); - assert!(due.ui.is_finished()); - assert!(due.store.load().unwrap().learning.items.is_empty()); - - let introduced = Fixture::with_introduction( - "1. e4 *", - LearningSide::White, - &[], - "introduce-explicit", - true, - ); - assert_eq!(introduced.ui.session.queue.len(), 1); - assert!(introduced.store.load().unwrap().learning.items.is_empty()); - } - - #[test] - fn introduce_new_starts_separate_session_and_preserves_previewed_snapshot() { - let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 *"; - let mut f = Fixture::with_introduction( - pgn, - LearningSide::White, - &[], - "introduce-preserves-preview", - true, - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - assert!(f.ui.request_hint_with_id_at( - "preview-before-new-introduction".to_owned(), - start, - NOW, - )); - let old_id = f.ui.session_id().to_owned(); - - let introduced = LearningTrainingUi::new( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - true, - false, - ) - .unwrap(); - - assert_ne!(introduced.session_id(), old_id); - assert_eq!(introduced.session.queue.len(), 6); - assert!( - introduced - .session - .queue - .iter() - .all(|target| target.key.expected_uci != "e2e4") - ); - let data = f.store.load().unwrap(); - assert_eq!(data.session_snapshots.len(), 2); - let old = data.session_snapshot(&old_id).unwrap(); - assert_eq!(old.phase, LearningSessionPhase::PreviewedReplay); - assert_eq!(old.queue.len(), 7); - assert!(data.session_snapshot(introduced.session_id()).is_some()); - } - - #[test] - fn review_in_order_second_cycle_restarts_progress_and_updates_srs() { - let mut f = Fixture::with_mode( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &[], - "review-second-cycle", - QueueMode::ReviewInOrder, - LearningPriority::DepthFirst, - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - answer_current( - &mut f, - start + Duration::from_millis(10), - NOW, - "review-cycle0-e4", - ); - assert_eq!(f.ui.session.cycle, 0); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - answer_current( - &mut f, - start + Duration::from_millis(20), - NOW + 1, - "review-cycle0-nf3", - ); - assert_eq!(f.ui.session.cycle, 1); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "e2e4" - ); - assert!(f.ui.session.completed_keys.is_empty()); - assert!(!f.ui.is_finished()); - - answer_current( - &mut f, - start + Duration::from_millis(30), - NOW + 24 * 60 * 60, - "review-cycle1-e4", - ); - assert_eq!(f.ui.session.cycle, 1); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - assert_eq!(f.ui.session.completed_keys.len(), 1); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - let item = f.store.load().unwrap().learning.item(&e4).unwrap().clone(); - assert_eq!(item.correct_count, 2); - assert!(item.next_review_at > Some(NOW + 24 * 60 * 60)); - } - - #[test] - fn least_recent_context_is_independent_once_and_new_pass_resumes() { - let mut f = Fixture::with_mode( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::White, - &[("e2e4", NOW - 10), ("g1f3", NOW - 100), ("f1b5", NOW - 50)], - "least-context-once", - QueueMode::LeastRecent, - LearningPriority::DepthFirst, - ); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "g1f3" - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - assert!(f.ui.can_input()); - assert!(f.ui.playback.is_none()); - assert!(f.ui.visual_log.is_empty()); - assert!( - f.ui.message - .as_deref() - .unwrap() - .contains(tr("Automatic move/context")) - ); - - answer_current( - &mut f, - start + Duration::from_millis(10), - NOW, - "least-context-e4", - ); - assert_eq!( - f.ui.session.phase, - LearningSessionPhase::AwaitingIndependent - ); - assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); - answer_current( - &mut f, - start + Duration::from_millis(20), - NOW + 1, - "least-target-nf3", - ); - assert_eq!( - f.ui.session.current_target().unwrap().key.expected_uci, - "f1b5" - ); - for expected in ["e2e4", "g1f3"] { - let key = key_for(&f.library, &f.scope, expected); - assert_eq!( - f.attempts() - .iter() - .filter(|attempt| { - attempt.item_key() == key && attempt.event_type.is_independent() - }) - .count(), - 1, - "context was checked twice for {expected}" - ); - } - answer_current( - &mut f, - start + Duration::from_millis(30), - NOW + 2, - "least-target-bb5", - ); - assert!(f.ui.is_finished()); - let attempts = f.attempts(); - for expected in ["e2e4", "g1f3", "f1b5"] { - let key = key_for(&f.library, &f.scope, expected); - assert_eq!( - attempts - .iter() - .filter(|attempt| { - attempt.item_key() == key && attempt.event_type.is_independent() - }) - .count(), - 1, - "duplicate independent review for {expected}" - ); - let item = f.store.load().unwrap().learning.item(&key).unwrap().clone(); - assert_eq!(item.correct_count, 2); - } - - let id = f.ui.session_id().to_owned(); - drop(f.ui); - let resumed = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::LeastRecent, - ) - .unwrap(); - assert_eq!(resumed.session_id(), id); - assert_eq!(resumed.session.cycle, 1); - assert_eq!(resumed.session.session.mode, QueueMode::LeastRecent); - assert!(resumed.target_available()); - } - - #[test] - fn resume_is_scoped_by_mode_and_learning_priority() { - let mut f = Fixture::with_mode( - "1. e4 (1. d4 d5) e5 2. Nf3 *", - LearningSide::White, - &[], - "resume-mode-priority", - QueueMode::ReviewInOrder, - LearningPriority::MainLinesFirst, - ); - let start = Instant::now(); - tick_with_prime(&mut f.ui, start, Duration::ZERO, NOW); - answer_current(&mut f, start, NOW, "priority-review-first"); - let review_id = f.ui.session_id().to_owned(); - assert_eq!(f.ui.session.current_index, 1); - - let resumed = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::ReviewInOrder, - ) - .unwrap(); - assert_eq!(resumed.session_id(), review_id); - assert_eq!(resumed.session.current_index, 1); - assert_eq!( - resumed.session.stats_scope.learning_priority, - LearningPriority::MainLinesFirst - ); - - let other_priority = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope - .clone() - .with_learning_priority(LearningPriority::DepthFirst), - SrsSettings::default(), - false, - false, - QueueMode::ReviewInOrder, - ) - .unwrap(); - assert_ne!(other_priority.session_id(), review_id); - assert_eq!( - other_priority.session.stats_scope.learning_priority, - LearningPriority::DepthFirst - ); - - let other_mode = LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - QueueMode::LeastRecent, - ) - .unwrap(); - assert_ne!(other_mode.session_id(), review_id); - assert_eq!(other_mode.session.session.mode, QueueMode::LeastRecent); - - let srs = LearningTrainingUi::new( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - false, - false, - ) - .unwrap(); - assert_ne!(srs.session_id(), review_id); - assert_eq!(srs.session.session.mode, QueueMode::SpacedRepetition); - assert!( - LearningTrainingUi::new_with_mode( - f.library.clone(), - f.store.clone(), - f.scope.clone(), - SrsSettings::default(), - true, - false, - QueueMode::ReviewInOrder, - ) - .is_err() - ); - assert_eq!( - queue_mode_label(QueueMode::SpacedRepetition), - tr("On schedule") - ); - assert_eq!( - queue_mode_label(QueueMode::ReviewInOrder), - tr("Review in order") - ); - assert_eq!( - queue_mode_label(QueueMode::LeastRecent), - tr("Least recent and unseen first") - ); - } - - #[test] - fn show_runs_at_mvp_window_sizes() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "mvp-sizes"); - let settings = Settings::default(); - let ctx = egui::Context::default(); - ctx.set_visuals(egui::Visuals::light()); - for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] { - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(0.0), - ..Default::default() - }, - |ui| { - f.ui.show(ui, &settings, "Test repertoire"); - }, - ); - if width == 640.0 { - let background = egui::Visuals::light().window_fill(); - assert!( - output.shapes.iter().any(|clipped| { - let egui::Shape::Rect(shape) = &clipped.shape else { - return false; - }; - shape.fill == background - && shape.rect.min.x <= 0.0 - && shape.rect.max.x >= width - && shape.rect.min.y > 0.0 - && shape.rect.min.y <= height - 58.0 - && shape.rect.max.y >= height - 0.01 - }), - "the stacked background must cover the bottom of the viewport" - ); - } - output.drop_without_applying_deltas(); - } - assert!(f.ui.target_available()); - assert!(!f.ui.has_unsaved()); - } - fn wait_for_commit(ui: &mut LearningTrainingUi) { - let deadline = Instant::now() + Duration::from_secs(5); - while ui.commit_in_flight.is_some() { - assert!(Instant::now() < deadline, "commit worker did not finish"); - ui.poll_commit(Instant::now()); - std::thread::sleep(Duration::from_millis(1)); - } - } - - #[test] - fn async_commit_keeps_frames_responsive_under_store_lock_and_commits_once() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-lock"); - f.ui.synchronous_commits = false; - tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); - let lock_path = f.store.path().with_file_name("learning.json.lock"); - let lock = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(lock_path) - .unwrap(); - lock.lock().unwrap(); - let unlock = std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(600)); - drop(lock); - }); - let start = Instant::now(); - assert!(f.ui.play_uci_with_id_at("e2e4", "async-answer".to_owned(), start, NOW)); - assert!( - start.elapsed() < Duration::from_millis(300), - "input waited for storage lock" - ); - assert!(f.ui.has_unsaved()); - assert!(f.ui.commit_in_flight.is_some()); - assert!(!f.ui.can_input()); - assert!( - !f.ui - .play_uci_with_id_at("e2e4", "async-answer".to_owned(), Instant::now(), NOW) - ); - f.ui.retry_pending(Instant::now()); - let ctx = egui::Context::default(); - let frame = Instant::now(); - ctx.run_ui(egui::RawInput::default(), |ui| { - f.ui.show(ui, &Settings::default(), "Test"); - }) - .drop_without_applying_deltas(); - assert!( - frame.elapsed() < Duration::from_millis(300), - "frame waited for storage lock" - ); - unlock.join().unwrap(); - wait_for_commit(&mut f.ui); - assert!(!f.ui.has_unsaved()); - assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); - assert_eq!(f.attempts().len(), 1); - let revision = f.ui.session.revision; - f.ui.poll_commit(Instant::now()); - f.ui.retry_pending(Instant::now()); - assert_eq!(f.ui.session.revision, revision); - assert_eq!(f.attempts().len(), 1); - } - - fn pointer_board_frame( - f: &mut Fixture, - ctx: &egui::Context, - time: f64, - events: Vec, - settings: &Settings, - ) -> egui::FullOutput { - let mut output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - vec2(800.0, 800.0), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| f.ui.board_ui(ui, settings), - ); - output.textures_delta.clear(); - output - } - - fn piece_meshes(output: &egui::FullOutput) -> Vec<(egui::TextureId, egui::Rect)> { - fn collect(shape: &egui::Shape, meshes: &mut Vec<(egui::TextureId, egui::Rect)>) { - match shape { - egui::Shape::Mesh(mesh) => meshes.push((mesh.texture_id, mesh.calc_bounds())), - egui::Shape::Rect(rect) => { - if let Some(brush) = &rect.brush { - meshes.push((brush.fill_texture_id, rect.rect)); - } - } - egui::Shape::Vec(shapes) => { - for shape in shapes { - collect(shape, meshes); - } - } - _ => {} - } - } - let mut meshes = Vec::new(); - for shape in &output.shapes { - collect(&shape.shape, &mut meshes); - } - meshes - } - - fn pointer_button(pos: egui::Pos2, pressed: bool) -> egui::Event { - egui::Event::PointerButton { - pos, - button: egui::PointerButton::Primary, - pressed, - modifiers: Modifiers::NONE, - } - } - - #[test] - fn pointer_move_stays_at_destination_during_async_save_without_a_second_animation() { - for drag in [true, false] { - for wrong in [false, true] { - for animation in [ - crate::settings::Animation::Normal, - crate::settings::Animation::Off, - ] { - let mut f = - Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "pointer-pending"); - f.ui.synchronous_commits = false; - let settings = Settings { - animation, - ..Settings::default() - }; - let duration = Duration::from_secs_f32(animation.seconds()); - f.ui.tick_at(Instant::now(), duration, NOW); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let from = egui::pos2(450.0, 650.0); - let to = egui::pos2(450.0, if wrong { 550.0 } else { 450.0 }); - let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); - let pawn = piece_meshes(&initial) - .into_iter() - .find(|(_, rect)| rect.contains(from)) - .expect("painted pawn at e2") - .0; - initial.drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.01, - vec![egui::Event::PointerMoved(from), pointer_button(from, true)], - &settings, - ) - .drop_without_applying_deltas(); - if drag { - pointer_board_frame( - &mut f, - &ctx, - 1.02, - vec![egui::Event::PointerMoved(to)], - &settings, - ) - .drop_without_applying_deltas(); - } else { - pointer_board_frame( - &mut f, - &ctx, - 1.02, - vec![pointer_button(from, false)], - &settings, - ) - .drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.03, - vec![egui::Event::PointerMoved(to), pointer_button(to, true)], - &settings, - ) - .drop_without_applying_deltas(); - } - let lock = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(f.store.path().with_file_name("learning.json.lock")) - .unwrap(); - lock.lock().unwrap(); - let released = pointer_board_frame( - &mut f, - &ctx, - 1.04, - vec![pointer_button(to, false)], - &settings, - ); - let assert_pawn_at_destination = |output: &egui::FullOutput| { - let meshes = piece_meshes(output); - assert!( - meshes - .iter() - .any(|(texture, rect)| *texture == pawn && rect.contains(to)), - "pawn not painted at destination" - ); - assert!( - !meshes - .iter() - .any(|(texture, rect)| *texture == pawn && rect.contains(from)), - "pawn snapped back to e2" - ); - }; - assert!(f.ui.has_unsaved(), "drag={drag} wrong={wrong}"); - assert!(!f.ui.can_input()); - assert!(f.ui.pending_sounds.is_empty()); - if drag { - assert_pawn_at_destination(&released); - } - released.drop_without_applying_deltas(); - let frame = Instant::now(); - let waiting = pointer_board_frame(&mut f, &ctx, 1.05, vec![], &settings); - assert!(frame.elapsed() < Duration::from_millis(300)); - if drag { - assert_pawn_at_destination(&waiting); - assert!( - f.ui.board - .animation_at(1.05) - .is_none_or(|(_, slides, _)| slides.is_empty()) - ); - } else if !duration.is_zero() { - assert!( - f.ui.board - .animation_at(1.05) - .unwrap() - .1 - .iter() - .any(|(_, source, _)| *source == Square::E2), - "click move must still animate" - ); - } - waiting.drop_without_applying_deltas(); - let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); - assert_pawn_at_destination(&waiting); - waiting.drop_without_applying_deltas(); - assert!( - f.ui.learning.attempts.is_empty(), - "unconfirmed answer affected learning data" - ); - drop(lock); - wait_for_commit(&mut f.ui); - let confirmed = pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings); - assert_pawn_at_destination(&confirmed); - confirmed.drop_without_applying_deltas(); - assert!( - f.ui.board.animation_at(2.01).is_none(), - "commit restarted the move animation" - ); - assert_eq!(f.attempts().len(), 1); - assert_eq!( - f.ui.pending_sounds, - [if wrong { Sound::Wrong } else { Sound::Move }] - ); - if wrong { - f.ui.tick_at(f.ui.playback_deadline().unwrap(), duration, NOW); - pointer_board_frame(&mut f, &ctx, 2.02, vec![], &settings) - .drop_without_applying_deltas(); - assert_eq!(fen4(&f.ui.board_position), fen4(&Chess::default())); - if !duration.is_zero() { - assert!( - f.ui.board - .animation_at(2.02) - .unwrap() - .1 - .iter() - .any(|(_, _, target)| *target == Square::E2), - "wrong move must return to source" - ); - } - } - } - } - } - } - - #[test] - fn dragged_special_moves_keep_auxiliary_effects_and_retry_does_not_move_again() { - let cases = [ - ( - "4k3/8/8/8/8/8/8/4K2R w K - 0 1", - "O-O", - "e1g1", - Square::E1, - Square::G1, - None, - false, - ), - ( - "4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1", - "exd5", - "e4d5", - Square::E4, - Square::D5, - Some(Square::D5), - false, - ), - ( - "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", - "exd6", - "e5d6", - Square::E5, - Square::D6, - Some(Square::D5), - false, - ), - ( - "4k3/P7/8/8/8/8/8/4K3 w - - 0 1", - "a8=Q+", - "a7a8q", - Square::A7, - Square::A8, - None, - true, - ), - ]; - let center = |sq: Square| { - egui::pos2( - (u32::from(sq.file()) as f32 + 0.5) * 100.0, - (7.5 - u32::from(sq.rank()) as f32) * 100.0, - ) - }; - for (fen, san, uci, from, to, captured, promotion) in cases { - let pgn = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"); - let mut f = Fixture::new(&pgn, LearningSide::White, &[uci], "special-drag"); - f.ui.synchronous_commits = false; - f.ui.tick_at(Instant::now(), normal(), NOW); - let valid_store = f.ui.store.clone(); - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let settings = Settings::default(); - let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); - let captured_texture = captured.map(|sq| { - piece_meshes(&initial) - .into_iter() - .find(|(_, rect)| rect.contains(center(sq))) - .unwrap() - .0 - }); - initial.drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.01, - vec![ - egui::Event::PointerMoved(center(from)), - pointer_button(center(from), true), - ], - &settings, - ) - .drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.02, - vec![egui::Event::PointerMoved(center(to))], - &settings, - ) - .drop_without_applying_deltas(); - let released = pointer_board_frame( - &mut f, - &ctx, - 1.03, - vec![pointer_button(center(to), false)], - &settings, - ); - if uci == "e1g1" { - let (_, slides, _) = f.ui.board.animation_at(1.03).unwrap(); - assert_eq!(slides.len(), 1); - assert_eq!( - (slides[0].1, slides[0].2), - (Square::H1, Square::F1), - "only the rook should animate after a dragged castle" - ); - } - if let Some(texture) = captured_texture { - assert!( - piece_meshes(&released).iter().any( - |(id, rect)| *id == texture && rect.contains(center(captured.unwrap())) - ), - "captured piece must still fade out" - ); - } - released.drop_without_applying_deltas(); - if promotion { - assert!( - !f.ui.has_unsaved(), - "promotion must wait for the chosen piece" - ); - pointer_board_frame( - &mut f, - &ctx, - 1.04, - vec![pointer_button(center(to), true)], - &settings, - ) - .drop_without_applying_deltas(); - pointer_board_frame( - &mut f, - &ctx, - 1.05, - vec![pointer_button(center(to), false)], - &settings, - ) - .drop_without_applying_deltas(); - assert_eq!( - f.ui.board_position.board().piece_at(to).unwrap().role, - chess_core::shakmaty::Role::Queen - ); - } - assert!(f.ui.has_unsaved()); - let after = fen4(&f.ui.board_position); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert!(f.attempts().is_empty()); - assert!(f.ui.pending_sounds.is_empty()); - pointer_board_frame(&mut f, &ctx, 1.1, vec![], &settings) - .drop_without_applying_deltas(); - let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); - if let Some(texture) = captured_texture { - assert!( - !piece_meshes(&waiting).iter().any( - |(id, rect)| *id == texture && rect.contains(center(captured.unwrap())) - ) - ); - } - waiting.drop_without_applying_deltas(); - f.ui.store = valid_store; - f.ui.retry_pending(Instant::now()); - f.ui.retry_pending(Instant::now()); - wait_for_commit(&mut f.ui); - pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings) - .drop_without_applying_deltas(); - assert_eq!(fen4(&f.ui.board_position), after); - assert!(f.ui.board.animation_at(2.01).is_none()); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.ui.pending_sounds, [Sound::Move]); - } - } - - #[test] - fn reused_context_retry_stays_silent_and_responsive_and_persists_once() { - let mut f = Fixture::new( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - &["e2e4", "g1f3"], - "reuse-retry", - ); - let at = Instant::now(); - tick_with_prime(&mut f.ui, at, normal(), NOW); - assert!(f.ui.play_uci_with_id_at("e2e4", "own-answer".into(), at, NOW)); - let position = fen4(&f.ui.board_position); - assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); - let valid_store = f.ui.store.clone(); - f.ui.synchronous_commits = false; - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - f.ui.tick_at(at + normal(), normal(), NOW); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert!(matches!( - f.ui.pending_commit.as_ref().unwrap().kind, - CommitKind::ReusedContext - )); - let reused_id = f.ui.pending_commit.as_ref().unwrap().attempts[0] - .client_attempt_id - .clone(); - assert_eq!(fen4(&f.ui.board_position), position); - assert!(f.ui.pending_sounds.is_empty()); - f.ui.store = valid_store; - let lock = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(f.store.path().with_file_name("learning.json.lock")) - .unwrap(); - lock.lock().unwrap(); - let unlock = std::thread::spawn(move || { - std::thread::sleep(Duration::from_millis(600)); - drop(lock); - }); - f.ui.retry_pending(Instant::now()); - f.ui.retry_pending(Instant::now()); - let frame = Instant::now(); - assert!(emitted_sounds(&mut f, &egui::Context::default(), &Settings::default()).is_empty()); - assert!( - frame.elapsed() < Duration::from_millis(300), - "reused context blocked the frame" - ); - assert_eq!(fen4(&f.ui.board_position), position); - assert!(!f.ui.can_input()); - unlock.join().unwrap(); - wait_for_commit(&mut f.ui); - assert!(f.ui.pending_sounds.is_empty()); - f.ui.debug_settle(); - assert_eq!(f.ui.visual_log, ["e7e5"]); - assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); - let attempts = f.attempts(); - assert_eq!(attempts.len(), 3); - assert_eq!( - attempts - .iter() - .filter(|event| event.client_attempt_id == reused_id) - .count(), - 1 - ); - assert_eq!( - attempts - .iter() - .filter(|event| event.event_type.is_independent()) - .count(), - 1 - ); - } - - #[test] - fn async_failed_commit_preserves_event_for_retry_without_double_counting() { - let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-retry"); - f.ui.synchronous_commits = false; - tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); - let valid_store = f.ui.store.clone(); - f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); - assert!(f.ui.play_uci_with_id_at("e2e4", "async-retry".to_owned(), Instant::now(), NOW)); - wait_for_commit(&mut f.ui); - assert!(f.ui.save_error.is_some()); - assert!(f.ui.has_unsaved()); - assert!(f.attempts().is_empty()); - f.ui.store = valid_store; - f.ui.retry_pending(Instant::now()); - f.ui.retry_pending(Instant::now()); - wait_for_commit(&mut f.ui); - assert!(!f.ui.has_unsaved()); - assert_eq!(f.attempts().len(), 1); - assert_eq!(f.attempts()[0].client_attempt_id, "async-retry"); - } -} diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs index fbb7b73..0581eb2 100644 --- a/apps/desktop/src/lib.rs +++ b/apps/desktop/src/lib.rs @@ -30,16 +30,6 @@ mod game_view; mod graphics; mod i18n; mod large_db; -#[cfg(not(web))] -mod learning_branches; -#[cfg(not(web))] -mod learning_charts; -#[cfg(not(web))] -mod learning_context_controls; -#[cfg(not(web))] -mod learning_dashboard; -#[cfg(not(web))] -mod learning_training; mod library; mod maia_download; #[cfg(web)] @@ -48,6 +38,12 @@ mod notation; mod online; #[cfg(not(web))] mod online_ui; +#[cfg(not(web))] +mod opening_layout; +#[cfg(not(web))] +mod opening_lines; +#[cfg(not(web))] +mod opening_session; mod own_db; pub mod platform; mod play; @@ -56,10 +52,6 @@ mod prep_saved; mod prep_ui; mod reference; #[cfg(not(web))] -mod repertoire_editor; -#[cfg(not(web))] -mod repertoire_training; -#[cfg(not(web))] mod repertoire_ui; mod review; mod review_engine; diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs new file mode 100644 index 0000000..61df871 --- /dev/null +++ b/apps/desktop/src/opening_layout.rs @@ -0,0 +1,498 @@ +//! What the three opening-training screens share (docs/design/opening-trainer-v2-spec.md +//! §1): the frame of the game screen, the card, the board's PGN marks and the texts +//! about moves, sides and dates. + +use chess_core::shakmaty::{Color, Square, uci::UciMove}; +use chess_core::{Annotation, CommentPart, Game, MoveKind, NodeId, parse_comment}; +use egui::{Color32, RichText, Ui, vec2}; +use trainer::repertoire::{LearningSide, RepertoireId, TrainingMode}; + +use crate::board::{Arrow, Badge}; +use crate::i18n::{tr, trf}; +use crate::settings::Settings; + +/// The panel's least width (the game's reference tab, `REF_MIN`). +const SIDE_LEAST: f32 = 320.0; +/// Under a stacked board: the panel's least height (`STACK_BOTTOM_MIN`). +const STACK_BOTTOM_MIN: f32 = 300.0; +const BOARD_MIN: f32 = 220.0; +/// Space between the blocks of the panel. +pub(crate) const GAP: f32 = 6.0; +/// The new moves of one session and of "10 more new". +pub(crate) const NEW_PER_SESSION: usize = 10; + +/// Header, side panel and board in the places of the game screen. The same panel id on +/// every screen of the section: switching screens never moves the board. +pub(crate) fn screen( + ui: &mut Ui, + this: &mut T, + header: impl FnOnce(&mut T, &mut Ui), + side: impl FnOnce(&mut T, &mut Ui), + board: impl FnOnce(&mut T, &mut Ui), +) { + egui::Panel::top("opening_header").show(ui, |ui| header(this, ui)); + let width = ui.available_width(); + let height = ui.available_height(); + let board_side = (height - 16.0).min(width - SIDE_LEAST - 24.0); + let board_stack = (width - 16.0).min(height - STACK_BOTTOM_MIN - 16.0); + let stacked = board_stack >= 1.25 * board_side; + let panel = if stacked { + let most = (height - BOARD_MIN - 16.0).max(STACK_BOTTOM_MIN); + let rest = (height - board_stack - 16.0).clamp(STACK_BOTTOM_MIN, most); + egui::Panel::bottom("opening_side_stacked") + .resizable(true) + .default_size(rest) + .size_range(STACK_BOTTOM_MIN..=most) + .show(ui, |ui| side(this, ui)) + } else { + let board = height - 16.0; + let most = (width - BOARD_MIN - 24.0).max(SIDE_LEAST); + let room = (width - board - 24.0).clamp(SIDE_LEAST, most); + egui::Panel::right("opening_side") + .resizable(true) + .default_size((width * 0.4).clamp(260.0, 460.0).min(room)) + .size_range(SIDE_LEAST..=most) + .show(ui, |ui| side(this, ui)) + }; + crate::widgets::check_panel("opening_side", &panel.response); + egui::CentralPanel::default().show(ui, |ui| { + let area = ui.available_rect_before_wrap(); + let side = area.width().min(area.height()).max(1.0).floor(); + let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); + let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); + let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| board(this, ui)); + }); +} + +/// The frame of a state card (the player's card of a game against the computer). +pub(crate) fn card(ui: &Ui, active: bool, alert: bool) -> egui::Frame { + let mut frame = egui::Frame::new() + .inner_margin(egui::Margin::symmetric(10, 6)) + .corner_radius(4) + .stroke(egui::Stroke::new( + 1.0, + ui.visuals().widgets.noninteractive.bg_stroke.color, + )); + if active { + frame = frame.fill(ui.visuals().selection.bg_fill.gamma_multiply(0.35)); + } + if alert { + frame = frame.stroke(egui::Stroke::new(1.5, ui.visuals().error_fg_color)); + } + frame +} + +/// A block of a fixed height: whatever it holds, what follows never moves. +pub(crate) fn fixed_block(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R { + let width = ui.available_width().max(1.0); + let (rect, _) = ui.allocate_exact_size(vec2(width, height), egui::Sense::hover()); + let mut child = ui.new_child( + egui::UiBuilder::new() + .max_rect(rect) + .layout(egui::Layout::top_down(egui::Align::Min)), + ); + child.set_clip_rect(rect.intersect(ui.clip_rect())); + add(&mut child) +} + +/// One line of text cut with "…", the whole text on hover. +pub(crate) fn line(ui: &mut Ui, text: impl Into) -> egui::Response { + let text = text.into(); + let hover = text.text().to_owned(); + let response = ui.add(egui::Label::new(text).truncate()); + if hover.is_empty() { + response + } else { + response.on_hover_text(hover) + } +} + +/// The trained colour of a repertoire, kept in the settings since 2.2.0 (an old "both +/// colours" repertoire opens for White). +pub(crate) fn side_of(settings: &Settings, id: &RepertoireId) -> LearningSide { + match settings.repertoire_modes.get(id.as_str()) { + Some((TrainingMode::Black, _)) => LearningSide::Black, + _ => LearningSide::White, + } +} + +pub(crate) fn set_side(settings: &mut Settings, id: &RepertoireId, side: LearningSide) { + let mode = match side { + LearningSide::White => TrainingMode::White, + LearningSide::Black => TrainingMode::Black, + }; + settings.repertoire_modes.insert( + id.to_string(), + (mode, trainer::repertoire::QueueMode::SpacedRepetition), + ); +} + +pub(crate) fn king(side: LearningSide) -> &'static str { + match side { + LearningSide::White => "♔", + LearningSide::Black => "♚", + } +} + +pub(crate) fn you_play(side: LearningSide) -> &'static str { + tr(match side { + LearningSide::White => "You play White", + LearningSide::Black => "You play Black", + }) +} + +pub(crate) fn orientation(side: LearningSide) -> Color { + side.color() +} + +/// "4. Ba4" or "4… Nf6" in the notation of the application. +pub(crate) fn move_text(game: &Game, node: NodeId) -> Option { + let (number, color) = game.move_number(node)?; + let san = crate::san::show(&game.game_move(node)?.san).into_owned(); + Some(match color { + Color::White => format!("{number}. {san}"), + Color::Black => format!("{number}… {san}"), + }) +} + +/// The symbol of a move's assessment (`!`, `?!` …) and its colour for text. +pub(crate) fn assessment(game: &Game, node: NodeId, dark: bool) -> Option<(&'static str, Color32)> { + let nag = game + .node(node)? + .nags() + .iter() + .copied() + .find(|nag| nag.is_move_assessment())?; + Some(( + nag.symbol()?, + crate::notation::assessment_text_color(nag, dark)?, + )) +} + +/// The node reached from the root by these UCI moves. +pub(crate) fn node_at(game: &Game, path: &[String]) -> Option { + let mut at = NodeId::ROOT; + for uci in path { + let mv = uci + .parse::() + .ok()? + .to_move(game.position(at)?) + .ok()?; + at = game.find_child(at, mv)?; + } + Some(at) +} + +/// The UCI moves from the root to a node. +pub(crate) fn uci_path(game: &Game, node: NodeId) -> Vec { + game.path(node) + .into_iter() + .skip(1) + .filter_map(|id| game.game_move(id).and_then(|mv| mv.uci())) + .collect() +} + +/// "C84 · Ruy Lopez: Closed": the most precise named position on the way to `node`. +pub(crate) fn opening_text(game: &Game, node: NodeId) -> String { + let keys: Vec = game + .path(node) + .into_iter() + .filter_map(|id| game.position(id)) + .map(chess_openings::key) + .collect(); + match chess_openings::deepest(&keys) { + Some((_, id)) => { + let opening = chess_openings::get(id); + format!("{} · {}", opening.eco, opening.name) + } + None => String::new(), + } +} + +/// The start a repertoire's lines share: the last move before the first branching. +pub(crate) fn common_start(game: &Game) -> NodeId { + let mut at = NodeId::ROOT; + while let [only] = game.children(at) { + at = *only; + } + at +} + +pub(crate) fn last_move(game: &Game, node: NodeId) -> Option<(Square, Square)> { + match game.game_move(node)?.kind { + MoveKind::Normal(mv) => Some(( + mv.from().unwrap_or_else(|| mv.to()), + crate::board::ui_target(&mv), + )), + MoveKind::Null => None, + } +} + +/// The lines of a repertoire: the paths of its last moves, without switched-off +/// branches, in PGN order. +pub(crate) fn lines(game: &Game, disabled: impl Fn(&[String]) -> bool) -> Vec> { + let mut out = Vec::new(); + let mut stack = vec![(NodeId::ROOT, Vec::new())]; + while let Some((node, path)) = stack.pop() { + let children: Vec<_> = game + .children(node) + .iter() + .filter_map(|child| { + let uci = game.game_move(*child)?.uci()?; + let mut next = path.clone(); + next.push(uci); + (!disabled(&next)).then_some((*child, next)) + }) + .collect(); + if children.is_empty() { + if !path.is_empty() { + out.push(path); + } + } else { + stack.extend(children.into_iter().rev()); + } + } + out +} + +/// The end of the local day: "today" in the counts includes everything due before it. +pub(crate) fn end_of_today() -> i64 { + use chrono::{Local, TimeZone}; + let now = Local::now(); + let tomorrow = now.date_naive().succ_opt().unwrap_or(now.date_naive()); + tomorrow + .and_hms_opt(0, 0, 0) + .and_then(|midnight| Local.from_local_datetime(&midnight).earliest()) + .map_or(now.timestamp() + 24 * 60 * 60, |midnight| { + midnight.timestamp() - 1 + }) +} + +pub(crate) fn now() -> i64 { + chrono::Local::now().timestamp() +} + +/// "today at 18:40", "tomorrow", "in 3 days", then a date as in the library. +pub(crate) fn when(at: i64, now: i64) -> String { + use chrono::{Local, TimeZone}; + let (Some(at), Some(now)) = ( + Local.timestamp_opt(at, 0).single(), + Local.timestamp_opt(now, 0).single(), + ) else { + return String::new(); + }; + let days = (at.date_naive() - now.date_naive()).num_days(); + match days { + ..=0 => trf("today at {time}", &[("time", &at.format("%H:%M"))]), + 1 => tr("tomorrow").to_owned(), + 2..=6 => trf("in {days} days", &[("days", &days)]), + _ => at.format("%d.%m.%Y").to_string(), + } +} + +#[derive(Default)] +pub(crate) struct BoardAnnotations { + pub(crate) arrows: Vec, + pub(crate) circles: Vec<(Square, Color32)>, + pub(crate) badge: Option, +} + +/// The marks of a PGN move on the board: its assessment badge, `[%cal]` arrows and +/// `[%csl]` squares. +pub(crate) fn pgn_annotations_at(game: &Game, at: NodeId) -> BoardAnnotations { + let mut out = BoardAnnotations::default(); + let Some(node) = game.node(at) else { + return out; + }; + let square = node.game_move().and_then(|game_move| match game_move.kind { + MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)), + MoveKind::Null => None, + }); + if let Some(square) = square { + out.badge = node + .nags() + .iter() + .copied() + .find(|nag| nag.is_move_assessment()) + .and_then(|nag| { + Some(Badge { + square, + text: nag.symbol()?, + color: crate::notation::assessment_color(nag)?, + }) + }); + } + for comment in node.comments_after() { + for part in parse_comment(comment) { + match part { + CommentPart::Annotation(Annotation::Arrows(list)) => { + out.arrows + .extend(list.into_iter().map(|(color, from, to)| Arrow { + from, + to, + color: crate::game_view::shape_color(color), + weight: 0.9, + })); + } + CommentPart::Annotation(Annotation::Squares(list)) => { + out.circles.extend( + list.into_iter() + .map(|(color, square)| (square, crate::game_view::shape_color(color))), + ); + } + CommentPart::Text(_) | CommentPart::Annotation(_) => {} + } + } + } + out +} + +/// The position after a node, for a board that only shows it. +pub(crate) fn position_of(game: &Game, node: NodeId) -> chess_core::shakmaty::Chess { + game.position(node) + .or_else(|| game.position(NodeId::ROOT)) + .cloned() + .unwrap_or_default() +} + +/// A board that only shows a position. +pub(crate) fn still_board( + ui: &mut Ui, + state: &mut crate::board::BoardState, + settings: &Settings, + pos: &chess_core::shakmaty::Chess, + orientation: Color, + last_move: Option<(Square, Square)>, + annotations: &BoardAnnotations, +) { + crate::board::BoardView { + pos, + orientation, + last_move, + arrows: &annotations.arrows, + circles: &annotations.circles, + badge: annotations.badge, + interactive: false, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation: settings.animation.seconds(), + premove: None, + auto_queen: false, + alert: None, + } + .show(ui, state); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() { + for (nag, symbol) in [ + (1, "!"), + (2, "?"), + (3, "!!"), + (4, "??"), + (5, "!?"), + (6, "?!"), + ] { + let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game; + let node = game.main_child(NodeId::ROOT).unwrap(); + let badge = pgn_annotations_at(&game, node).badge.unwrap(); + assert_eq!(badge.text, symbol); + assert_eq!(badge.square, Square::E4); + assert_eq!( + badge.color, + crate::notation::assessment_color(chess_core::Nag(nag)).unwrap() + ); + } + for (fen, san, expected) in [ + ("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1), + ("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8), + ] { + let game = + chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *")) + .game; + let node = game.main_child(NodeId::ROOT).unwrap(); + assert_eq!( + pgn_annotations_at(&game, node).badge.unwrap().square, + expected + ); + } + let game = chess_core::parse_str("1. e4 $14 *").game; + let node = game.main_child(NodeId::ROOT).unwrap(); + assert!( + pgn_annotations_at(&game, node).badge.is_none(), + "position assessments are not move badges" + ); + } + + #[test] + fn pgn_shapes_of_a_move_become_arrows_and_circles() { + let game = chess_core::parse_str("1. e4 {[%cal Re2e4,Ge7e5] [%csl Ye4]} *").game; + let node = game.main_child(NodeId::ROOT).unwrap(); + let marks = pgn_annotations_at(&game, node); + assert_eq!(marks.arrows.len(), 2); + assert_eq!( + marks.arrows[0].color, + crate::game_view::shape_color(chess_core::ShapeColor::Red) + ); + assert_eq!( + marks.circles, + [( + Square::E4, + crate::game_view::shape_color(chess_core::ShapeColor::Yellow) + )] + ); + assert!(pgn_annotations_at(&game, NodeId::ROOT).badge.is_none()); + } + + #[test] + fn common_start_stops_before_the_first_branching() { + let game = chess_core::parse_str("1. e4 e5 2. Nf3 (2. Bc4) Nc6 *").game; + let start = common_start(&game); + assert_eq!(uci_path(&game, start), ["e2e4", "e7e5"]); + let game = chess_core::parse_str("1. e4 (1. d4) *").game; + assert_eq!(common_start(&game), NodeId::ROOT); + let game = chess_core::parse_str("*").game; + assert_eq!(common_start(&game), NodeId::ROOT); + } + + #[test] + fn lines_are_the_last_moves_in_pgn_order_without_switched_off_branches() { + let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *").game; + let all = lines(&game, |_| false); + assert_eq!( + all, + [ + vec!["e2e4", "e7e5", "g1f3"], + vec!["e2e4", "e7e5", "f1c4"], + vec!["e2e4", "c7c5", "g1f3"], + ] + .map(|line| line.into_iter().map(str::to_owned).collect::>()) + ); + let without_c5 = lines(&game, |path| { + path.starts_with(&["e2e4".into(), "c7c5".into()]) + }); + assert_eq!(without_c5.len(), 2); + let node = node_at(&game, &all[1]).unwrap(); + assert_eq!(uci_path(&game, node), all[1]); + assert_eq!(move_text(&game, node).as_deref(), Some("2. Bc4")); + let black = node_at(&game, &all[2][..2]).unwrap(); + assert_eq!(move_text(&game, black).as_deref(), Some("1… c5")); + } + + #[test] + fn dates_read_as_today_tomorrow_days_then_a_date() { + let at = 1_800_000_000; + assert!(when(at + 60, at).contains(':')); + assert_eq!(when(at + 24 * 3600, at), tr("tomorrow")); + assert!(when(at + 3 * 24 * 3600, at).contains('3')); + assert_eq!(when(at + 30 * 24 * 3600, at).len(), 10); + assert!(end_of_today() >= now()); + assert!(end_of_today() - now() < 24 * 3600 + 3600); + } +} diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs new file mode 100644 index 0000000..a1f3b98 --- /dev/null +++ b/apps/desktop/src/opening_lines.rs @@ -0,0 +1,584 @@ +//! The «Lines» screen of opening training (spec §6.3): the repertoire's tree, read only, +//! to choose what to train and which branches to leave out. + +use std::collections::BTreeSet; +use std::sync::mpsc; + +use chess_core::shakmaty::Color; +use chess_core::{Game, NodeId}; +use egui::{Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + LearningData, LearningItemKey, LearningSide, Library, Repertoire, RepertoireId, StatsScope, + active_learning_memberships, +}; + +use crate::board::BoardState; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, GAP, pgn_annotations_at}; +use crate::settings::Settings; + +const SELECTED_H: f32 = 92.0; +const TOOL_H: f32 = 28.0; +const MAIN_W: f32 = 170.0; + +pub enum LinesAction { + Back, + OpenSettings, + /// Train the lines through this move (empty: every line). + Train { + through: Vec, + label: String, + }, + /// Switch a branch off (`true`) or on again, from the move at this path. + SetDisabled { + path: Vec, + disabled: bool, + }, +} + +/// The repertoire's own moves with their paths and which of them are learnt; computed +/// off the frame. +struct Counts { + moves: Vec<(Vec, LearningItemKey)>, + learnt: BTreeSet, +} + +pub struct OpeningLinesUi { + id: RepertoireId, + name: String, + side: LearningSide, + repertoire: Repertoire, + game: Game, + lines: Vec>, + cursor: NodeId, + scroll: bool, + orientation: Color, + board: BoardState, + counts: Option, + counting: Option>>, + error: Option, +} + +impl OpeningLinesUi { + pub fn new( + library: &Library, + learning: &LearningData, + id: RepertoireId, + side: LearningSide, + cursor: Option>, + ) -> Option { + let repertoire = library.repertoire(&id)?.clone(); + let game = repertoire.game(); + let cursor = cursor + .and_then(|path| layout::node_at(&game, &path)) + .unwrap_or(NodeId::ROOT); + let lines = layout::lines(&game, |path| repertoire.is_prefix_disabled(path)); + let mut this = Self { + id, + name: repertoire.name.clone(), + side, + repertoire, + game, + lines, + cursor, + scroll: true, + orientation: layout::orientation(side), + board: BoardState::default(), + counts: None, + counting: None, + error: None, + }; + this.count(library, learning); + Some(this) + } + + pub fn id(&self) -> &RepertoireId { + &self.id + } + + pub fn cursor_path(&self) -> Vec { + layout::uci_path(&self.game, self.cursor) + } + + /// The library changed (a branch switched off or on): recount, keep the move. + pub fn refresh(&mut self, library: &Library, learning: &LearningData) { + if let Some(repertoire) = library.repertoire(&self.id) { + self.repertoire = repertoire.clone(); + self.name = repertoire.name.clone(); + self.lines = layout::lines(&self.game, |path| repertoire.is_prefix_disabled(path)); + } + self.count(library, learning); + } + + fn count(&mut self, library: &Library, learning: &LearningData) { + let library = library.clone(); + let learning = learning.clone(); + let scope = StatsScope::for_repertoire(self.id.clone(), self.side, layout::now()); + let (tx, rx) = mpsc::channel(); + self.counting = Some(rx); + if let Err(error) = crate::platform::spawn("repertoire-lines-count", move || { + let result = active_learning_memberships(&library, &scope) + .map(|memberships| { + let learnt = memberships + .iter() + .filter(|membership| { + learning + .item(&membership.key) + .is_some_and(|item| item.is_learnt()) + }) + .map(|membership| membership.key.clone()) + .collect(); + Counts { + moves: memberships + .into_iter() + .map(|membership| (membership.path, membership.key)) + .collect(), + learnt, + } + }) + .map_err(|error| error.to_string()); + let _ = tx.send(result); + }) { + self.counting = None; + self.error = Some(error.to_string()); + } + } + + fn poll(&mut self) { + let Some(rx) = &self.counting else { + return; + }; + match rx.try_recv() { + Ok(Ok(counts)) => { + self.counts = Some(counts); + self.counting = None; + } + Ok(Err(error)) => { + self.error = Some(error); + self.counting = None; + } + Err(mpsc::TryRecvError::Empty) => {} + Err(mpsc::TryRecvError::Disconnected) => self.counting = None, + } + } + + /// The prefix that switches this path off, if any. + fn disabled_by(&self, path: &[String]) -> Option> { + self.repertoire + .disabled_prefixes + .iter() + .filter(|prefix| path.starts_with(prefix)) + .min_by_key(|prefix| prefix.len()) + .cloned() + } + + fn goto(&mut self, node: NodeId) { + if self.game.node(node).is_some() { + self.cursor = node; + self.scroll = true; + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { + return; + } + let mut command = None; + ui.input_mut(|input| { + for (key, name) in [ + (Key::ArrowLeft, "back"), + (Key::ArrowRight, "forward"), + (Key::ArrowUp, "previous"), + (Key::ArrowDown, "next"), + (Key::Home, "home"), + (Key::End, "end"), + (Key::F, "flip"), + (Key::Enter, "train"), + (Key::Escape, "back_screen"), + ] { + if command.is_none() + && (input.consume_key(Modifiers::NONE, key) + || input.consume_key(Modifiers::SHIFT, key)) + { + command = Some(name); + } + } + if command.is_none() + && input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + { + command = Some("back_screen"); + } + }); + let game = &self.game; + let cursor = self.cursor; + match command { + Some("back") => { + if let Some(parent) = game.parent(cursor) { + self.goto(parent); + } + } + Some("forward") => { + if let Some(next) = game.main_child(cursor) { + self.goto(next); + } + } + Some("previous") => { + if let Some(other) = game.prev_sibling(cursor) { + self.goto(other); + } + } + Some("next") => { + if let Some(other) = game.next_sibling(cursor) { + self.goto(other); + } + } + Some("home") => self.goto(NodeId::ROOT), + Some("end") => { + let end = game.line_end(cursor); + self.goto(end); + } + Some("flip") => self.orientation = self.orientation.other(), + Some("train") => actions.push(self.train_action()), + Some("back_screen") => actions.push(LinesAction::Back), + _ => {} + } + } + + fn train_action(&self) -> LinesAction { + let through = self.cursor_path(); + let label = self.path_label(self.cursor); + LinesAction::Train { through, label } + } + + /// "… 4. Ba4 Nf6": the moves to a node in the notation of the application. + fn path_label(&self, node: NodeId) -> String { + let mut words = Vec::new(); + for id in self.game.path(node).into_iter().skip(1) { + let Some(mv) = self.game.game_move(id) else { + continue; + }; + let san = crate::san::show(&mv.san).into_owned(); + match self.game.move_number(id) { + Some((number, Color::White)) => words.push(format!("{number}. {san}")), + Some((number, Color::Black)) if words.is_empty() => { + words.push(format!("{number}… {san}")) + } + _ => words.push(san), + } + } + words.join(" ") + } + + fn below(&self, path: &[String]) -> Option<(usize, usize, usize)> { + let counts = self.counts.as_ref()?; + let lines = self + .lines + .iter() + .filter(|line| line.starts_with(path)) + .count(); + let mine: Vec<_> = counts + .moves + .iter() + .filter(|(move_path, _)| move_path.starts_with(path)) + .collect(); + let learnt = mine + .iter() + .filter(|(_, key)| counts.learnt.contains(key)) + .count(); + Some((lines, mine.len(), learnt)) + } + + fn selected_block(&self, ui: &mut Ui, actions: &mut Vec) { + let path = self.cursor_path(); + let disabled = self.disabled_by(&path); + layout::fixed_block(ui, SELECTED_H, |ui| { + let inner = vec2(ui.available_width() - 20.0, SELECTED_H - 12.0); + layout::card(ui, false, false).show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.spacing_mut().item_spacing.y = 4.0; + if self.cursor == NodeId::ROOT { + layout::line(ui, RichText::new(tr("Start position")).strong()); + } else { + let label = self.path_label(self.cursor); + // Cut on the left: the last moves matter. + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.set_max_height(20.0); + layout::line(ui, RichText::new(label).strong()); + }); + } + if disabled.is_some() { + layout::line( + ui, + RichText::new(tr("Not trained")).color(ui.visuals().warn_fg_color), + ); + } else { + let text = match self.below(&path) { + Some((lines, mine, learnt)) => trf( + "Below: {n} lines · {y} your moves · learned {x}", + &[("n", &lines), ("y", &mine), ("x", &learnt)], + ), + None => tr("Counting moves…").to_owned(), + }; + layout::line(ui, RichText::new(text).weak()); + } + ui.horizontal(|ui| { + let label = if self.cursor == NodeId::ROOT { + tr("Review all lines") + } else { + tr("Train this branch") + }; + let width = MAIN_W.min(ui.available_width() / 2.0 - 4.0); + let can_train = disabled.is_none() && !self.lines.is_empty(); + if ui + .add_enabled_ui(can_train, |ui| { + crate::widgets::primary_wide(ui, label, width) + }) + .inner + .on_hover_text("Enter") + .clicked() + { + actions.push(self.train_action()); + } + if self.cursor != NodeId::ROOT { + let (label, action) = match &disabled { + Some(prefix) => ( + tr("Train again"), + LinesAction::SetDisabled { + path: prefix.clone(), + disabled: false, + }, + ), + None => ( + tr("Don't train"), + LinesAction::SetDisabled { + path: path.clone(), + disabled: true, + }, + ), + }; + if ui + .add( + egui::Button::new(label) + .truncate() + .min_size(vec2(width, 30.0)), + ) + .clicked() + { + actions.push(action); + } + } + }); + }); + }); + } + + fn side(&mut self, ui: &mut Ui, actions: &mut Vec) { + let rect = ui.available_rect_before_wrap(); + let footer_h = TOOL_H + 12.0; + let footer = egui::Rect::from_min_max( + egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())), + rect.max, + ); + let body = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); + let mut clicked = None; + ui.scope_builder(egui::UiBuilder::new().max_rect(body), |ui| { + ui.set_clip_rect(body.intersect(ui.clip_rect())); + ui.spacing_mut().item_spacing.y = GAP; + ui.add_space(4.0); + let opening = layout::opening_text(&self.game, self.cursor); + layout::fixed_block(ui, 20.0, |ui| { + layout::line(ui, RichText::new(opening).weak()); + }); + let tree = (ui.available_height() - SELECTED_H - GAP).max(0.0); + let scroll = std::mem::take(&mut self.scroll); + let game = &self.game; + let cursor = self.cursor; + let response = layout::fixed_block(ui, tree, |ui| { + egui::ScrollArea::vertical() + .id_salt("opening_lines_tree") + .auto_shrink([false, false]) + .show(ui, |ui| { + crate::notation::Notation { + game, + cursor, + scroll_to_cursor: scroll, + marks: None, + preview: None, + translations: None, + editor: None, + read_only: true, + dim_until: None, + mistakes: None, + } + .show(ui) + }) + .inner + }); + clicked = response.clicked; + if let Some(error) = &self.error { + ui.colored_label(ui.visuals().warn_fg_color, error); + } + self.selected_block(ui, actions); + }); + if let Some(node) = clicked { + self.cursor = node; + } + ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { + ui.separator(); + ui.horizontal(|ui| { + let icon = |s: &str| { + egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H)) + }; + let game = &self.game; + let mut target = None; + if ui.add(icon("⏮")).clicked() { + target = Some(NodeId::ROOT); + } + if ui.add(icon("◀")).clicked() { + target = game.parent(self.cursor); + } + if ui.add(icon("▶")).clicked() { + target = game.main_child(self.cursor); + } + if ui.add(icon("⏭")).clicked() { + target = Some(game.line_end(self.cursor)); + } + ui.separator(); + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + self.orientation = self.orientation.other(); + } + if let Some(target) = target { + self.goto(target); + } + }); + }); + } + + pub fn show(&mut self, ui: &mut Ui, settings: &Settings) -> Vec { + self.poll(); + if self.counting.is_some() { + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(50)); + } + let mut actions = Vec::new(); + self.keyboard(ui, &mut actions); + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + tr("⬅ Repertoires") + }; + let subtitle = trf( + "Lines · {n} lines · {y} your moves", + &[ + ("n", &self.lines.len()), + ( + "y", + &self + .counts + .as_ref() + .map_or_else(|| "…".to_owned(), |counts| counts.moves.len().to_string()), + ), + ], + ); + let name = self.name.clone(); + let mut header = (false, false); + layout::screen( + ui, + self, + |_, ui| header = crate::widgets::section_header_sub(ui, back, &name, &subtitle), + |this, ui| this.side(ui, &mut actions), + |this, ui| { + let position = layout::position_of(&this.game, this.cursor); + let marks = pgn_annotations_at(&this.game, this.cursor); + let last = layout::last_move(&this.game, this.cursor); + layout::still_board( + ui, + &mut this.board, + settings, + &position, + this.orientation, + last, + &marks, + ); + }, + ); + if header.0 { + actions.push(LinesAction::Back); + } + if header.1 { + actions.push(LinesAction::OpenSettings); + } + actions + } + + #[cfg_attr(not(test), allow(dead_code))] + pub fn debug_select(&mut self, path: &[String]) { + if let Some(node) = layout::node_at(&self.game, path) { + self.goto(node); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn lines_ui(pgn: &str) -> (Library, OpeningLinesUi) { + let mut library = Library::default(); + let id = library + .create("Lines", &chess_core::parse_str(pgn).game) + .unwrap(); + let mut ui = OpeningLinesUi::new( + &library, + &LearningData::default(), + id, + LearningSide::White, + None, + ) + .unwrap(); + let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5); + while ui.counting.is_some() && web_time::Instant::now() < deadline { + ui.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + (library, ui) + } + + #[test] + fn counts_below_a_move_and_branches_switched_off() { + let (mut library, mut ui) = lines_ui("1. e4 e5 (1... c5 2. Nf3) 2. Nf3 (2. Bc4) *"); + assert_eq!(ui.below(&[]), Some((3, 4, 0))); + let c5 = ["e2e4".to_owned(), "c7c5".to_owned()]; + assert_eq!(ui.below(&c5), Some((1, 1, 0))); + ui.debug_select(&c5); + assert_eq!(ui.cursor_path(), c5); + assert_eq!(ui.path_label(ui.cursor), "1. e4 c5"); + assert!(matches!( + ui.train_action(), + LinesAction::Train { through, .. } if through == c5 + )); + let id = ui.id().clone(); + library + .repertoire_mut(&id) + .unwrap() + .set_prefix_disabled(&c5, true) + .unwrap(); + ui.refresh(&library, &LearningData::default()); + let deadline = web_time::Instant::now() + std::time::Duration::from_secs(5); + while ui.counting.is_some() && web_time::Instant::now() < deadline { + ui.poll(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(ui.lines.len(), 2); + assert_eq!( + ui.disabled_by(&[c5[0].clone(), c5[1].clone(), "g1f3".into()]), + Some(c5.to_vec()) + ); + assert_eq!(ui.below(&[]), Some((2, 3, 0))); + } +} diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs new file mode 100644 index 0000000..e4c153e --- /dev/null +++ b/apps/desktop/src/opening_session.rs @@ -0,0 +1,2426 @@ +//! The «Session» screen of opening training (docs/design/opening-trainer-v2-spec.md §4–6): +//! the program plays the line up to the next question, shows a new move before asking +//! it, takes the answer on the board and records it in the background. + +use std::{ + collections::{BTreeMap, BTreeSet, HashMap, VecDeque}, + sync::{ + atomic::{AtomicU64, Ordering}, + mpsc, + }, + time::Duration, +}; + +use chess_core::shakmaty::{CastlingMode, Chess, Color, Move, Square, fen::Fen, uci::UciMove}; +use chess_core::{Game, NodeId}; +use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; +use trainer::repertoire::{ + AttemptApplication, LearningContextStep, LearningData, LearningItem, LearningItemKey, + LearningPresentation, LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, + LearningSessionTarget, LearningSide, LearningStore, Library, PersistedSessionAttempt, + RepertoireId, SrsSettings, StatsScope, TrainingAttempt, TrainingEventType, + active_learning_keys, fen4, +}; +use web_time::{Instant, SystemTime, UNIX_EPOCH}; + +use crate::assets::Sound; +use crate::board::{Arrow, BoardState, BoardView}; +use crate::i18n::{tr, trf}; +use crate::opening_layout::{self as layout, BoardAnnotations, GAP, pgn_annotations_at}; +use crate::settings::Settings; + +const WRONG_SHOWN: Duration = Duration::from_millis(400); +/// How long «Correct» and «Got it» stay after the move's animation. +const FEEDBACK: Duration = Duration::from_millis(600); +const DEFAULT_ANIMATION: Duration = Duration::from_millis(250); +/// Mistakes listed under «Moves to remember». +const REMEMBER_ROWS: usize = 8; +const CARD_H: f32 = 64.0; +const LINE_H: f32 = 20.0; +const ROW_H: f32 = 30.0; +const TOOL_H: f32 = 28.0; +const LEFT_W: f32 = 150.0; +const MAIN_W: f32 = 170.0; +static NEXT_ID: AtomicU64 = AtomicU64::new(1); + +pub enum SessionAction { + /// Leave the session (to the repertoires, or to the lines it was started from). + Back, + OpenSettings, + Sound(Sound), + /// «10 more new»: the caller prepares the next new moves in the background. + MoreNew, +} + +/// What the session goes through. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum SessionKind { + /// What is due today and up to ten new moves. + Daily, + /// Every move of every line, one pass. + ReviewAll, + /// Every move of the lines through `through` (UCI from the start). + Branch { through: Vec, label: String }, +} + +impl SessionKind { + pub fn subtitle(&self, side: LearningSide) -> String { + match self { + Self::Daily => match side { + LearningSide::White => tr("Training · you play White").to_owned(), + LearningSide::Black => tr("Training · you play Black").to_owned(), + }, + Self::ReviewAll => match side { + LearningSide::White => tr("Review all lines · you play White").to_owned(), + LearningSide::Black => tr("Review all lines · you play Black").to_owned(), + }, + Self::Branch { label, .. } => trf("Branch: {path}", &[("path", label)]), + } + } +} + +#[derive(Clone)] +struct VisualMove { + #[cfg_attr(not(test), allow(dead_code))] + uci: String, + before: Chess, + after: Chess, + from: Square, + to: Square, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum PlayOutcome { + CorrectIndependent, + WrongIndependent, + WrongReplay, + ReplayAfterError, + /// The move after a hint or a revealed alternative. + PreviewedReplay, + /// A new move played after it was shown. + NewPlayed, +} + +#[derive(Clone)] +enum CommitKind { + Context, + ReusedContext, + Play { + visual: Box, + outcome: PlayOutcome, + shown_prefix: ShownPrefix, + }, + /// `new`: the first showing of a new move; otherwise a hint (or the move revealed + /// after another repertoire move). + Preview { + new: bool, + }, +} + +#[derive(Clone)] +struct ShownPrefix { + repertoire_id: RepertoireId, + path: Vec, +} + +#[derive(Clone)] +struct PendingCommit { + attempts: Vec, + kind: CommitKind, + /// The question the event answers (for the session's result). + target: Option, +} + +enum Playback { + Automatic { + current: Box, + remaining: VecDeque, + started_at: Instant, + duration: Duration, + }, + Wrong { + visual: Box, + until: Instant, + }, + Alternative { + visual: Box, + until: Instant, + }, + Accepted { + started_at: Instant, + duration: Duration, + outcome: PlayOutcome, + }, +} + +/// The numbers of the session's result. +#[derive(Default)] +struct Tally { + first_time: usize, + mistakes: usize, + hints: usize, + new_moves: usize, + missed: Vec, +} + +impl Tally { + fn any(&self) -> bool { + self.first_time + self.mistakes + self.hints + self.new_moves > 0 + } + + fn miss(&mut self, target: Option) { + if let Some(target) = target + && !self.missed.iter().any(|missed| missed.key == target.key) + { + self.missed.push(target); + } + } + + fn missed_key(&self, key: &LearningItemKey) -> bool { + self.missed.iter().any(|missed| &missed.key == key) + } +} + +/// The states of spec §4.2 (S0 is the caller's: before the session exists). +#[derive(Clone, Debug, PartialEq)] +enum State { + Watch, + NextLine, + New, + Yours, + YoursMore(String), + Correct, + Wrong, + Alternative, + GotIt, + Hint, + NewDone, + SaveError(String), + Failed(String), + Summary, +} + +/// Computed once when the result is shown. +struct Summary { + next_review: String, + more_new: usize, +} + +pub struct OpeningSessionUi { + library: Library, + store: LearningStore, + session: LearningSessionSnapshot, + learning: LearningData, + kind: SessionKind, + presentation: Option, + completed_attempt_ids: BTreeSet, + pending_commit: Option, + commit_in_flight: Option>>, + #[cfg(test)] + synchronous_commits: bool, + save_error: Option, + error: Option, + board: BoardState, + board_position: Chess, + // Parsed once in the training-start worker, never in a frame or save callback. + annotation_games: BTreeMap, + /// Active answers of this session's scope (a branch: of the branch). + repertoire_answers: BTreeSet, + /// Active answers of the whole repertoire, for the result. + repertoire_keys: BTreeSet, + /// The lines of a review, to count «line k of n». + lines: Vec>, + line: usize, + next_line_banner: bool, + // The visible node is independent of the session's already-advanced target. + displayed_node: Option<(RepertoireId, NodeId)>, + board_shown: bool, + pending_automatic: Option>, + shown_prefix: Option, + playback: Option, + needs_prepare: bool, + animation: Duration, + /// How long «Correct» and «Got it» stay after the move ([`FEEDBACK`]). + feedback: Duration, + ready_since: Option, + last_move: Option<(Square, Square)>, + orientation: Color, + /// The next frame puts the board in place without a slide (a skipped context). + jump: bool, + /// The move revealed after another repertoire move was played (S5a). + alternative_revealed: bool, + /// Left before the end: the result says «Session stopped». + stopped: bool, + exit_requested: bool, + /// Leave at the next frame (an exit asked during a save, nothing answered). + leave: bool, + /// Started from the «Lines» screen: going back leads there. + back_to_lines: bool, + current_key: Option, + tally: Tally, + summary: Option, + shown_state: State, + pending_sounds: Vec, + #[cfg(test)] + visual_log: Vec, +} + +impl OpeningSessionUi { + /// A new session (never a resumed one: every answer of an earlier session is already + /// recorded). Runs in a worker: it reads the store and parses the repertoire. + pub fn new( + library: Library, + store: LearningStore, + scope: StatsScope, + kind: SessionKind, + ) -> Result { + let data = store.load().map_err(|error| error.to_string())?; + let id = unique_id("learning-session"); + let srs = SrsSettings::default(); + let mut session = match &kind { + SessionKind::Daily => LearningSessionSnapshot::new_daily( + id, + &library, + &data.learning, + scope, + srs, + layout::NEW_PER_SESSION, + ), + SessionKind::ReviewAll => LearningSessionSnapshot::new_single_pass_review( + id, + &library, + &data.learning, + scope, + srs, + ), + SessionKind::Branch { through, .. } => LearningSessionSnapshot::new_branch_review( + id, + &library, + &data.learning, + scope, + srs, + through, + ), + } + .map_err(|error| error.to_string())?; + store + .save_session(&mut session) + .map_err(|error| error.to_string())?; + Self::from_session(library, store, data.learning, session, kind) + } + + /// «10 more new» after a finished daily session. Runs in a worker. + pub fn more_new( + library: Library, + store: LearningStore, + mut session: LearningSessionSnapshot, + orientation: Color, + ) -> Result { + let data = store.load().map_err(|error| error.to_string())?; + session + .introduce_more(&library, &data.learning, layout::NEW_PER_SESSION) + .map_err(|error| error.to_string())?; + store + .save_session(&mut session) + .map_err(|error| error.to_string())?; + let mut this = + Self::from_session(library, store, data.learning, session, SessionKind::Daily)?; + this.orientation = orientation; + Ok(this) + } + + fn from_session( + library: Library, + store: LearningStore, + learning: LearningData, + session: LearningSessionSnapshot, + kind: SessionKind, + ) -> Result { + let completed_attempt_ids = learning + .attempts + .iter() + .filter(|attempt| attempt.session_id == session.id()) + .map(|attempt| attempt.client_attempt_id.clone()) + .collect(); + let repertoire_answers = active_learning_keys(&library, &session.stats_scope) + .map_err(|error| error.to_string())?; + let mut whole = session.stats_scope.clone(); + whole.branch_root = None; + let repertoire_keys = if whole == session.stats_scope { + repertoire_answers.clone() + } else { + active_learning_keys(&library, &whole).map_err(|error| error.to_string())? + }; + let annotation_games: BTreeMap<_, _> = session + .stats_scope + .repertoire_ids + .iter() + .filter_map(|id| { + library + .repertoire(id) + .map(|repertoire| (id.clone(), repertoire.game())) + }) + .collect(); + let lines = session + .stats_scope + .repertoire_ids + .iter() + .filter_map(|id| Some((library.repertoire(id)?, annotation_games.get(id)?))) + .flat_map(|(repertoire, game)| { + layout::lines(game, |path| repertoire.is_prefix_disabled(path)) + }) + .filter(|line| match &kind { + SessionKind::Branch { through, .. } => line.starts_with(through), + SessionKind::Daily | SessionKind::ReviewAll => true, + }) + .collect(); + let orientation = layout::orientation(session.stats_scope.side); + Ok(Self { + library, + store, + session, + learning, + kind, + presentation: None, + completed_attempt_ids, + pending_commit: None, + commit_in_flight: None, + #[cfg(test)] + synchronous_commits: false, + save_error: None, + error: None, + board: BoardState::default(), + board_position: Chess::default(), + annotation_games, + repertoire_answers, + repertoire_keys, + lines, + line: 0, + next_line_banner: false, + displayed_node: None, + board_shown: false, + pending_automatic: None, + shown_prefix: None, + playback: None, + needs_prepare: true, + animation: DEFAULT_ANIMATION, + feedback: FEEDBACK, + ready_since: None, + last_move: None, + orientation, + jump: false, + alternative_revealed: false, + stopped: false, + exit_requested: false, + leave: false, + back_to_lines: false, + current_key: None, + tally: Tally::default(), + summary: None, + shown_state: State::Watch, + pending_sounds: Vec::new(), + #[cfg(test)] + visual_log: Vec::new(), + }) + } + + pub fn has_unsaved(&self) -> bool { + self.pending_commit.is_some() || self.save_error.is_some() + } + + pub fn target_available(&self) -> bool { + self.session.current_target().is_some() + } + + pub fn set_back_to_lines(&mut self, back_to_lines: bool) { + self.back_to_lines = back_to_lines; + } + + pub fn orientation(&self) -> Color { + self.orientation + } + + /// The finished session, for «10 more new». + pub fn snapshot(&self) -> &LearningSessionSnapshot { + &self.session + } + + #[cfg_attr(not(test), allow(dead_code))] + pub fn session_id(&self) -> &str { + self.session.id() + } + + fn is_finished(&self) -> bool { + self.session.phase == LearningSessionPhase::Finished + && self.playback.is_none() + && !self.has_unsaved() + } + + fn summary_visible(&self) -> bool { + (self.stopped || self.is_finished()) && !self.has_unsaved() + } + + fn can_input(&self) -> bool { + !self.has_unsaved() + && !self.stopped + && self.error.is_none() + && !self.needs_prepare + && self.playback.is_none() + && self.pending_automatic.is_none() + && self.session.current_target().is_some() + && matches!( + self.session.phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + | LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay + ) + } + + fn can_hint(&self) -> bool { + self.can_input() + && self.session.phase == LearningSessionPhase::AwaitingIndependent + && !self.session.current_is_new(&self.learning) + } + + fn tick_at(&mut self, now: Instant, animation: Duration, happened_at: i64) { + self.animation = animation; + self.poll_commit(now); + if self.stopped || self.has_unsaved() { + return; + } + if self.board_shown + && let Some(steps) = self.pending_automatic.take() + { + self.start_next_automatic(steps, now); + } + if self.needs_prepare { + self.prepare_presentation(now); + } + loop { + if self.stopped || self.has_unsaved() || self.error.is_some() { + return; + } + if self.needs_prepare { + self.prepare_presentation(now); + continue; + } + let Some(deadline) = self.playback_deadline() else { + return; + }; + if now < deadline { + return; + } + match self.playback { + Some(Playback::Wrong { .. } | Playback::Alternative { .. }) => { + self.finish_temporary_move(now, happened_at); + } + Some(Playback::Accepted { .. }) => self.finish_accepted(now), + Some(Playback::Automatic { .. }) => { + let id = unique_id(self.session.id()); + self.advance_context_with_id_at(id, now, happened_at); + } + None => return, + } + if !animation.is_zero() { + return; + } + } + } + + fn playback_deadline(&self) -> Option { + match &self.playback { + Some(Playback::Automatic { + started_at, + duration, + .. + }) + | Some(Playback::Accepted { + started_at, + duration, + .. + }) => Some(*started_at + *duration), + Some(Playback::Wrong { until, .. } | Playback::Alternative { until, .. }) => { + Some(*until) + } + None => None, + } + } + + fn prepare_presentation(&mut self, now: Instant) { + let presentation = match self + .session + .presentation_with_learning(&self.library, &self.learning) + { + Ok(presentation) => presentation, + Err(error) => { + self.error = Some(error.to_string()); + self.needs_prepare = false; + self.ready_since = None; + return; + } + }; + self.error = None; + self.needs_prepare = false; + self.presentation = Some(presentation.clone()); + let Some(ref current) = presentation.current_position else { + self.ready_since = None; + self.pending_automatic = None; + return; + }; + let key = self + .session + .current_target() + .map(|target| target.key.clone()); + if key != self.current_key { + self.current_key = key; + self.alternative_revealed = false; + self.track_line(); + } + // A following task may extend the line that is already on the board. Keep + // its context journal, but do not rewind and animate those same moves again. + // The complete path and repertoire must match; a transposed FEN is not enough. + if self.reuse_shown_context(&presentation, now) { + return; + } + self.shown_prefix = None; + if !presentation.automatic_context.is_empty() { + let mut steps = VecDeque::new(); + for step in presentation.automatic_context { + match VisualMove::from_context(&step) { + Ok(_) => steps.push_back(step), + Err(error) => { + self.error = Some(error); + self.ready_since = None; + return; + } + } + } + self.ready_since = None; + let Some(first) = steps.front() else { + self.error = Some("automatic context has no visual step".to_owned()); + return; + }; + self.board_position = match parse_position(&first.from) { + Ok(position) => position, + Err(error) => { + self.error = Some(error); + return; + } + }; + self.set_displayed_context(self.session.context_index); + self.board_shown = false; + self.pending_automatic = Some(steps); + self.playback = None; + self.last_move = None; + return; + } + self.pending_automatic = None; + let position = match parse_position(current) { + Ok(position) => position, + Err(error) => { + self.error = Some(error); + self.ready_since = None; + return; + } + }; + if fen4(&self.board_position) != current.fen4 { + self.last_move = None; + } + self.board_position = position; + self.set_displayed_context(self.session.context_index); + self.playback = None; + self.next_line_banner = false; + match self.session.phase { + LearningSessionPhase::AwaitingIndependent + if self.session.current_is_new(&self.learning) => + { + // A new move is shown before it is asked (decision 2026-11-26). + self.ready_since = None; + let id = unique_id(self.session.id()); + self.preview_with_id_at(id, true, now, layout::now()); + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => { + self.ready_since = Some(now); + } + LearningSessionPhase::AwaitingReplayAfterError + | LearningSessionPhase::PreviewedReplay => { + self.ready_since = None; + } + phase => { + self.ready_since = None; + self.error = Some(format!( + "learning session has no playable position in {phase:?}" + )); + } + } + } + + /// The line of the current question (1-based), for a review. + fn track_line(&mut self) { + if self.kind == SessionKind::Daily { + return; + } + let Some(target) = self.session.current_target() else { + return; + }; + let Some(index) = self + .lines + .iter() + .position(|line| line.starts_with(&target.path)) + else { + return; + }; + let line = index + 1; + if line > self.line { + self.next_line_banner = self.line > 0; + self.line = line; + } + } + + fn reuse_shown_context(&mut self, presentation: &LearningPresentation, at: Instant) -> bool { + let Some(prefix) = &self.shown_prefix else { + return false; + }; + let Some(target) = self.session.current_target() else { + return false; + }; + let Some(remaining) = prefix.path.len().checked_sub(self.session.context_index) else { + return false; + }; + if remaining == 0 + || target.repertoire_id != prefix.repertoire_id + || !presentation.target_path.starts_with(&prefix.path) + // An independent context question must still be asked. Only reuse a + // prefix that the core explicitly allows to be automatic in full. + || presentation.automatic_context.len() < remaining + || presentation.automatic_context[remaining - 1].to.fen4 != fen4(&self.board_position) + { + return false; + } + // These moves are already visible. Preserve each AUTO_CONTEXT event, + // but commit the whole prefix once instead of rereading/writing all + // history and rebuilding the presentation once per old move. + self.commit_context_batch(remaining, at) + } + + /// Records `count` automatic moves of the current line at once (moves already on the + /// board, or skipped by the user). + fn commit_context_batch(&mut self, count: usize, at: Instant) -> bool { + let mut next_session = self.session.clone(); + let mut attempts = Vec::with_capacity(count); + let happened_at = layout::now(); + for _ in 0..count { + let id = unique_id(next_session.id()); + match next_session.advance_context_with_learning( + &self.library, + &self.learning, + id, + happened_at, + ) { + Ok(attempt) => attempts.push(attempt), + Err(error) => { + self.error = Some(error.to_string()); + return true; + } + } + } + if attempts.is_empty() { + return false; + } + self.session = next_session; + self.ready_since = None; + self.pending_commit = Some(PendingCommit { + attempts, + kind: CommitKind::ReusedContext, + target: None, + }); + self.persist_pending(at); + true + } + + /// «Skip»: the position of the question at once, the skipped moves recorded as + /// shown. + fn skip_context(&mut self, now: Instant) -> bool { + if self.has_unsaved() || self.stopped { + return false; + } + let (count, last) = match (&self.playback, &self.pending_automatic) { + ( + Some(Playback::Automatic { + current, remaining, .. + }), + _, + ) => ( + remaining.len() + 1, + remaining + .back() + .map(VisualMove::from_context) + .unwrap_or_else(|| Ok((**current).clone())), + ), + (None, Some(steps)) => match steps.back() { + Some(step) => (steps.len(), VisualMove::from_context(step)), + None => return false, + }, + _ => return false, + }; + let last = match last { + Ok(last) => last, + Err(error) => { + self.error = Some(error); + return false; + } + }; + self.playback = None; + self.pending_automatic = None; + if !self.commit_context_batch(count, now) { + return false; + } + self.board_position = last.after.clone(); + self.set_displayed_context(self.session.context_index); + self.last_move = Some((last.from, last.to)); + self.jump = true; + true + } + + fn start_next_automatic(&mut self, mut remaining: VecDeque, now: Instant) { + let Some(step) = remaining.pop_front() else { + self.needs_prepare = true; + self.prepare_presentation(now); + return; + }; + let current = match VisualMove::from_context(&step) { + Ok(current) => current, + Err(error) => { + self.error = Some(error); + return; + } + }; + self.board_position = current.after.clone(); + self.set_displayed_context(self.session.context_index + 1); + self.last_move = Some((current.from, current.to)); + self.playback = Some(Playback::Automatic { + current: Box::new(current.clone()), + remaining, + started_at: now, + duration: self.animation.div_f32(step.speed_factor.max(0.01) as f32), + }); + #[cfg(test)] + self.visual_log.push(current.uci.clone()); + self.queue_sound(Sound::Move); + } + + fn advance_context_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if self.has_unsaved() + || !matches!(self.playback, Some(Playback::Automatic { .. })) + || self.completed_attempt_ids.contains(&client_attempt_id) + { + return false; + } + let attempt = match self.session.advance_context_with_learning( + &self.library, + &self.learning, + client_attempt_id, + happened_at, + ) { + Ok(attempt) => attempt, + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + self.begin_commit(attempt, CommitKind::Context, now); + true + } + + fn finish_context(&mut self, now: Instant) { + let Some(Playback::Automatic { remaining, .. }) = self.playback.take() else { + self.error = Some("automatic context is missing its visual step".to_owned()); + return; + }; + self.start_next_automatic(remaining, now); + } + + fn play_move_at(&mut self, mv: Move, now: Instant, happened_at: i64) -> bool { + let id = unique_id(self.session.id()); + self.play_move_with_id_at(mv, id, now, happened_at) + } + + fn play_move_with_id_at( + &mut self, + mv: Move, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let Some(expected_uci) = self.session.current_expected_uci().map(str::to_owned) else { + return false; + }; + let before = self.board_position.clone(); + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let visual = VisualMove::new(uci.clone(), before, mv); + let phase = self.session.phase; + let independent = matches!( + phase, + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent + ); + let showing_new = self.session.showing_new; + let Some(target) = self.session.current_target().cloned() else { + return false; + }; + let Some(prefix) = target.path.get(..self.session.context_index) else { + return false; + }; + let mut path = prefix.to_vec(); + path.push(uci.clone()); + let shown_prefix = ShownPrefix { + repertoire_id: target.repertoire_id.clone(), + path, + }; + if !independent && uci != expected_uci { + let key = LearningItemKey::new(target.key.user_id.clone(), fen4(&visual.before), &uci); + if self.repertoire_answers.contains(&key) { + self.show_repertoire_alternative(visual, &shown_prefix, now); + return true; + } + self.set_displayed_path(Some(&shown_prefix)); + self.start_playback(visual, PlayOutcome::WrongReplay, now); + return true; + } + let response_time_ms = independent.then(|| { + self.ready_since.map_or(0, |ready| { + u64::try_from(now.saturating_duration_since(ready).as_millis()).unwrap_or(u64::MAX) + }) + }); + let attempt = match self.session.play_uci_with_learning_answers( + &self.library, + &self.learning, + &self.repertoire_answers, + &uci, + client_attempt_id, + happened_at, + response_time_ms, + ) { + Ok(attempt) => attempt, + Err(LearningSessionError::RepertoireAlternative { .. }) => { + self.show_repertoire_alternative(visual, &shown_prefix, now); + return true; + } + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + let outcome = match attempt.event_type { + TrainingEventType::CorrectIndependent => PlayOutcome::CorrectIndependent, + TrainingEventType::IncorrectIndependent => PlayOutcome::WrongIndependent, + TrainingEventType::ReplayAfterError => PlayOutcome::ReplayAfterError, + TrainingEventType::AutoContext if showing_new => PlayOutcome::NewPlayed, + TrainingEventType::AutoContext => PlayOutcome::PreviewedReplay, + TrainingEventType::Previewed | TrainingEventType::IllegalMove => { + self.error = Some("legal board input produced a non-play event".to_owned()); + return false; + } + }; + // The credited question: the played answer itself when it was another + // pending answer of this position. + let credited = if attempt.item_key() == target.key { + Some(target) + } else { + self.session + .queue + .iter() + .find(|candidate| candidate.key == attempt.item_key()) + .cloned() + }; + // The legal move is visible immediately, including while its event is + // being saved. Input stays blocked until persistence acknowledges it. + // In particular a dropped piece must not jump back to its source square. + self.board_position = visual.after.clone(); + self.set_displayed_path(Some(&shown_prefix)); + self.last_move = Some((visual.from, visual.to)); + self.begin_commit_for( + attempt, + CommitKind::Play { + visual: Box::new(visual), + outcome, + shown_prefix, + }, + credited, + now, + ); + true + } + + fn play_uci_with_id_at( + &mut self, + uci: &str, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_input() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let mv = uci + .parse::() + .ok() + .and_then(|uci| uci.to_move(&self.board_position).ok()); + let Some(mv) = mv else { + return false; + }; + self.play_move_with_id_at(mv, client_attempt_id, now, happened_at) + } + + fn start_playback(&mut self, visual: VisualMove, outcome: PlayOutcome, now: Instant) { + self.ready_since = None; + self.board_position = visual.after.clone(); + self.last_move = Some((visual.from, visual.to)); + match outcome { + PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay => { + self.playback = Some(Playback::Wrong { + visual: Box::new(visual), + until: now + WRONG_SHOWN, + }); + self.queue_sound(Sound::Wrong); + } + PlayOutcome::CorrectIndependent + | PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay + | PlayOutcome::NewPlayed => { + self.playback = Some(Playback::Accepted { + started_at: now, + duration: self.animation + self.feedback, + outcome, + }); + self.queue_sound(Sound::Move); + } + } + } + + fn show_repertoire_alternative( + &mut self, + visual: VisualMove, + shown_prefix: &ShownPrefix, + now: Instant, + ) { + self.ready_since = None; + self.board_position = visual.after.clone(); + self.set_displayed_path(Some(shown_prefix)); + self.last_move = Some((visual.from, visual.to)); + self.playback = Some(Playback::Alternative { + visual: Box::new(visual), + until: now + WRONG_SHOWN.max(self.animation), + }); + } + + fn finish_temporary_move(&mut self, now: Instant, happened_at: i64) { + let (visual, alternative) = match self.playback.take() { + Some(Playback::Wrong { visual, .. }) => (visual, false), + Some(Playback::Alternative { visual, .. }) => (visual, true), + _ => return, + }; + self.board_position = visual.before; + self.last_move = None; + self.needs_prepare = true; + self.prepare_presentation(now); + // Another move of the repertoire is no mistake, but «now play {san}» shows the + // answer: it is recorded as shown, not as known. + if alternative && self.session.phase == LearningSessionPhase::AwaitingIndependent { + self.alternative_revealed = true; + let id = unique_id(self.session.id()); + self.preview_with_id_at(id, false, now, happened_at); + } else if alternative { + self.alternative_revealed = true; + } + } + + fn finish_accepted(&mut self, now: Instant) { + let Some(Playback::Accepted { outcome, .. }) = self.playback.take() else { + return; + }; + if outcome == PlayOutcome::CorrectIndependent + && self.session.phase == LearningSessionPhase::Finished + { + self.queue_sound(Sound::Success); + } + self.alternative_revealed = false; + self.needs_prepare = true; + self.prepare_presentation(now); + } + + fn request_hint_with_id_at( + &mut self, + client_attempt_id: String, + now: Instant, + happened_at: i64, + ) -> bool { + if !self.can_hint() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + self.preview_with_id_at(client_attempt_id, false, now, happened_at) + } + + fn preview_with_id_at( + &mut self, + client_attempt_id: String, + new: bool, + now: Instant, + happened_at: i64, + ) -> bool { + if self.has_unsaved() || self.completed_attempt_ids.contains(&client_attempt_id) { + return false; + } + let target = self.session.current_target().cloned(); + let result = if new { + self.session.preview_new(client_attempt_id, happened_at) + } else { + self.session.preview(client_attempt_id, happened_at) + }; + let attempt = match result { + Ok(Some(attempt)) => attempt, + Ok(None) => return false, + Err(error) => { + self.error = Some(error.to_string()); + return false; + } + }; + self.board.clear(); + self.begin_commit_for(attempt, CommitKind::Preview { new }, target, now); + true + } + + fn begin_commit(&mut self, attempt: TrainingAttempt, kind: CommitKind, now: Instant) { + self.begin_commit_for(attempt, kind, None, now); + } + + fn begin_commit_for( + &mut self, + attempt: TrainingAttempt, + kind: CommitKind, + target: Option, + now: Instant, + ) { + if self.pending_commit.is_some() { + self.save_error = + Some("another learning event is still waiting to be saved".to_owned()); + return; + } + self.pending_commit = Some(PendingCommit { + attempts: vec![attempt], + kind, + target, + }); + self.persist_pending(now); + } + + fn persist_pending(&mut self, _now: Instant) { + let Some(pending) = self.pending_commit.clone() else { + return; + }; + if self.commit_in_flight.is_some() { + return; + } + #[cfg(test)] + if self.synchronous_commits { + let result = self + .store + .apply_attempts_and_session(pending.attempts.clone(), &mut self.session) + .map_err(|error| error.to_string()); + self.finish_commit(result, _now); + return; + } + let store = self.store.clone(); + let mut session = self.session.clone(); + let (tx, rx) = mpsc::channel(); + self.commit_in_flight = Some(rx); + self.save_error = None; + if let Err(error) = crate::platform::spawn("learning-save-attempt", move || { + let result = store + .apply_attempts_and_session(pending.attempts, &mut session) + .map_err(|error| error.to_string()); + let _ = tx.send(result); + }) { + self.commit_in_flight = None; + self.save_error = Some(error.to_string()); + self.ready_since = None; + } + } + + fn poll_commit(&mut self, now: Instant) { + let Some(receiver) = &self.commit_in_flight else { + return; + }; + let result = match receiver.try_recv() { + Ok(result) => result, + Err(mpsc::TryRecvError::Empty) => return, + Err(mpsc::TryRecvError::Disconnected) => { + Err("learning save worker disconnected".to_owned()) + } + }; + self.commit_in_flight = None; + self.finish_commit(result, now); + } + + fn finish_commit(&mut self, result: Result, now: Instant) { + let Some(pending) = self.pending_commit.clone() else { + return; + }; + match result { + Ok(persisted) => { + let duplicate = persisted.application == AttemptApplication::Duplicate; + self.learning = persisted.learning; + self.session = persisted.session; + self.completed_attempt_ids.extend( + pending + .attempts + .iter() + .map(|attempt| attempt.client_attempt_id.clone()), + ); + self.pending_commit = None; + self.save_error = None; + if duplicate { + self.playback = None; + self.shown_prefix = None; + self.ready_since = None; + self.needs_prepare = true; + self.prepare_presentation(now); + self.finish_exit(); + return; + } + self.count(&pending); + match pending.kind { + CommitKind::Context => self.finish_context(now), + CommitKind::ReusedContext => self.needs_prepare = true, + CommitKind::Play { + visual, + outcome, + shown_prefix, + } => { + self.shown_prefix = (!matches!( + outcome, + PlayOutcome::WrongIndependent | PlayOutcome::WrongReplay + )) + .then_some(shown_prefix); + self.start_playback(*visual, outcome, now); + } + CommitKind::Preview { .. } => { + self.needs_prepare = true; + self.prepare_presentation(now); + } + } + self.finish_exit(); + } + Err(error) => { + self.save_error = Some(error.to_string()); + self.ready_since = None; + } + } + } + + /// The session's result counts recorded events only. + fn count(&mut self, pending: &PendingCommit) { + let target = pending.target.clone(); + match &pending.kind { + CommitKind::Play { outcome, .. } => match outcome { + PlayOutcome::CorrectIndependent => { + if target + .as_ref() + .is_none_or(|target| !self.tally.missed_key(&target.key)) + { + self.tally.first_time += 1; + } + } + PlayOutcome::WrongIndependent => { + self.tally.mistakes += 1; + self.tally.miss(target); + } + PlayOutcome::NewPlayed => self.tally.new_moves += 1, + PlayOutcome::WrongReplay + | PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay => {} + }, + CommitKind::Preview { new: false } => { + self.tally.hints += 1; + self.tally.miss(target); + } + CommitKind::Preview { new: true } | CommitKind::Context | CommitKind::ReusedContext => { + } + } + } + + fn retry_pending(&mut self, now: Instant) { + if self.pending_commit.is_some() { + self.persist_pending(now); + } + } + + fn queue_sound(&mut self, sound: Sound) { + if sound == Sound::Move && self.pending_sounds.last() == Some(&Sound::Move) { + return; + } + self.pending_sounds.push(sound); + } + + /// Esc, «⬅», «× Finish»: every answer is already recorded, so no question; after + /// an answer the result shows what was done. + fn request_exit(&mut self, actions: &mut Vec) { + if self.summary_visible() { + actions.push(SessionAction::Back); + return; + } + if self.save_error.is_some() { + // «Finish» in S9 gives up the one answer that could not be saved. + self.pending_commit = None; + self.save_error = None; + self.commit_in_flight = None; + } + if self.has_unsaved() { + self.exit_requested = true; + return; + } + if self.tally.any() { + self.stop(); + } else { + actions.push(SessionAction::Back); + } + } + + fn stop(&mut self) { + self.stopped = true; + self.pending_automatic = None; + if let Some(Playback::Automatic { .. }) = self.playback { + self.playback = None; + } + self.ready_since = None; + } + + /// An exit asked while an answer was being saved. + fn finish_exit(&mut self) { + if std::mem::take(&mut self.exit_requested) { + if self.tally.any() { + self.stop(); + } else { + self.leave = true; + } + } + } + + fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() || crate::app::overlay_open(ui.ctx()) { + return; + } + let state = self.shown_state.clone(); + let more = self.more_new_count() > 0; + let busy = self.board.is_busy(); + let mut command = None; + ui.input_mut(|input| { + if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + || (!busy && input.consume_key(Modifiers::NONE, Key::Escape)) + { + command = Some("exit"); + } else if input.consume_key(Modifiers::NONE, Key::F) { + command = Some("flip"); + } else if input.consume_key(Modifiers::NONE, Key::H) { + command = Some("hint"); + } else if state == State::Summary && more && input.consume_key(Modifiers::NONE, Key::N) + { + command = Some("more"); + } else if matches!( + state, + State::Watch | State::NextLine | State::Summary | State::SaveError(_) + ) && (input.consume_key(Modifiers::NONE, Key::Enter) + || input.consume_key(Modifiers::NONE, Key::Space)) + { + command = Some("main"); + } + }); + match command { + Some("exit") => self.request_exit(actions), + Some("flip") => self.orientation = self.orientation.other(), + Some("hint") => { + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + Some("more") => actions.push(SessionAction::MoreNew), + Some("main") => self.main_action(&state, actions), + _ => {} + } + } + + fn main_action(&mut self, state: &State, actions: &mut Vec) { + match state { + State::Watch | State::NextLine => { + self.skip_context(Instant::now()); + } + State::Summary => actions.push(SessionAction::Back), + State::SaveError(_) => self.retry_pending(Instant::now()), + _ => {} + } + } + + fn board_animation_seconds(&mut self, settings: &Settings) -> f32 { + if self.pending_automatic.is_some() || std::mem::take(&mut self.jump) { + return 0.0; + } + match &self.playback { + Some(Playback::Automatic { duration, .. }) => duration.as_secs_f32(), + _ => settings.animation.seconds(), + } + } + + fn set_displayed_context(&mut self, played: usize) { + let prefix = self.session.current_target().and_then(|target| { + Some(ShownPrefix { + repertoire_id: target.repertoire_id.clone(), + path: target.path.get(..played)?.to_vec(), + }) + }); + self.set_displayed_path(prefix.as_ref()); + } + + fn set_displayed_path(&mut self, prefix: Option<&ShownPrefix>) { + self.displayed_node = prefix.and_then(|prefix| { + let game = self.annotation_games.get(&prefix.repertoire_id)?; + let at = layout::node_at(game, &prefix.path)?; + Some((prefix.repertoire_id.clone(), at)) + }); + } + + /// The node on the board, when the board really shows it. + fn shown_node(&self) -> Option<(&Game, NodeId)> { + let (id, at) = self.displayed_node.as_ref()?; + let game = self.annotation_games.get(id)?; + // A visual wrong move outside the source tree must never inherit the + // expected move's badge or arrows merely because the task advanced. + (game.position(*at)? == &self.board_position).then_some((game, *at)) + } + + fn displayed_annotations(&self) -> BoardAnnotations { + match self.shown_node() { + Some((game, at)) => pgn_annotations_at(game, at), + None => BoardAnnotations::default(), + } + } + + /// The asked move's node in the PGN. + fn expected_node(&self) -> Option<(&Game, NodeId)> { + let target = self.session.current_target()?; + let game = self.annotation_games.get(&target.repertoire_id)?; + let path = target.path.get(..=self.session.context_index)?; + Some((game, layout::node_at(game, path)?)) + } + + fn expected_text(&self) -> String { + self.expected_node() + .and_then(|(game, node)| layout::move_text(game, node)) + .unwrap_or_default() + } + + /// «4. Ba4 !» of the move just played. + fn played_text(&self, dark: bool) -> String { + let Some((game, node)) = self.shown_node() else { + return String::new(); + }; + let mut text = layout::move_text(game, node).unwrap_or_default(); + if let Some((symbol, _)) = layout::assessment(game, node, dark) { + text.push_str(symbol); + } + text + } + + /// The move shown by an arrow: revealed by the core, or a new move about to be shown. + fn revealed_uci(&self) -> Option { + if self.playback.is_some() || self.pending_automatic.is_some() { + return None; + } + if let Some(uci) = self + .presentation + .as_ref() + .and_then(|presentation| presentation.revealed_move.clone()) + && self.session.phase != LearningSessionPhase::AwaitingIndependent + { + return Some(uci); + } + matches!(self.shown_state, State::New) + .then(|| self.session.current_expected_uci().map(str::to_owned)) + .flatten() + } + + fn state(&self) -> Option { + if let Some(error) = &self.save_error { + return Some(State::SaveError(error.clone())); + } + if let Some(error) = &self.error { + return Some(State::Failed(error.clone())); + } + if self.summary_visible() { + return Some(State::Summary); + } + match &self.playback { + Some(Playback::Automatic { .. }) => return Some(self.watch()), + Some(Playback::Wrong { .. }) => return Some(State::Wrong), + Some(Playback::Alternative { .. }) => return Some(State::Alternative), + Some(Playback::Accepted { outcome, .. }) => { + return Some(match outcome { + PlayOutcome::CorrectIndependent => State::Correct, + PlayOutcome::NewPlayed => State::NewDone, + PlayOutcome::ReplayAfterError + | PlayOutcome::PreviewedReplay + | PlayOutcome::WrongIndependent + | PlayOutcome::WrongReplay => State::GotIt, + }); + } + None => {} + } + if self.pending_automatic.is_some() { + return Some(self.watch()); + } + if let Some(pending) = &self.pending_commit { + return match pending.kind { + CommitKind::Preview { new: true } => Some(State::New), + // Between moves: the card keeps what it said. + _ => None, + }; + } + if self.needs_prepare { + return None; + } + Some(match self.session.phase { + LearningSessionPhase::AwaitingIndependent + if self.session.current_is_new(&self.learning) => + { + State::New + } + LearningSessionPhase::AwaitingIndependent + | LearningSessionPhase::AwaitingContextIndependent => self.yours(), + LearningSessionPhase::AwaitingReplayAfterError => State::Wrong, + LearningSessionPhase::PreviewedReplay if self.session.showing_new => State::New, + LearningSessionPhase::PreviewedReplay if self.alternative_revealed => { + State::Alternative + } + LearningSessionPhase::PreviewedReplay => State::Hint, + LearningSessionPhase::AdvancingContext => self.watch(), + LearningSessionPhase::Finished => State::Summary, + }) + } + + fn watch(&self) -> State { + if self.next_line_banner { + State::NextLine + } else { + State::Watch + } + } + + /// S3, or S3a when another answer of this position was already played. + fn yours(&self) -> State { + let position = fen4(&self.board_position); + let played: Vec = self + .session + .completed_keys + .iter() + .filter(|key| key.position_fen4 == position && self.repertoire_answers.contains(key)) + .filter_map(|key| { + let mv = key + .expected_uci + .parse::() + .ok()? + .to_move(&self.board_position) + .ok()?; + let san = chess_core::shakmaty::san::San::from_move(&self.board_position, mv); + Some(crate::san::show(&san.to_string()).into_owned()) + }) + .collect(); + if played.is_empty() { + State::Yours + } else { + State::YoursMore(played.join(", ")) + } + } + + fn more_new_count(&self) -> usize { + if self.kind != SessionKind::Daily { + return 0; + } + self.summary.as_ref().map_or(0, |summary| summary.more_new) + } + + fn compute_summary(&mut self) { + if self.summary.is_some() { + return; + } + let items: HashMap<&LearningItemKey, &LearningItem> = self + .learning + .items + .iter() + .map(|item| (&item.key, item)) + .collect(); + let today = layout::end_of_today(); + let now = layout::now(); + let mut due_today = 0usize; + let mut next: Option = None; + let mut unseen = 0usize; + for key in &self.repertoire_keys { + match items.get(key) { + Some(item) if item.introduced => { + if item.is_due(today) { + due_today += 1; + } else if let Some(at) = item.next_review_at { + next = Some(next.map_or(at, |old| old.min(at))); + } + } + _ => unseen += 1, + } + } + let next_review = if due_today > 0 { + trf("today, {n} more", &[("n", &due_today)]) + } else { + next.map(|at| layout::when(at, now)).unwrap_or_default() + }; + self.summary = Some(Summary { + next_review, + more_new: unseen.min(layout::NEW_PER_SESSION), + }); + } + + fn board_ui(&mut self, ui: &mut Ui, settings: &Settings) { + let interactive = self.can_input(); + let annotations = self.displayed_annotations(); + let mut arrows = annotations.arrows; + if let Some(mv) = self.revealed_uci().and_then(|uci| { + uci.parse::() + .ok() + .and_then(|uci| uci.to_move(&self.board_position).ok()) + }) { + arrows.push(Arrow { + from: mv.from().unwrap_or_else(|| mv.to()), + to: crate::board::ui_target(&mv), + color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), + weight: 1.0, + }); + } + let alert = match &self.playback { + Some(Playback::Wrong { visual, .. }) => Some((visual.from, visual.to)), + _ => None, + }; + let animation = self.board_animation_seconds(settings); + let played = BoardView { + pos: &self.board_position, + orientation: self.orientation, + last_move: self.last_move, + arrows: &arrows, + circles: &annotations.circles, + badge: annotations.badge, + interactive, + show_coords: settings.show_coords, + theme: settings.board_theme.theme(), + pieces: settings.piece_set, + animation, + premove: None, + auto_queen: false, + alert, + } + .show(ui, &mut self.board); + if let Some(mv) = played { + self.play_move_at(mv, Instant::now(), layout::now()); + } + self.board_shown = true; + } + + /// The card's texts: title, instruction, title colour. + fn card_texts(&self, state: &State, dark: bool) -> (String, String, Option) { + let dash = |s: &str| s.to_owned(); + let review = self.kind != SessionKind::Daily; + match state { + State::Watch => ( + dash(tr("Watch")), + dash(tr("Moves up to your next question")), + None, + ), + State::NextLine => ( + dash(tr("Next line")), + trf("{k} of {n}", &[("k", &self.line), ("n", &self.lines.len())]), + None, + ), + State::New => ( + dash(tr("New move")), + trf( + "Play {san} — it is shown by the arrow", + &[("san", &self.expected_text())], + ), + None, + ), + State::Yours => ( + dash(tr("Your move")), + dash(tr("Play the move from your repertoire")), + None, + ), + State::YoursMore(played) => ( + dash(tr("Your move")), + trf("One more move of yours here, not {san}", &[("san", played)]), + None, + ), + State::Correct => ( + dash(tr("Correct!")), + self.played_text(dark), + crate::notation::assessment_text_color(chess_core::Nag(1), dark), + ), + State::NewDone => (dash(tr("New move")), self.played_text(dark), None), + State::Wrong => ( + dash(tr("Not this move")), + trf("Correct: {san}. Play it", &[("san", &self.expected_text())]), + None, + ), + State::Alternative => ( + dash(tr("This one is in your repertoire too")), + trf( + "Now the other one: play {san}", + &[("san", &self.expected_text())], + ), + None, + ), + State::GotIt => ( + dash(tr("Got it")), + if review { + self.played_text(dark) + } else { + trf( + "{move} will come back in this session", + &[("move", &self.played_text(dark))], + ) + }, + None, + ), + State::Hint => ( + dash(tr("Hint")), + if review { + trf("Play {san}", &[("san", &self.expected_text())]) + } else { + trf( + "Play {san}. It will come back in this session", + &[("san", &self.expected_text())], + ) + }, + None, + ), + State::SaveError(error) => { + (dash(tr("Could not save your answer")), error.clone(), None) + } + State::Failed(error) => ( + dash(tr("Could not continue the session")), + error.clone(), + None, + ), + State::Summary => ( + dash(if self.stopped { + tr("Session stopped") + } else { + tr("Session complete") + }), + dash(tr("Everything is saved")), + None, + ), + } + } + + fn counter(&self, state: &State) -> (String, &'static str) { + match &self.kind { + SessionKind::Daily => { + let left = if matches!(state, State::Summary) && !self.stopped { + 0 + } else { + self.session.remaining() + }; + (left.to_string(), tr("left")) + } + SessionKind::ReviewAll | SessionKind::Branch { .. } => { + let k = if self.is_finished() { + self.lines.len() + } else { + self.line.max(1).min(self.lines.len()) + }; + (format!("{k}/{}", self.lines.len()), tr("line")) + } + } + } + + fn state_card(&self, ui: &mut Ui, state: &State) { + let dark = ui.visuals().dark_mode; + let (title, instruction, title_color) = self.card_texts(state, dark); + let active = matches!(state, State::New | State::Yours | State::YoursMore(_)); + let alert = matches!(state, State::Wrong | State::SaveError(_) | State::Failed(_)); + let (count, label) = self.counter(state); + show_card( + ui, + &CardView { + title, + instruction, + title_color, + active, + alert, + count, + label, + }, + ); + } + + /// Block D: the comment of the last move on the board (in S2, S5, S7 already of + /// the asked move), or the nearest earlier one of the line. + fn comment(&self, ui: &mut Ui, state: &State) { + let start = if matches!( + state, + State::New | State::Wrong | State::Hint | State::Alternative + ) { + self.expected_node() + } else { + self.shown_node() + }; + let Some((game, start)) = start else { + return; + }; + let dark = ui.visuals().dark_mode; + let mut path = game.path(start); + while let Some(node) = path.pop() { + let Some(data) = game.node(node) else { + continue; + }; + let text = crate::notation::comment_text(data.comments_after()); + if text.trim().is_empty() { + continue; + } + egui::ScrollArea::vertical() + .id_salt("opening_comment") + .auto_shrink([false, false]) + .show(ui, |ui| { + if let Some(label) = layout::move_text(game, node) { + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 2.0; + ui.label(RichText::new(label).strong()); + if let Some((symbol, color)) = layout::assessment(game, node, dark) { + ui.label(RichText::new(symbol).strong().color(color)); + } + }); + } + ui.add(egui::Label::new(text).wrap()); + }); + return; + } + } + + fn summary_body(&self, ui: &mut Ui) { + let row = |ui: &mut Ui, label: &str, value: String| { + ui.allocate_ui_with_layout( + vec2(ui.available_width(), 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + let width = (ui.available_width() - 60.0).max(0.0); + ui.allocate_ui_with_layout( + vec2(width, 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| layout::line(ui, label), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + layout::line(ui, RichText::new(value).strong()); + }); + }, + ); + }; + egui::ScrollArea::vertical() + .id_salt("opening_summary") + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + if self.kind != SessionKind::Daily { + let k = if self.stopped { + self.line.saturating_sub(1) + } else { + self.lines.len() + }; + row( + ui, + tr("Lines reviewed"), + trf("{k} of {n}", &[("k", &k), ("n", &self.lines.len())]), + ); + } + row( + ui, + tr("Correct first time"), + self.tally.first_time.to_string(), + ); + row(ui, tr("Mistakes"), self.tally.mistakes.to_string()); + if self.tally.hints > 0 { + row(ui, tr("Hints"), self.tally.hints.to_string()); + } + if self.tally.new_moves > 0 { + row( + ui, + tr("New moves learned"), + self.tally.new_moves.to_string(), + ); + } + ui.add_space(4.0); + ui.separator(); + ui.add_space(4.0); + if let Some(summary) = &self.summary + && !summary.next_review.is_empty() + { + row(ui, tr("Next review"), summary.next_review.clone()); + } + if self.tally.missed.is_empty() { + return; + } + ui.add_space(8.0); + ui.label(RichText::new(tr("Moves to remember")).strong()); + ui.add_space(2.0); + for target in self.tally.missed.iter().take(REMEMBER_ROWS) { + let Some(game) = self.annotation_games.get(&target.repertoire_id) else { + continue; + }; + let Some(node) = layout::node_at(game, &target.path) else { + continue; + }; + let after = game + .parent(node) + .and_then(|parent| layout::move_text(game, parent)); + ui.allocate_ui_with_layout( + vec2(ui.available_width(), 22.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.label( + RichText::new(layout::move_text(game, node).unwrap_or_default()) + .strong(), + ); + if let Some(after) = after { + layout::line( + ui, + RichText::new(trf("after {path}", &[("path", &after)])).weak(), + ); + } + }, + ); + } + if self.tally.missed.len() > REMEMBER_ROWS { + ui.label( + RichText::new(trf( + "and {k} more", + &[("k", &(self.tally.missed.len() - REMEMBER_ROWS))], + )) + .weak(), + ); + } + }); + } + + fn side(&mut self, ui: &mut Ui, state: &State, actions: &mut Vec) { + let opening = self + .shown_node() + .map(|(game, node)| layout::opening_text(game, node)) + .unwrap_or_default(); + let (left, right) = match state { + State::Summary => { + let more = self.more_new_count(); + ( + (more > 0).then(|| { + ( + if more == layout::NEW_PER_SESSION { + tr("10 more new (N)").to_owned() + } else { + trf("{n} more new (N)", &[("n", &more)]) + }, + true, + ) + }), + Some(( + if self.back_to_lines { + tr("To lines (Enter)") + } else { + tr("To repertoires (Enter)") + } + .to_owned(), + true, + )), + ) + } + State::SaveError(_) => ( + Some((tr("Finish").to_owned(), true)), + Some((tr("Try again").to_owned(), true)), + ), + State::Watch | State::NextLine => ( + Some((tr("Hint (H)").to_owned(), false)), + Some((tr("Skip (Enter)").to_owned(), false)), + ), + _ => (Some((tr("Hint (H)").to_owned(), self.can_hint())), None), + }; + let clicked = side_panel( + ui, + |ui| self.state_card(ui, state), + &opening, + |ui| { + if *state == State::Summary { + self.summary_body(ui); + } else { + self.comment(ui, state); + } + }, + left, + right, + *state == State::Summary || matches!(state, State::SaveError(_)), + ); + match clicked { + Some(Clicked::Left) => match state { + State::Summary => actions.push(SessionAction::MoreNew), + State::SaveError(_) => self.request_exit(actions), + _ => { + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + }, + Some(Clicked::Right) => self.main_action(state, actions), + Some(Clicked::Flip) => self.orientation = self.orientation.other(), + Some(Clicked::Finish) => self.request_exit(actions), + None => {} + } + } + + pub fn show(&mut self, ui: &mut Ui, settings: &Settings, name: &str) -> Vec { + let animation = Duration::from_secs_f32(settings.animation.seconds()); + self.tick_at(Instant::now(), animation, layout::now()); + if self.commit_in_flight.is_some() { + ui.ctx().request_repaint_after(Duration::from_millis(16)); + } else if let Some(deadline) = self.playback_deadline() { + ui.ctx() + .request_repaint_after(deadline.saturating_duration_since(Instant::now())); + } else if self.needs_prepare || self.pending_automatic.is_some() { + ui.ctx().request_repaint(); + } + if let Some(state) = self.state() { + self.shown_state = state; + } + if self.shown_state == State::Summary { + self.compute_summary(); + } + let mut actions = Vec::new(); + self.keyboard(ui, &mut actions); + let state = self.shown_state.clone(); + let subtitle = self.kind.subtitle(self.session.stats_scope.side); + let back = if ui.available_width() < 600.0 { + "⬅" + } else if self.back_to_lines { + tr("⬅ Lines") + } else { + tr("⬅ Repertoires") + }; + let mut header = (false, false); + layout::screen( + ui, + self, + |_, ui| header = crate::widgets::section_header_sub(ui, back, name, &subtitle), + |this, ui| this.side(ui, &state, &mut actions), + |this, ui| this.board_ui(ui, settings), + ); + if header.0 { + self.request_exit(&mut actions); + } + if header.1 { + actions.push(SessionAction::OpenSettings); + } + if std::mem::take(&mut self.leave) { + actions.push(SessionAction::Back); + } + actions.extend(self.pending_sounds.drain(..).map(SessionAction::Sound)); + actions + } + + pub fn debug_settle(&mut self) { + // Only this explicit QA hook waits. Normal frames poll workers without blocking. + let deadline = Instant::now() + Duration::from_secs(10); + loop { + if self.commit_in_flight.is_some() { + self.poll_commit(Instant::now()); + if Instant::now() >= deadline { + return; + } + if self.commit_in_flight.is_some() { + std::thread::sleep(Duration::from_millis(1)); + continue; + } + } + if self.has_unsaved() { + return; + } + if self.pending_automatic.is_some() { + self.board_shown = true; + } + let at = self + .playback_deadline() + .map_or_else(Instant::now, |at| at.max(Instant::now())); + self.tick_at(at, Duration::ZERO, layout::now()); + if self.commit_in_flight.is_none() + && self.pending_automatic.is_none() + && !self.needs_prepare + && self.playback_deadline().is_none() + { + return; + } + if Instant::now() >= deadline { + return; + } + } + } + + pub fn debug_hint(&mut self) { + if self.needs_prepare { + self.debug_settle(); + } + let id = unique_id(self.session.id()); + self.request_hint_with_id_at(id, Instant::now(), layout::now()); + } + + /// QA (`CP_REPERTOIRE_MOVES`): UCI moves as from the board; `hint`, `settle`, + /// `skip`, `stop` (Esc), `answer` (the expected move), `wrong` (a move not in the + /// repertoire). + pub fn debug_moves(&mut self, moves: &str) { + if self.needs_prepare { + self.debug_settle(); + } + for text in moves.split_whitespace() { + match text { + "hint" => self.debug_hint(), + "settle" | "wait" => self.debug_settle(), + "skip" => { + self.skip_context(Instant::now()); + } + "stop" => { + let mut actions = Vec::new(); + self.request_exit(&mut actions); + } + "answer" => { + if let Some(uci) = self.session.current_expected_uci().map(str::to_owned) { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(&uci, id, Instant::now(), layout::now()); + } + } + "wrong" => { + if let Some(uci) = self.debug_wrong_move() { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(&uci, id, Instant::now(), layout::now()); + } + } + _ => { + let id = unique_id(self.session.id()); + self.play_uci_with_id_at(text, id, Instant::now(), layout::now()); + } + } + } + } + + /// A legal move that is no answer of the repertoire here. + fn debug_wrong_move(&self) -> Option { + use chess_core::shakmaty::Position; + let position = fen4(&self.board_position); + let user = self.session.current_target()?.key.user_id.clone(); + self.board_position + .legal_moves() + .into_iter() + .find_map(|mv| { + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let key = LearningItemKey::new(user.clone(), position.clone(), &uci); + (!self.repertoire_answers.contains(&key)).then_some(uci) + }) + } +} + +/// «Preparing…» (S0): the session's screen before the session exists, so the board +/// and the panel do not move when it comes. +pub fn show_preparing( + ui: &mut Ui, + settings: &Settings, + board: &mut BoardState, + view: &PreparingView<'_>, +) -> Vec { + let mut actions = Vec::new(); + if !ui.ctx().egui_wants_keyboard_input() + && !crate::app::overlay_open(ui.ctx()) + && ui.input_mut(|input| { + input.consume_key(Modifiers::NONE, Key::Escape) + || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) + }) + { + actions.push(SessionAction::Back); + } + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + view.back + }; + let mut header = (false, false); + layout::screen( + ui, + board, + |_, ui| header = crate::widgets::section_header_sub(ui, back, view.name, view.subtitle), + |_, ui| { + let clicked = side_panel( + ui, + |ui| { + show_card( + ui, + &CardView { + title: tr("Preparing…").to_owned(), + instruction: String::new(), + title_color: None, + active: false, + alert: false, + count: "—".to_owned(), + label: if view.lines { tr("line") } else { tr("left") }, + }, + ) + }, + "", + |_| {}, + Some((tr("Hint (H)").to_owned(), false)), + None, + false, + ); + if clicked == Some(Clicked::Finish) { + actions.push(SessionAction::Back); + } + }, + |board, ui| { + layout::still_board( + ui, + board, + settings, + view.position, + view.orientation, + view.last_move, + &BoardAnnotations::default(), + ) + }, + ); + if header.0 { + actions.push(SessionAction::Back); + } + if header.1 { + actions.push(SessionAction::OpenSettings); + } + actions +} + +pub struct PreparingView<'a> { + pub name: &'a str, + pub subtitle: &'a str, + pub back: &'a str, + pub position: &'a Chess, + pub orientation: Color, + pub last_move: Option<(Square, Square)>, + /// A review: the counter counts lines. + pub lines: bool, +} + +struct CardView { + title: String, + instruction: String, + title_color: Option, + active: bool, + alert: bool, + count: String, + label: &'static str, +} + +/// Block A: two lines on the left, the counter on the right; always 64 pt. +fn show_card(ui: &mut Ui, view: &CardView) { + layout::fixed_block(ui, CARD_H, |ui| { + let frame = layout::card(ui, view.active, view.alert); + let inner = vec2(ui.available_width() - 20.0, CARD_H - 12.0); + frame.show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.horizontal(|ui| { + let counter_w = 64.0; + ui.allocate_ui_with_layout( + vec2((ui.available_width() - counter_w).max(0.0), inner.y), + egui::Layout::top_down(egui::Align::Min), + |ui| { + ui.spacing_mut().item_spacing.y = 2.0; + let mut title = RichText::new(&view.title).strong().size(15.0); + if let Some(color) = view.title_color { + title = title.color(color); + } + layout::line(ui, title); + layout::line(ui, RichText::new(&view.instruction).size(13.0)); + }, + ); + ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + ui.label(RichText::new(&view.count).monospace().size(24.0)); + ui.label(RichText::new(view.label).weak().size(11.0)); + }); + }); + }); + }); +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Clicked { + Left, + Right, + Flip, + Finish, +} + +/// The session's panel (spec §4.1): A card · B opening · D comment or result · E +/// actions · F tool row; every block keeps its height in every state. +#[allow(clippy::too_many_arguments)] +fn side_panel( + ui: &mut Ui, + card: impl FnOnce(&mut Ui), + opening: &str, + body: impl FnOnce(&mut Ui), + left: Option<(String, bool)>, + right: Option<(String, bool)>, + right_primary: bool, +) -> Option { + let mut clicked = None; + let rect = ui.available_rect_before_wrap(); + let footer_h = TOOL_H + 12.0; + let footer = egui::Rect::from_min_max( + egui::pos2(rect.left(), (rect.bottom() - footer_h).max(rect.top())), + rect.max, + ); + let body_rect = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), footer.top())); + ui.scope_builder(egui::UiBuilder::new().max_rect(body_rect), |ui| { + ui.set_clip_rect(body_rect.intersect(ui.clip_rect())); + ui.spacing_mut().item_spacing.y = GAP; + ui.add_space(4.0); + card(ui); + layout::fixed_block(ui, LINE_H, |ui| { + layout::line(ui, RichText::new(opening).weak()); + }); + let rest = (ui.available_height() - ROW_H - GAP).max(0.0); + layout::fixed_block(ui, rest, body); + layout::fixed_block(ui, ROW_H, |ui| { + ui.horizontal(|ui| { + if let Some((label, enabled)) = left { + let response = ui.add_enabled( + enabled, + egui::Button::new(label) + .truncate() + .min_size(vec2(LEFT_W.min(ui.available_width() / 2.0), ROW_H)), + ); + if response.clicked() { + clicked = Some(Clicked::Left); + } + } + if let Some((label, enabled)) = right { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let width = MAIN_W.min(ui.available_width()); + let response = if right_primary { + ui.add_enabled_ui(enabled, |ui| { + crate::widgets::primary_wide(ui, &label, width) + }) + .inner + } else { + ui.add_enabled( + enabled, + egui::Button::new(label) + .truncate() + .min_size(vec2(width, ROW_H)), + ) + }; + if response.clicked() { + clicked = Some(Clicked::Right); + } + }); + } + }); + }); + }); + ui.scope_builder(egui::UiBuilder::new().max_rect(footer), |ui| { + ui.separator(); + ui.horizontal(|ui| { + let icon = |s: &str| { + egui::Button::new(RichText::new(s).size(18.0)).min_size(vec2(0.0, TOOL_H)) + }; + if ui + .add(icon("🔃")) + .on_hover_text(tr("Flip board (F)")) + .clicked() + { + clicked = Some(Clicked::Flip); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .add( + egui::Button::new(RichText::new(tr("× Finish")).size(14.0)) + .min_size(vec2(0.0, TOOL_H)), + ) + .on_hover_text(tr("Finish the session (Esc)")) + .clicked() + { + clicked = Some(Clicked::Finish); + } + }); + }); + }); + clicked +} + +impl VisualMove { + fn from_context(step: &LearningContextStep) -> Result { + let before = parse_position(&step.from)?; + let mv = step + .uci + .parse::() + .ok() + .and_then(|uci| uci.to_move(&before).ok()) + .ok_or_else(|| format!("automatic context move {} is not legal", step.uci))?; + Ok(Self::new(step.uci.clone(), before, mv)) + } + + fn new(uci: String, before: Chess, mv: Move) -> Self { + use chess_core::shakmaty::Position; + let from = mv.from().unwrap_or_else(|| mv.to()); + let to = crate::board::ui_target(&mv); + let mut after = before.clone(); + after.play_unchecked(mv); + Self { + uci, + before, + after, + from, + to, + } + } +} + +fn parse_position(position: &trainer::repertoire::LearningPosition) -> Result { + position + .fen + .parse::() + .map_err(|error| error.to_string())? + .into_position(CastlingMode::Standard) + .map_err(|error| error.to_string()) +} + +fn unique_id(prefix: &str) -> String { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| duration.as_nanos()); + let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); + format!("{prefix}-{nanos:x}-{}-{sequence:x}", std::process::id()) +} + +#[cfg(test)] +#[path = "opening_session_tests.rs"] +mod tests; diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs new file mode 100644 index 0000000..6a2b614 --- /dev/null +++ b/apps/desktop/src/opening_session_tests.rs @@ -0,0 +1,2129 @@ +use std::path::PathBuf; + +use super::*; +use chess_core::shakmaty::Position; +use trainer::repertoire::{LearningStoreData, active_learning_memberships}; + +#[test] +fn status_growth_does_not_move_training_controls() { + let mut positions = Vec::new(); + for message in [ + "Your turn", + "Hint\nReplay the shown move\nNo independent success", + ] { + let ctx = egui::Context::default(); + let output = ctx.run_ui(egui::RawInput::default(), |ui| { + egui::CentralPanel::default().show(ui, |ui| { + layout::fixed_block(ui, 144.0, |ui| { + ui.label(message); + }); + positions.push(ui.button("Hint").rect.top()); + }); + }); + output.drop_without_applying_deltas(); + } + assert_eq!(positions[0], positions[1]); + assert!(positions[0] >= 144.0); +} + +const NOW: i64 = 1_800_000_000; +static NEXT_TEST: AtomicU64 = AtomicU64::new(1); + +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cp-opening-session-{}-{}-{name}", + std::process::id(), + NEXT_TEST.fetch_add(1, Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn store(&self) -> LearningStore { + LearningStore::new(self.0.join("learning.json")) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +struct Fixture { + _dir: TestDir, + library: Library, + scope: StatsScope, + store: LearningStore, + ui: OpeningSessionUi, +} + +impl Fixture { + /// A daily session asking exactly `due`: every other move of the side is known and + /// not due. + fn new(pgn: &str, side: LearningSide, due: &[&str], name: &str) -> Self { + Self::with(pgn, side, due, &[], name, SessionKind::Daily) + } + + /// `due` are due, `new` never shown, every other move known and not due. + fn with( + pgn: &str, + side: LearningSide, + due: &[&str], + new: &[&str], + name: &str, + kind: SessionKind, + ) -> Self { + let dir = TestDir::new(name); + let mut library = Library::default(); + let id = library + .create("Test", &chess_core::parse_str(pgn).game) + .unwrap(); + let scope = StatsScope::for_repertoire(id, side, NOW); + let mut learning = LearningData::default(); + for membership in active_learning_memberships(&library, &scope).unwrap() { + let uci = membership.key.expected_uci.as_str(); + if new.contains(&uci) { + continue; + } + let item = learning.ensure_item(membership.key.clone()); + item.introduced = true; + if due.contains(&uci) { + item.next_review_at = Some(NOW); + } else { + item.correct_streak = 1; + item.correct_count = 1; + item.last_correct_at = Some(NOW - 24 * 60 * 60); + item.next_review_at = Some(NOW + 10 * 24 * 60 * 60); + } + } + let bytes = serde_json::to_vec_pretty(&LearningStoreData { + learning, + ..LearningStoreData::default() + }) + .unwrap(); + std::fs::write(dir.0.join("learning.json"), bytes).unwrap(); + let store = dir.store(); + let mut ui = + OpeningSessionUi::new(library.clone(), store.clone(), scope.clone(), kind).unwrap(); + ui.board_shown = true; + ui.synchronous_commits = true; + ui.feedback = Duration::ZERO; + Self { + _dir: dir, + library, + scope, + store, + ui, + } + } + + fn attempts(&self) -> Vec { + self.store.load().unwrap().learning.attempts + } +} + +fn key_for(library: &Library, scope: &StatsScope, expected: &str) -> LearningItemKey { + active_learning_memberships(library, scope) + .unwrap() + .into_iter() + .find(|membership| membership.key.expected_uci == expected) + .unwrap() + .key +} + +fn normal() -> Duration { + Duration::from_millis(250) +} + +fn answer_current(f: &mut Fixture, at: Instant, happened_at: i64, id: &str) { + let expected = f.ui.session.current_expected_uci().unwrap().to_owned(); + assert!(f.ui.play_uci_with_id_at(&expected, id.to_owned(), at, happened_at,)); + tick_with_prime(&mut f.ui, at, Duration::ZERO, happened_at); +} + +fn board_frame(f: &mut Fixture, ctx: &egui::Context, time: f64, settings: &Settings) { + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 800.0), + )), + time: Some(time), + ..Default::default() + }, + |ui| f.ui.board_ui(ui, settings), + ) + .drop_without_applying_deltas(); +} + +fn tick_with_prime(ui: &mut OpeningSessionUi, at: Instant, animation: Duration, happened_at: i64) { + ui.tick_at(at, animation, happened_at); + if ui.pending_automatic.is_none() { + return; + } + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let settings = Settings::default(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(800.0, 800.0), + )), + time: Some(0.0), + ..Default::default() + }, + |root| ui.board_ui(root, &settings), + ) + .drop_without_applying_deltas(); + assert!(ui.board_shown); + assert!(ui.board.animation_at(0.0).is_none()); + ui.tick_at(at, animation, happened_at); +} + +fn automatic_duration(f: &Fixture) -> Duration { + match &f.ui.playback { + Some(Playback::Automatic { duration, .. }) => *duration, + _ => panic!("automatic playback expected"), + } +} + +fn assert_current_slide( + f: &Fixture, + time: f64, + expected_duration: Duration, + from: Square, + to: Square, +) { + let (duration, slides, remaining) = + f.ui.board + .animation_at(time) + .expect("the current BoardView transition"); + assert_eq!(remaining, 1.0, "the first visual frame must be at from"); + assert!( + (duration - f64::from(expected_duration.as_secs_f32())).abs() < 1e-6, + "animation {duration} does not match scheduler {}", + expected_duration.as_secs_f32() + ); + assert!( + slides + .iter() + .any(|(_, slide_from, slide_to)| *slide_from == from && *slide_to == to), + "missing {from}{to} in {slides:?}" + ); +} + +fn assert_adaptive_board_slides(f: &mut Fixture, first_ms: u128, last_ms: u128) { + let ctx = egui::Context::default(); + let settings = Settings::default(); + let start = Instant::now(); + f.ui.board_shown = false; + f.ui.tick_at(start, normal(), NOW); + board_frame(f, &ctx, 0.0, &settings); + assert!(f.ui.board.animation_at(0.0).is_none()); + + f.ui.tick_at(start, normal(), NOW); + let first = automatic_duration(f); + assert_eq!(first.as_millis(), first_ms); + assert_eq!(f.ui.playback_deadline(), Some(start + first)); + assert_eq!(f.ui.session.context_index, 0); + board_frame(f, &ctx, 0.01, &settings); + assert_current_slide(f, 0.01, first, Square::E2, Square::E4); + assert_eq!(f.ui.state(), Some(State::Watch)); + + tick_with_prime(&mut f.ui, start + first, normal(), NOW); + let last = automatic_duration(f); + assert_eq!(last.as_millis(), last_ms); + assert_eq!(f.ui.session.context_index, 1); + board_frame(f, &ctx, 0.02, &settings); + assert_current_slide(f, 0.02, last, Square::E7, Square::E5); + assert_eq!(f.ui.state(), Some(State::Watch)); + + tick_with_prime(&mut f.ui, start + first + last, normal(), NOW); + assert_eq!(f.ui.session.context_index, 2); + assert!(f.ui.can_input()); + board_frame(f, &ctx, 10.0, &settings); + assert!( + f.ui.board.animation_at(10.0).is_none(), + "the final position must not start a settings-duration slide" + ); + assert_eq!(f.attempts().len(), 2); +} + +#[test] +fn adaptive_board_animation_matches_actual_slides_and_starts_at_from() { + let mut fast = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "adaptive-fast", + ); + let e4 = key_for(&fast.library, &fast.scope, "e2e4"); + fast.ui.learning.ensure_item(e4).correct_streak = 3; + fast.ui.session.context_policy.use_fixed_piece_speed = false; + fast.ui.session.context_policy.move_speed_adjustment = 1.5; + assert_adaptive_board_slides(&mut fast, 83, 166); + + let mut slow = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "adaptive-slow", + ); + slow.ui.session.context_policy.use_fixed_piece_speed = false; + slow.ui.session.context_policy.move_speed_adjustment = 0.0; + assert_adaptive_board_slides(&mut slow, 1000, 1000); +} + +#[test] +fn next_target_continues_the_shown_line_without_reverse_slide() { + fn settle_to_input(f: &mut Fixture, at: Instant) { + let mut at = at; + for _ in 0..32 { + if f.ui.can_input() { + return; + } + let next = f.ui.playback_deadline().unwrap_or(at); + tick_with_prime(&mut f.ui, next, normal(), NOW); + at = next; + } + panic!("training did not reach independent input"); + } + + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::Black, + &["e7e5", "b8c6", "a7a6"], + "next-target-prime", + ); + f.ui.session.context_policy.use_fixed_piece_speed = false; + f.ui.session.context_policy.move_speed_adjustment = 0.0; + let start = Instant::now(); + settle_to_input(&mut f, start); + assert_eq!(f.ui.session.current_expected_uci(), Some("e7e5")); + answer_current( + &mut f, + start + Duration::from_secs(1), + NOW, + "first-target-e5", + ); + + settle_to_input(&mut f, start + Duration::from_secs(1) + normal()); + assert_eq!(f.ui.session.current_expected_uci(), Some("b8c6")); + answer_current( + &mut f, + start + Duration::from_secs(3), + NOW + 1, + "second-target-nc6", + ); + + let prime_at = start + Duration::from_secs(3) + normal(); + // Every old move keeps its event, but a long visible prefix requires + // only one store transaction before the next opponent move. + let before_reuse = f.store.load().unwrap(); + for _ in 0..8 { + f.ui.tick_at(prime_at, normal(), NOW); + if f.ui.pending_automatic.is_some() { + break; + } + } + assert!(f.ui.pending_automatic.is_some()); + let after_reuse = f.store.load().unwrap(); + assert_eq!(after_reuse.revision, before_reuse.revision + 1); + let added = &after_reuse.learning.attempts[before_reuse.learning.attempts.len()..]; + assert_eq!(added.len(), 4); + assert!( + added + .iter() + .all(|event| event.event_type == TrainingEventType::AutoContext) + ); + assert_eq!(f.ui.session.context_index, 4); + assert!(!f.ui.board_shown); + let ctx = egui::Context::default(); + let settings = Settings::default(); + board_frame(&mut f, &ctx, 10.0, &settings); + assert!( + f.ui.board.animation_at(10.0).is_none(), + "prime must not animate the previous target backwards" + ); + + f.ui.tick_at(prime_at, normal(), NOW); + let duration = automatic_duration(&f); + assert_eq!(duration, Duration::from_millis(1000)); + board_frame(&mut f, &ctx, 10.01, &settings); + assert_current_slide(&f, 10.01, duration, Square::F1, Square::B5); + let (_, slides, _) = f.ui.board.animation_at(10.01).unwrap(); + assert!( + slides + .iter() + .all(|(_, from, to)| !(*from == Square::F3 && *to == Square::G1)), + "next target started with a reverse slide: {slides:?}" + ); + assert!(matches!( + &f.ui.playback, + Some(Playback::Automatic { remaining, .. }) if remaining.is_empty() + )); +} + +fn emitted_sounds(f: &mut Fixture, ctx: &egui::Context, settings: &Settings) -> Vec { + let mut sounds = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(960.0, 600.0), + )), + ..Default::default() + }, + |ui| { + sounds.extend( + f.ui.show(ui, settings, "Test") + .into_iter() + .filter_map(|action| { + if let SessionAction::Sound(sound) = action { + Some(sound) + } else { + None + } + }), + ); + }, + ) + .drop_without_applying_deltas(); + sounds +} + +#[test] +fn accepted_move_emits_once_and_next_task_only_animates_the_opponent_reply() { + for side in [LearningSide::White, LearningSide::Black] { + for animation in [ + crate::settings::Animation::Normal, + crate::settings::Animation::Off, + ] { + for replay in [false, true] { + let (due, reply, wrong) = match side { + LearningSide::White => (["e2e4", "g1f3"], "e7e5", "d2d4"), + LearningSide::Black => (["e7e5", "b8c6"], "g1f3", "d7d5"), + }; + let mut f = + Fixture::new("1. e4 e5 2. Nf3 Nc6 *", side, &due, "continuous-feedback"); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + let ctx = egui::Context::default(); + let settings = Settings { + animation, + ..Settings::default() + }; + let at = Instant::now() + Duration::from_secs(60); + let duration = Duration::from_secs_f32(animation.seconds()); + f.ui.animation = duration; + f.ui.pending_sounds.clear(); + f.ui.visual_log.clear(); + if replay { + assert!(f.ui.play_uci_with_id_at(wrong, "wrong".into(), at - WRONG_SHOWN, NOW)); + f.ui.tick_at(at, duration, NOW); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Wrong]); + } + assert!(f.ui.play_uci_with_id_at(due[0], "accepted".into(), at, NOW)); + let accepted_position = fen4(&f.ui.board_position); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); + for _ in 0..8 { + f.ui.tick_at(at + duration, duration, NOW); + assert_eq!( + fen4(&f.ui.board_position), + accepted_position, + "accepted move must not rewind" + ); + if f.ui.pending_automatic.is_some() { + break; + } + } + assert!(f.ui.pending_automatic.is_some()); + // The prime frame is silent; a separate later frame emits the + // opponent move, so queue coalescing cannot conceal a duplicate. + assert!(emitted_sounds(&mut f, &ctx, &settings).is_empty()); + assert_eq!(emitted_sounds(&mut f, &ctx, &settings), [Sound::Move]); + assert_eq!(f.ui.visual_log, [reply]); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some(due[1])); + let attempts = f.attempts(); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type.is_independent()) + .count(), + 1 + ); + assert!(attempts.iter().any(|event| event.expected_uci == due[0] + && event.event_type == TrainingEventType::AutoContext)); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type == TrainingEventType::ReplayAfterError) + .count(), + usize::from(replay) + ); + } + } + } +} + +#[test] +fn shown_context_requires_the_same_history_and_never_bypasses_a_question() { + let mut f = Fixture::new( + "1. Nf3 Nf6 2. g3 g6 3. Bg2 *", + LearningSide::White, + &["f1g2"], + "context-identity", + ); + let presentation = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + f.ui.board_position = parse_position(&presentation.automatic_context[3].to).unwrap(); + let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); + // Even with an identical final position, a different move order must not + // reuse context. A matching FEN alone cannot establish repetition history. + f.ui.shown_prefix = Some(ShownPrefix { + repertoire_id: id.clone(), + path: vec!["g2g3".into(), "g7g6".into(), "g1f3".into(), "g8f6".into()], + }); + assert!(!f.ui.reuse_shown_context(&presentation, Instant::now())); + assert!(f.attempts().is_empty()); + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["g1f3"], + "context-question", + ); + let presentation = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + f.ui.board_position = parse_position(&presentation.automatic_context[1].to).unwrap(); + f.ui.shown_prefix = Some(ShownPrefix { + repertoire_id: f.ui.session.current_target().unwrap().repertoire_id.clone(), + path: vec!["e2e4".into(), "e7e5".into()], + }); + f.ui.session.context_policy.consider_leadup_moves = true; + let question = + f.ui.session + .presentation_with_learning(&f.library, &f.ui.learning) + .unwrap(); + assert_eq!( + question.phase, + LearningSessionPhase::AwaitingContextIndependent + ); + assert!(!f.ui.reuse_shown_context(&question, Instant::now())); + f.ui.prepare_presentation(Instant::now()); + assert!(f.ui.can_input()); + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.attempts().is_empty()); +} + +fn assert_annotation_badge(ui: &OpeningSessionUi, text: &str, square: Square) { + let annotation = ui.displayed_annotations(); + let badge = annotation.badge.expect("PGN move badge"); + assert_eq!(badge.text, text); + assert_eq!(badge.square, square); +} + +#[test] +fn pgn_annotations_follow_visible_user_and_automatic_moves_not_the_next_task() { + let mut f = Fixture::with( + "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} 2. Nf3! {[%csl Gf3]} Nc6 *", + LearningSide::White, + &["e2e4", "g1f3"], + &[], + "visible-pgn-annotations", + SessionKind::ReviewAll, + ); + let original = + f.ui.library + .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) + .unwrap() + .pgn + .clone(); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().arrows.is_empty()); + // A hint reveals the expected move, not that future node's annotations. + assert!(f.ui.request_hint_with_id_at("annotation-hint".into(), start, NOW)); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().arrows.is_empty()); + assert!(f.ui.play_uci_with_id_at("e2e4", "annotation-e4".into(), start, NOW)); + assert_eq!( + f.ui.session.current_target().unwrap().key.expected_uci, + "g1f3" + ); + assert_annotation_badge(&f.ui, "!!", Square::E4); + let annotation = f.ui.displayed_annotations(); + assert_eq!(annotation.arrows.len(), 2); + assert_eq!(annotation.circles.len(), 2); + assert!( + annotation + .arrows + .iter() + .any(|arrow| arrow.from == Square::E2 + && arrow.to == Square::E4 + && arrow.color == crate::game_view::shape_color(chess_core::ShapeColor::Red)) + ); + // Verify the helper's data actually reaches the rendered BoardView. + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let output = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &Settings::default()); + assert!(output.shapes.iter().any( + |shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "!!") + )); + output.drop_without_applying_deltas(); + f.ui.tick_at(start + normal(), normal(), NOW); + assert_annotation_badge(&f.ui, "!!", Square::E4); + assert!(f.ui.visual_log.is_empty(), "reused e4 must not play again"); + for _ in 0..8 { + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + if matches!(f.ui.playback, Some(Playback::Automatic { .. })) { + break; + } + } + assert_eq!(f.ui.visual_log, ["e7e5"]); + assert_annotation_badge(&f.ui, "?!", Square::E5); + assert_eq!(f.ui.displayed_annotations().arrows[0].from, Square::G1); + f.ui.tick_at(f.ui.playback_deadline().unwrap(), normal(), NOW); + assert!(f.ui.can_input()); + assert_annotation_badge(&f.ui, "?!", Square::E5); + assert!( + f.ui.displayed_annotations().circles.is_empty(), + "future Nf3 circle leaked before the answer" + ); + assert!(f.ui.play_uci_with_id_at( + "g1f3", + "annotation-nf3".into(), + start + Duration::from_secs(1), + NOW + )); + assert_annotation_badge(&f.ui, "!", Square::F3); + assert_eq!(f.ui.displayed_annotations().circles[0].0, Square::F3); + f.ui.debug_settle(); + assert_annotation_badge(&f.ui, "!", Square::F3); + assert_eq!( + f.ui.library + .repertoire(f.scope.repertoire_ids.iter().next().unwrap()) + .unwrap() + .pgn, + original + ); +} + +#[test] +fn pgn_annotations_clear_for_wrong_moves_and_survive_failed_async_save_and_retry() { + let mut f = Fixture::new( + "1. e4!! {[%csl Ge4]} *", + LearningSide::White, + &["e2e4"], + "annotations-retry", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("d2d4", "annotations-wrong".into(), start, NOW)); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().circles.is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert!(f.ui.can_input()); + assert!(f.ui.displayed_annotations().badge.is_none()); + // Another wrong move during replay must not inherit the revealed e4 badge. + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "annotations-wrong-replay".into(), + start + WRONG_SHOWN, + NOW + )); + assert!(f.ui.displayed_annotations().badge.is_none()); + f.ui.tick_at(start + WRONG_SHOWN * 2, normal(), NOW); + let store = f.ui.store.clone(); + f.ui.synchronous_commits = false; + f.ui.store = LearningStore::with_legacy(store.path(), store.path()); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "annotations-replay".into(), + start + WRONG_SHOWN * 2, + NOW + )); + assert!(f.ui.has_unsaved()); + assert_annotation_badge(&f.ui, "!!", Square::E4); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert_annotation_badge(&f.ui, "!!", Square::E4); + f.ui.store = store; + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + assert_annotation_badge(&f.ui, "!!", Square::E4); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(), + 1 + ); + assert_eq!( + f.attempts().last().unwrap().event_type, + TrainingEventType::ReplayAfterError + ); +} + +#[test] +fn alternative_answer_credits_actual_move_and_completed_answer_is_silent_and_neutral() { + let mut f = Fixture::new( + "1. e4! (1. d4!! {[%csl Gd4]}) *", + LearningSide::White, + &["e2e4", "d2d4"], + "alternative-answers", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + let original = f.ui.session.current_expected_uci().unwrap().to_owned(); + let (played, badge, square) = if original == "e2e4" { + ("d2d4", "!!", Square::D4) + } else { + ("e2e4", "!", Square::E4) + }; + let initial_position = f.ui.board_position.clone(); + assert_eq!( + f.ui.session + .pending_answers_for_position(&fen4(&initial_position)) + .len(), + 2 + ); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + assert_eq!(f.ui.state(), Some(State::Yours)); + assert!(f.ui.play_uci_with_id_at(played, "actual-alternative".into(), start, NOW)); + assert_annotation_badge(&f.ui, badge, square); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].expected_uci, played); + assert_eq!( + f.attempts()[0].event_type, + TrainingEventType::CorrectIndependent + ); + assert_eq!(f.ui.session.current_expected_uci(), Some(original.as_str())); + assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); + f.ui.tick_at(start + normal(), normal(), NOW); + assert_eq!(f.ui.board_position, initial_position); + // S3a: the other answer of this position is still asked. + let played_san = if played == "d2d4" { "d4" } else { "e4" }; + assert_eq!(f.ui.state(), Some(State::YoursMore(played_san.to_owned()))); + assert!(f.ui.play_uci_with_id_at(played, "repeat-alternative".into(), start + normal(), NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert_annotation_badge(&f.ui, badge, square); + assert!(f.ui.save_error.is_none() && f.ui.error.is_none()); + assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); + f.ui.tick_at(start + normal() + WRONG_SHOWN, normal(), NOW); + assert_eq!(f.ui.board_position, initial_position); + assert!(f.ui.can_input()); + assert!(f.ui.displayed_annotations().badge.is_none()); + // «Now the other one: play …» shows the answer: recorded as shown, not as an + // error and not as known. + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[1].event_type, TrainingEventType::Previewed); + assert_eq!(attempts[1].expected_uci, original); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert_eq!(f.ui.revealed_uci().as_deref(), Some(original.as_str())); + assert_eq!(f.ui.tally.mistakes, 0); + assert_eq!(f.ui.session.remaining(), 1); + assert!(emitted_sounds(&mut f, &ctx, &Settings::default()).is_empty()); +} + +#[test] +fn move_input_uses_the_startup_answer_snapshot_in_independent_and_replay_phases() { + let mut f = Fixture::new( + "1. e4 (1. d4) *", + LearningSide::White, + &["e2e4"], + "cached-repertoire-answers", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + let key = key_for(&f.library, &f.scope, "d2d4"); + assert!(f.ui.repertoire_answers.contains(&key)); + // The production library is immutable for the UI's lifetime. Change it + // only here to detect any accidental rebuilding in the input hot path. + let id = f.scope.repertoire_ids.iter().next().unwrap(); + f.ui.library + .repertoire_mut(id) + .unwrap() + .set_prefix_disabled(&["d2d4".to_owned()], true) + .unwrap(); + assert!( + !active_learning_keys(&f.ui.library, &f.scope) + .unwrap() + .contains(&key) + ); + assert!(f.ui.play_uci_with_id_at("d2d4", "cached-independent".into(), start, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert!(f.attempts().is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + // The answer was revealed after the other move: no second preview. + assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); + assert!( + !f.ui + .request_hint_with_id_at("cached-preview".into(), start + WRONG_SHOWN, NOW) + ); + assert!(f.ui.play_uci_with_id_at("d2d4", "cached-replay".into(), start + WRONG_SHOWN, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].event_type, TrainingEventType::Previewed); + assert!(f.ui.pending_sounds.is_empty()); +} + +#[test] +fn known_unscheduled_answer_during_hint_is_neutral_but_outside_move_still_wrong() { + let mut f = Fixture::new( + "1. e4! (1. d4!! {[%csl Gd4]}) *", + LearningSide::White, + &["e2e4"], + "hint-alternative", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.request_hint_with_id_at("preview-alternative".into(), start, NOW)); + let attempts = f.attempts().len(); + let snapshot = f.ui.session.clone(); + assert!(f.ui.play_uci_with_id_at("d2d4", "unscheduled-alternative".into(), start, NOW)); + assert!(matches!(f.ui.playback, Some(Playback::Alternative { .. }))); + assert_annotation_badge(&f.ui, "!!", Square::D4); + assert_eq!(f.ui.session, snapshot); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert_eq!(f.attempts().len(), attempts); + assert!(f.ui.can_input()); + assert_eq!(f.ui.state(), Some(State::Alternative)); + assert!(f.ui.play_uci_with_id_at( + "g1f3", + "outside-repertoire".into(), + start + WRONG_SHOWN, + NOW + )); + assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); + assert_eq!(f.ui.pending_sounds, [Sound::Wrong]); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert_eq!(f.attempts().len(), attempts); +} + +#[test] +fn authored_wrong_branch_has_its_own_annotations_only_after_it_is_played() { + let mut f = Fixture::new( + "1. e4! (1. d4?? {[%csl Rd4]}) e5 *", + LearningSide::White, + &["e2e4"], + "wrong-branch-annotations", + ); + let start = Instant::now(); + f.ui.tick_at(start, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.play_uci_with_id_at("d2d4", "authored-wrong-branch".into(), start, NOW)); + assert_annotation_badge(&f.ui, "??", Square::D4); + assert_eq!( + f.ui.displayed_annotations().circles[0], + ( + Square::D4, + crate::game_view::shape_color(chess_core::ShapeColor::Red) + ) + ); + f.ui.tick_at(start + WRONG_SHOWN, normal(), NOW); + assert!(f.ui.displayed_annotations().badge.is_none()); + assert!(f.ui.displayed_annotations().circles.is_empty()); +} + +#[test] +fn pgn_annotation_cursor_distinguishes_transposed_paths_and_repertoire_sources() { + let mut f = Fixture::new( + "1. Nf3 (1. g3 g6 2. Nf3 Nf6? {[%csl Rf6]} 3. Bg2) Nf6 2. g3 g6! {[%csl Gg6]} 3. Bg2 *", + LearningSide::White, + &["f1g2"], + "annotations-transposition", + ); + let id = f.ui.session.current_target().unwrap().repertoire_id.clone(); + let mut position_keys = Vec::new(); + for (path, badge, square) in [ + (["g1f3", "g8f6", "g2g3", "g7g6"], "!", Square::G6), + (["g2g3", "g7g6", "g1f3", "g8f6"], "?", Square::F6), + ] { + f.ui.set_displayed_path(Some(&ShownPrefix { + repertoire_id: id.clone(), + path: path.map(str::to_owned).to_vec(), + })); + let (_, node) = f.ui.displayed_node.as_ref().expect("exact PGN branch"); + f.ui.board_position = f.ui.annotation_games[&id].position(*node).unwrap().clone(); + position_keys.push(fen4(&f.ui.board_position)); + assert_annotation_badge(&f.ui, badge, square); + assert_eq!(f.ui.displayed_annotations().circles[0].0, square); + } + assert_eq!( + position_keys[0], position_keys[1], + "fixture must really transpose" + ); + let other_id = + f.ui.library + .create("Other annotations", &Game::new()) + .unwrap(); + f.ui.annotation_games.insert( + other_id.clone(), + chess_core::parse_str("1. Nf3 Nf6 2. g3 g6?? {[%csl Yg6]} *").game, + ); + f.ui.set_displayed_path(Some(&ShownPrefix { + repertoire_id: other_id.clone(), + path: ["g1f3", "g8f6", "g2g3", "g7g6"].map(str::to_owned).to_vec(), + })); + let (_, node) = f.ui.displayed_node.as_ref().unwrap(); + f.ui.board_position = f.ui.annotation_games[&other_id] + .position(*node) + .unwrap() + .clone(); + assert_annotation_badge(&f.ui, "??", Square::G6); +} + +#[test] +fn debug_moves_settles_prime_between_targets() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", + LearningSide::Black, + &["e7e5", "b8c6", "a7a6"], + "debug-prime-between-targets", + ); + f.ui.debug_moves("e7e5 settle b8c6 settle"); + assert!(f.ui.can_input()); + assert_eq!(f.ui.session.current_expected_uci(), Some("a7a6")); + f.ui.debug_moves("a7a6 settle"); + assert!(f.ui.is_finished()); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(), + 3 + ); +} + +#[test] +fn automatic_context_has_three_separate_normal_timed_steps() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "context-normal", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert_eq!(f.ui.visual_log, ["e2e4"]); + assert_eq!(f.ui.session.context_index, 0); + assert!(!f.ui.can_input()); + + tick_with_prime(&mut f.ui, start + Duration::from_millis(249), normal(), NOW); + assert_eq!(f.ui.session.context_index, 0); + assert!(f.attempts().is_empty()); + + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5"]); + tick_with_prime(&mut f.ui, start + normal(), normal(), NOW); + assert_eq!(f.ui.session.context_index, 1); + + tick_with_prime(&mut f.ui, start + normal() * 2, normal(), NOW); + assert_eq!(f.ui.session.context_index, 2); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); + tick_with_prime(&mut f.ui, start + normal() * 3, normal(), NOW); + assert_eq!(f.ui.session.context_index, 3); + assert_eq!( + f.ui.session.phase, + LearningSessionPhase::AwaitingIndependent + ); + assert!(f.ui.can_input()); + assert_eq!(f.attempts().len(), 3); + assert_eq!( + trainer::repertoire::fen4(&f.ui.board_position), + key_for(&f.library, &f.scope, "b8c6").position_fen4 + ); +} + +#[test] +fn animation_off_commits_every_context_step_without_skipping_store_calls() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "context-off", + ); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert_eq!(f.ui.visual_log, ["e2e4", "e7e5", "g1f3"]); + assert_eq!(f.ui.session.context_index, 3); + assert!(f.ui.can_input()); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 3); + assert_eq!( + attempts + .iter() + .map(|attempt| attempt.actual_uci.as_deref()) + .collect::>(), + [Some("e2e4"), Some("e7e5"), Some("g1f3")] + ); + assert!(attempts.iter().all(|attempt| { + attempt.event_type == TrainingEventType::AutoContext && attempt.response_time_ms.is_none() + })); +} + +#[test] +fn legal_input_is_ignored_during_autoplay() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "autoplay-input", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(!f.ui.play_uci_with_id_at( + "e7e5", + "blocked-input".to_owned(), + start + Duration::from_millis(20), + NOW, + )); + assert_eq!(f.ui.session.context_index, 0); + assert!(f.attempts().is_empty()); + assert_eq!(f.ui.visual_log, ["e2e4"]); +} + +#[test] +fn wrong_answer_replays_without_a_second_independent_error() { + let mut f = Fixture::with( + "1. e4 *", + LearningSide::White, + &["e2e4"], + &[], + "wrong-replay", + SessionKind::ReviewAll, + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "wrong-d4".to_owned(), + start + Duration::from_millis(1500), + NOW, + )); + assert!(matches!(f.ui.playback, Some(Playback::Wrong { .. }))); + tick_with_prime( + &mut f.ui, + start + Duration::from_millis(1500) + WRONG_SHOWN, + normal(), + NOW, + ); + assert_eq!( + f.ui.session.phase, + LearningSessionPhase::AwaitingReplayAfterError + ); + assert_eq!( + f.ui.presentation.as_ref().unwrap().revealed_move.as_deref(), + Some("e2e4") + ); + + assert!(f.ui.play_uci_with_id_at( + "d2d4", + "wrong-replay-d4".to_owned(), + start + Duration::from_secs(3), + NOW, + )); + assert_eq!(f.attempts().len(), 1); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(3) + WRONG_SHOWN, + normal(), + NOW, + ); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "replay-e4".to_owned(), + start + Duration::from_secs(4), + NOW, + )); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(4) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!( + attempts[0].event_type, + TrainingEventType::IncorrectIndependent + ); + assert_eq!(attempts[0].response_time_ms, Some(1500)); + assert_eq!(attempts[1].event_type, TrainingEventType::ReplayAfterError); + assert_eq!(attempts[1].response_time_ms, None); + let item = f + .store + .load() + .unwrap() + .learning + .item(&key_for(&f.library, &f.scope, "e2e4")) + .unwrap() + .clone(); + assert_eq!(item.wrong_count, 1); + assert_eq!(item.correct_count, 0); +} + +#[test] +fn preview_is_idempotent_and_shown_move_is_not_success() { + let mut f = Fixture::with( + "1. e4 *", + LearningSide::White, + &["e2e4"], + &[], + "preview", + SessionKind::ReviewAll, + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!(f.ui.request_hint_with_id_at( + "preview-e4".to_owned(), + start + Duration::from_millis(100), + NOW, + )); + assert_eq!(f.ui.session.phase, LearningSessionPhase::PreviewedReplay); + assert!(!f.ui.request_hint_with_id_at( + "preview-e4-again".to_owned(), + start + Duration::from_millis(200), + NOW, + )); + assert_eq!(f.attempts().len(), 1); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "play-preview-e4".to_owned(), + start + Duration::from_secs(1), + NOW, + )); + tick_with_prime( + &mut f.ui, + start + Duration::from_secs(1) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.tally.hints, 1); + let data = f.store.load().unwrap(); + assert_eq!(data.learning.attempts.len(), 2); + assert_eq!( + data.learning.attempts[0].event_type, + TrainingEventType::Previewed + ); + assert_eq!( + data.learning.attempts[1].event_type, + TrainingEventType::AutoContext + ); + let item = data + .learning + .item(&key_for(&f.library, &f.scope, "e2e4")) + .unwrap(); + assert_eq!(item.correct_count, 0); + assert_eq!(item.wrong_count, 0); + assert!(item.independent_response_times_ms.is_empty()); +} + +#[test] +fn duplicate_store_response_does_not_advance_the_ui_twice() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::Black, + &["b8c6"], + "duplicate", + ); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + assert!( + f.ui.advance_context_with_id_at("duplicate-context".to_owned(), start + normal(), NOW,) + ); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.attempts().len(), 1); + + f.ui.completed_attempt_ids.remove("duplicate-context"); + assert!(f.ui.advance_context_with_id_at( + "duplicate-context".to_owned(), + start + normal() * 2, + NOW, + )); + assert_eq!(f.ui.session.context_index, 1); + assert_eq!(f.attempts().len(), 1); + assert!(!f.ui.visual_log.contains(&"g1f3".to_owned())); +} + +#[test] +fn store_error_is_visible_blocking_and_retryable() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "store-error"); + let start = Instant::now(); + tick_with_prime(&mut f.ui, start, normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + assert!(f.ui.play_uci_with_id_at( + "e2e4", + "save-error-e4".to_owned(), + start + Duration::from_millis(100), + NOW, + )); + assert!(f.ui.has_unsaved()); + assert!(f.ui.save_error.is_some()); + assert!(!f.ui.can_input()); + assert!(!f.ui.is_finished()); + assert!(f.attempts().is_empty()); + assert!(!f.ui.play_uci_with_id_at( + "d2d4", + "blocked-after-save-error".to_owned(), + start + Duration::from_millis(200), + NOW, + )); + + f.ui.store = valid_store; + f.ui.retry_pending(start + Duration::from_millis(300)); + assert!(!f.ui.has_unsaved()); + assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); + tick_with_prime( + &mut f.ui, + start + Duration::from_millis(300) + normal(), + normal(), + NOW, + ); + assert!(f.ui.is_finished()); + assert_eq!(f.attempts().len(), 1); +} + +/// Runs one frame of the whole screen at a window size; returns the side panel's rect. +fn screen_frame( + ui: &mut OpeningSessionUi, + ctx: &egui::Context, + size: egui::Vec2, + events: Vec, +) -> (Vec, egui::Rect) { + let mut actions = Vec::new(); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), + time: Some(0.0), + events, + ..Default::default() + }, + |root| actions = ui.show(root, &Settings::default(), "Test repertoire"), + ) + .drop_without_applying_deltas(); + let panel = egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side")) + .or_else(|| { + egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side_stacked")) + }) + .map(|state| state.outer_rect) + .unwrap_or(egui::Rect::NOTHING); + (actions, panel) +} + +fn key(key: Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn the_panel_takes_the_game_screens_place_at_both_reference_sizes() { + for (size, left) in [(vec2(1400.0, 900.0), 940.0), (vec2(960.0, 600.0), 576.0)] { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "geometry"); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let mut rects = Vec::new(); + for _ in 0..3 { + rects.push(screen_frame(&mut f.ui, &ctx, size, Vec::new()).1); + } + assert!( + (rects[2].left() - left).abs() <= 1.0, + "panel at {} in {size:?}", + rects[2].left() + ); + assert_eq!(rects[1], rects[2]); + // A question, a wrong move and its replay: the panel never moves. + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert!(f.ui.play_uci_with_id_at("d2d4", "geometry-wrong".into(), Instant::now(), NOW)); + assert_eq!(screen_frame(&mut f.ui, &ctx, size, Vec::new()).1, rects[2]); + assert!(f.ui.state() == Some(State::Wrong)); + } +} + +#[test] +fn a_new_move_is_shown_before_it_is_asked_and_counts_once_played() { + let mut f = Fixture::with( + "1. e4 {The king's pawn.} e5 *", + LearningSide::White, + &[], + &["e2e4"], + "new-move-shown", + SessionKind::Daily, + ); + assert_eq!(f.ui.session.remaining(), 1); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + // Shown at once: PREVIEWED recorded, the arrow and the comment visible, no hint. + let attempts = f.attempts(); + assert_eq!(attempts.len(), 1); + assert_eq!(attempts[0].event_type, TrainingEventType::Previewed); + assert!(f.ui.session.showing_new); + assert_eq!(f.ui.state(), Some(State::New)); + assert_eq!(f.ui.revealed_uci().as_deref(), Some("e2e4")); + assert!(!f.ui.can_hint()); + assert!(f.ui.can_input()); + let (game, node) = f.ui.expected_node().unwrap(); + assert_eq!( + crate::notation::comment_text(game.node(node).unwrap().comments_after()), + "The king's pawn." + ); + let (title, instruction, _) = f.ui.card_texts(&State::New, true); + assert_eq!(title, tr("New move")); + assert!(instruction.contains("1. e4"), "{instruction}"); + assert!(f.ui.play_uci_with_id_at("e2e4", "play-new".into(), Instant::now(), NOW)); + assert_eq!(f.ui.state(), Some(State::NewDone)); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.session.remaining(), 0); + assert_eq!(f.ui.tally.new_moves, 1); + assert_eq!( + f.ui.tally.mistakes + f.ui.tally.hints + f.ui.tally.first_time, + 0 + ); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 2); + assert_eq!(attempts[1].event_type, TrainingEventType::AutoContext); +} + +#[test] +fn a_daily_session_brings_mistakes_and_hints_back_and_its_numbers_agree() { + // White's moves: e4, Nf3, Bb5, then O-O after a6 Ba4 Nf6 is new. + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *"; + let mut f = Fixture::with( + pgn, + LearningSide::White, + &["e2e4", "g1f3", "f1b5"], + &["b5a4", "e1g1"], + "daily-numbers", + SessionKind::Daily, + ); + let at = Instant::now(); + assert_eq!(f.ui.session.remaining(), 5); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + // e4: a mistake, then the replay. It comes back: still 5 to go. + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.ui.play_uci_with_id_at("d2d4", "e4-wrong".into(), at, NOW)); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::Wrong)); + answer_current(&mut f, at + WRONG_SHOWN, NOW, "e4-replay"); + assert_eq!(f.ui.session.remaining(), 5); + // Nf3: a hint, then the move. It comes back too. + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + assert!(f.ui.request_hint_with_id_at("nf3-hint".into(), at, NOW)); + assert_eq!(f.ui.state(), Some(State::Hint)); + answer_current(&mut f, at, NOW, "nf3-after-hint"); + assert_eq!(f.ui.session.remaining(), 5); + // Bb5 right; the new moves are shown and played. + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1b5")); + answer_current(&mut f, at, NOW, "bb5"); + assert_eq!(f.ui.session.remaining(), 4); + for _ in 0..2 { + f.ui.debug_settle(); + assert_eq!(f.ui.state(), Some(State::New)); + let uci = f.ui.session.current_expected_uci().unwrap().to_owned(); + answer_current(&mut f, at, NOW, &format!("new-{uci}")); + } + assert_eq!(f.ui.session.remaining(), 2); + // The returned two, answered right this time. + for expected in ["e2e4", "g1f3"] { + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some(expected)); + answer_current(&mut f, at, NOW, &format!("again-{expected}")); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.state(), Some(State::Summary)); + let tally = &f.ui.tally; + assert_eq!( + ( + tally.first_time, + tally.mistakes, + tally.hints, + tally.new_moves + ), + (1, 1, 1, 2) + ); + assert_eq!( + tally + .missed + .iter() + .map(|target| target.key.expected_uci.as_str()) + .collect::>(), + ["e2e4", "g1f3"] + ); + let independent = f + .attempts() + .iter() + .filter(|attempt| attempt.event_type.is_independent()) + .count(); + // e4 wrong, e4 right, Nf3 right, Bb5 right. + assert_eq!(independent, 4); + f.ui.compute_summary(); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!(summary.more_new, 0); + assert!(!summary.next_review.is_empty()); + assert_eq!(f.ui.counter(&State::Summary).0, "0"); +} + +#[test] +fn leaving_keeps_every_answer_and_shows_what_was_done() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "leave", + ); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + // Nothing answered: straight back, no question. + let mut early = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "leave-early"); + tick_with_prime(&mut early.ui, Instant::now(), Duration::ZERO, NOW); + screen_frame(&mut early.ui, &ctx, size, Vec::new()); + let (actions, _) = screen_frame(&mut early.ui, &ctx, size, vec![key(Key::Escape)]); + assert!(matches!(actions.as_slice(), [SessionAction::Back])); + // One answer: the result, «Session stopped», and the answer is in the store. + answer_current(&mut f, Instant::now(), NOW, "leave-e4"); + screen_frame(&mut f.ui, &ctx, size, Vec::new()); + let (actions, _) = screen_frame(&mut f.ui, &ctx, size, vec![key(Key::Escape)]); + assert!( + actions + .iter() + .all(|action| !matches!(action, SessionAction::Back)) + ); + screen_frame(&mut f.ui, &ctx, size, Vec::new()); + assert_eq!(f.ui.shown_state, State::Summary); + assert_eq!( + f.ui.card_texts(&State::Summary, true).0, + tr("Session stopped") + ); + assert_eq!(f.ui.counter(&State::Summary).0, "1"); + assert!(!f.ui.can_input()); + let before = f.attempts().len(); + let (actions, _) = screen_frame(&mut f.ui, &ctx, size, vec![key(Key::Enter)]); + assert!(matches!(actions.as_slice(), [SessionAction::Back])); + assert_eq!(f.attempts().len(), before); + assert_eq!( + f.attempts() + .iter() + .filter(|attempt| attempt.event_type == TrainingEventType::CorrectIndependent) + .count(), + 1 + ); +} + +#[test] +fn skip_puts_the_question_at_once_and_records_the_moves_shown() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 *", + LearningSide::White, + &["f1b5"], + "skip", + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert_eq!(f.ui.state(), Some(State::Watch)); + assert_eq!(f.ui.visual_log, ["e2e4"]); + assert!(f.ui.skip_context(at)); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.can_input()); + assert_eq!(f.ui.state(), Some(State::Yours)); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1b5")); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 4); + assert!( + attempts + .iter() + .all(|attempt| attempt.event_type == TrainingEventType::AutoContext) + ); + assert_eq!( + fen4(&f.ui.board_position), + key_for(&f.library, &f.scope, "f1b5").position_fen4 + ); + assert_eq!(f.ui.visual_log, ["e2e4"], "skipped moves are not animated"); +} + +#[test] +fn correct_stays_six_hundred_ms_after_the_move() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "feedback", + ); + f.ui.feedback = FEEDBACK; + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "feedback-e4".into(), at, NOW)); + assert_eq!(f.ui.playback_deadline(), Some(at + normal() + FEEDBACK)); + f.ui.tick_at(at + normal(), normal(), NOW); + assert_eq!(f.ui.state(), Some(State::Correct)); + f.ui.tick_at(at + normal() + FEEDBACK, normal(), NOW); + assert_ne!(f.ui.state(), Some(State::Correct)); +} + +#[test] +fn ten_more_new_continues_the_finished_session_with_new_moves_only() { + let moves = [ + "Nf3", "Nf6", "g3", "g6", "Bg2", "Bg7", "O-O", "O-O", "d3", "d6", "e4", "e5", "Nc3", "Nc6", + "a3", "a6", "h3", "h6", "Be3", "Be6", "Qd2", "Qd7", "Rab1", "Rab8", "b4", "b5", + ]; + let mut pgn = String::new(); + for (index, pair) in moves.chunks(2).enumerate() { + pgn.push_str(&format!("{}. {} {} ", index + 1, pair[0], pair[1])); + } + pgn.push('*'); + let mut f = Fixture::with( + &pgn, + LearningSide::White, + &[], + &[ + "g1f3", "g2g3", "f1g2", "e1g1", "d2d3", "e2e4", "b1c3", "a2a3", "h2h3", "c1e3", "d1d2", + "a1b1", "b2b4", + ], + "more-new", + SessionKind::Daily, + ); + assert_eq!(f.ui.session.remaining(), layout::NEW_PER_SESSION); + for index in 0..layout::NEW_PER_SESSION { + f.ui.debug_settle(); + assert_eq!(f.ui.state(), Some(State::New), "move {index}"); + answer_current(&mut f, Instant::now(), NOW, &format!("more-{index}")); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + f.ui.compute_summary(); + assert_eq!(f.ui.more_new_count(), 3); + let snapshot = f.ui.snapshot().clone(); + let mut more = + OpeningSessionUi::more_new(f.library.clone(), f.store.clone(), snapshot, Color::Black) + .unwrap(); + assert_eq!(more.session.remaining(), 3); + assert_eq!(more.orientation(), Color::Black); + assert_eq!(more.session.id(), f.ui.session.id()); + more.synchronous_commits = true; + more.board_shown = true; + more.debug_settle(); + assert_eq!(more.state(), Some(State::New)); + assert_eq!(more.session.current_expected_uci(), Some("d1d2")); +} + +#[test] +fn a_review_counts_lines_and_announces_the_next_one() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 (2. Bc4) *", + LearningSide::White, + &[], + &[], + "review-lines", + SessionKind::ReviewAll, + ); + assert_eq!(f.ui.lines.len(), 2); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + assert_eq!(f.ui.counter(&State::Yours).0, "1/2"); + answer_current(&mut f, Instant::now(), NOW, "review-e4"); + f.ui.debug_settle(); + let at = Instant::now(); + assert!(f.ui.play_uci_with_id_at("g1f3", "review-nf3".into(), at, NOW)); + // Bc4 is in the second line; its context starts again from the beginning. + f.ui.tick_at(at + Duration::from_secs(1), normal(), NOW); + assert!(f.ui.pending_automatic.is_some()); + assert_eq!(f.ui.line, 2); + assert!(f.ui.next_line_banner); + assert_eq!(f.ui.state(), Some(State::NextLine)); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("f1c4")); + answer_current(&mut f, Instant::now(), NOW, "review-bc4"); + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(f.ui.counter(&State::Summary).0, "2/2"); + f.ui.compute_summary(); + assert_eq!(f.ui.more_new_count(), 0, "no «10 more new» after a review"); +} + +#[test] +fn a_new_session_never_resumes_an_unfinished_one() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &["e2e4", "g1f3"], + "no-resume", + ); + tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); + answer_current(&mut f, Instant::now(), NOW, "first-e4"); + let old = f.ui.session_id().to_owned(); + let again = OpeningSessionUi::new( + f.library.clone(), + f.store.clone(), + f.scope.clone(), + SessionKind::Daily, + ) + .unwrap(); + assert_ne!(again.session_id(), old); + // The unfinished snapshot is kept in the file, untouched. + let data = f.store.load().unwrap(); + assert!(data.session_snapshot(&old).is_some()); + assert_eq!(again.session.remaining(), 1); +} + +fn wait_for_commit(ui: &mut OpeningSessionUi) { + let deadline = Instant::now() + Duration::from_secs(5); + while ui.commit_in_flight.is_some() { + assert!(Instant::now() < deadline, "commit worker did not finish"); + ui.poll_commit(Instant::now()); + std::thread::sleep(Duration::from_millis(1)); + } +} + +#[test] +fn async_commit_keeps_frames_responsive_under_store_lock_and_commits_once() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-lock"); + f.ui.synchronous_commits = false; + tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); + let lock_path = f.store.path().with_file_name("learning.json.lock"); + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(lock_path) + .unwrap(); + lock.lock().unwrap(); + let unlock = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(600)); + drop(lock); + }); + let start = Instant::now(); + assert!(f.ui.play_uci_with_id_at("e2e4", "async-answer".to_owned(), start, NOW)); + assert!( + start.elapsed() < Duration::from_millis(300), + "input waited for storage lock" + ); + assert!(f.ui.has_unsaved()); + assert!(f.ui.commit_in_flight.is_some()); + assert!(!f.ui.can_input()); + assert!( + !f.ui + .play_uci_with_id_at("e2e4", "async-answer".to_owned(), Instant::now(), NOW) + ); + f.ui.retry_pending(Instant::now()); + let ctx = egui::Context::default(); + let frame = Instant::now(); + ctx.run_ui(egui::RawInput::default(), |ui| { + f.ui.show(ui, &Settings::default(), "Test"); + }) + .drop_without_applying_deltas(); + assert!( + frame.elapsed() < Duration::from_millis(300), + "frame waited for storage lock" + ); + unlock.join().unwrap(); + wait_for_commit(&mut f.ui); + assert!(!f.ui.has_unsaved()); + assert!(matches!(f.ui.playback, Some(Playback::Accepted { .. }))); + assert_eq!(f.attempts().len(), 1); + let revision = f.ui.session.revision; + f.ui.poll_commit(Instant::now()); + f.ui.retry_pending(Instant::now()); + assert_eq!(f.ui.session.revision, revision); + assert_eq!(f.attempts().len(), 1); +} + +fn pointer_board_frame( + f: &mut Fixture, + ctx: &egui::Context, + time: f64, + events: Vec, + settings: &Settings, +) -> egui::FullOutput { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + vec2(800.0, 800.0), + )), + time: Some(time), + events, + ..Default::default() + }, + |ui| f.ui.board_ui(ui, settings), + ); + output.textures_delta.clear(); + output +} + +fn piece_meshes(output: &egui::FullOutput) -> Vec<(egui::TextureId, egui::Rect)> { + fn collect(shape: &egui::Shape, meshes: &mut Vec<(egui::TextureId, egui::Rect)>) { + match shape { + egui::Shape::Mesh(mesh) => meshes.push((mesh.texture_id, mesh.calc_bounds())), + egui::Shape::Rect(rect) => { + if let Some(brush) = &rect.brush { + meshes.push((brush.fill_texture_id, rect.rect)); + } + } + egui::Shape::Vec(shapes) => { + for shape in shapes { + collect(shape, meshes); + } + } + _ => {} + } + } + let mut meshes = Vec::new(); + for shape in &output.shapes { + collect(&shape.shape, &mut meshes); + } + meshes +} + +fn pointer_button(pos: egui::Pos2, pressed: bool) -> egui::Event { + egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + } +} + +#[test] +fn pointer_move_stays_at_destination_during_async_save_without_a_second_animation() { + for drag in [true, false] { + for wrong in [false, true] { + for animation in [ + crate::settings::Animation::Normal, + crate::settings::Animation::Off, + ] { + let mut f = + Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "pointer-pending"); + f.ui.synchronous_commits = false; + let settings = Settings { + animation, + ..Settings::default() + }; + let duration = Duration::from_secs_f32(animation.seconds()); + f.ui.tick_at(Instant::now(), duration, NOW); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let from = egui::pos2(450.0, 650.0); + let to = egui::pos2(450.0, if wrong { 550.0 } else { 450.0 }); + let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); + let pawn = piece_meshes(&initial) + .into_iter() + .find(|(_, rect)| rect.contains(from)) + .expect("painted pawn at e2") + .0; + initial.drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.01, + vec![egui::Event::PointerMoved(from), pointer_button(from, true)], + &settings, + ) + .drop_without_applying_deltas(); + if drag { + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![egui::Event::PointerMoved(to)], + &settings, + ) + .drop_without_applying_deltas(); + } else { + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![pointer_button(from, false)], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.03, + vec![egui::Event::PointerMoved(to), pointer_button(to, true)], + &settings, + ) + .drop_without_applying_deltas(); + } + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.store.path().with_file_name("learning.json.lock")) + .unwrap(); + lock.lock().unwrap(); + let released = pointer_board_frame( + &mut f, + &ctx, + 1.04, + vec![pointer_button(to, false)], + &settings, + ); + let assert_pawn_at_destination = |output: &egui::FullOutput| { + let meshes = piece_meshes(output); + assert!( + meshes + .iter() + .any(|(texture, rect)| *texture == pawn && rect.contains(to)), + "pawn not painted at destination" + ); + assert!( + !meshes + .iter() + .any(|(texture, rect)| *texture == pawn && rect.contains(from)), + "pawn snapped back to e2" + ); + }; + assert!(f.ui.has_unsaved(), "drag={drag} wrong={wrong}"); + assert!(!f.ui.can_input()); + assert!(f.ui.pending_sounds.is_empty()); + if drag { + assert_pawn_at_destination(&released); + } + released.drop_without_applying_deltas(); + let frame = Instant::now(); + let waiting = pointer_board_frame(&mut f, &ctx, 1.05, vec![], &settings); + assert!(frame.elapsed() < Duration::from_millis(300)); + if drag { + assert_pawn_at_destination(&waiting); + assert!( + f.ui.board + .animation_at(1.05) + .is_none_or(|(_, slides, _)| slides.is_empty()) + ); + } else if !duration.is_zero() { + assert!( + f.ui.board + .animation_at(1.05) + .unwrap() + .1 + .iter() + .any(|(_, source, _)| *source == Square::E2), + "click move must still animate" + ); + } + waiting.drop_without_applying_deltas(); + let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); + assert_pawn_at_destination(&waiting); + waiting.drop_without_applying_deltas(); + assert!( + f.ui.learning.attempts.is_empty(), + "unconfirmed answer affected learning data" + ); + drop(lock); + wait_for_commit(&mut f.ui); + let confirmed = pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings); + assert_pawn_at_destination(&confirmed); + confirmed.drop_without_applying_deltas(); + assert!( + f.ui.board.animation_at(2.01).is_none(), + "commit restarted the move animation" + ); + assert_eq!(f.attempts().len(), 1); + assert_eq!( + f.ui.pending_sounds, + [if wrong { Sound::Wrong } else { Sound::Move }] + ); + if wrong { + f.ui.tick_at(f.ui.playback_deadline().unwrap(), duration, NOW); + pointer_board_frame(&mut f, &ctx, 2.02, vec![], &settings) + .drop_without_applying_deltas(); + assert_eq!(fen4(&f.ui.board_position), fen4(&Chess::default())); + if !duration.is_zero() { + assert!( + f.ui.board + .animation_at(2.02) + .unwrap() + .1 + .iter() + .any(|(_, _, target)| *target == Square::E2), + "wrong move must return to source" + ); + } + } + } + } + } +} + +#[test] +fn dragged_special_moves_keep_auxiliary_effects_and_retry_does_not_move_again() { + let cases = [ + ( + "4k3/8/8/8/8/8/8/4K2R w K - 0 1", + "O-O", + "e1g1", + Square::E1, + Square::G1, + None, + false, + ), + ( + "4k3/8/8/3p4/4P3/8/8/4K3 w - - 0 1", + "exd5", + "e4d5", + Square::E4, + Square::D5, + Some(Square::D5), + false, + ), + ( + "4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", + "exd6", + "e5d6", + Square::E5, + Square::D6, + Some(Square::D5), + false, + ), + ( + "4k3/P7/8/8/8/8/8/4K3 w - - 0 1", + "a8=Q+", + "a7a8q", + Square::A7, + Square::A8, + None, + true, + ), + ]; + let center = |sq: Square| { + egui::pos2( + (u32::from(sq.file()) as f32 + 0.5) * 100.0, + (7.5 - u32::from(sq.rank()) as f32) * 100.0, + ) + }; + for (fen, san, uci, from, to, captured, promotion) in cases { + let pgn = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *"); + let mut f = Fixture::new(&pgn, LearningSide::White, &[uci], "special-drag"); + f.ui.synchronous_commits = false; + f.ui.tick_at(Instant::now(), normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let settings = Settings::default(); + let initial = pointer_board_frame(&mut f, &ctx, 1.0, vec![], &settings); + let captured_texture = captured.map(|sq| { + piece_meshes(&initial) + .into_iter() + .find(|(_, rect)| rect.contains(center(sq))) + .unwrap() + .0 + }); + initial.drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.01, + vec![ + egui::Event::PointerMoved(center(from)), + pointer_button(center(from), true), + ], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.02, + vec![egui::Event::PointerMoved(center(to))], + &settings, + ) + .drop_without_applying_deltas(); + let released = pointer_board_frame( + &mut f, + &ctx, + 1.03, + vec![pointer_button(center(to), false)], + &settings, + ); + if uci == "e1g1" { + let (_, slides, _) = f.ui.board.animation_at(1.03).unwrap(); + assert_eq!(slides.len(), 1); + assert_eq!( + (slides[0].1, slides[0].2), + (Square::H1, Square::F1), + "only the rook should animate after a dragged castle" + ); + } + if let Some(texture) = captured_texture { + assert!( + piece_meshes(&released) + .iter() + .any(|(id, rect)| *id == texture && rect.contains(center(captured.unwrap()))), + "captured piece must still fade out" + ); + } + released.drop_without_applying_deltas(); + if promotion { + assert!( + !f.ui.has_unsaved(), + "promotion must wait for the chosen piece" + ); + pointer_board_frame( + &mut f, + &ctx, + 1.04, + vec![pointer_button(center(to), true)], + &settings, + ) + .drop_without_applying_deltas(); + pointer_board_frame( + &mut f, + &ctx, + 1.05, + vec![pointer_button(center(to), false)], + &settings, + ) + .drop_without_applying_deltas(); + assert_eq!( + f.ui.board_position.board().piece_at(to).unwrap().role, + chess_core::shakmaty::Role::Queen + ); + } + assert!(f.ui.has_unsaved()); + let after = fen4(&f.ui.board_position); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(f.attempts().is_empty()); + assert!(f.ui.pending_sounds.is_empty()); + pointer_board_frame(&mut f, &ctx, 1.1, vec![], &settings).drop_without_applying_deltas(); + let waiting = pointer_board_frame(&mut f, &ctx, 2.0, vec![], &settings); + if let Some(texture) = captured_texture { + assert!( + !piece_meshes(&waiting) + .iter() + .any(|(id, rect)| *id == texture && rect.contains(center(captured.unwrap()))) + ); + } + waiting.drop_without_applying_deltas(); + f.ui.store = valid_store; + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + pointer_board_frame(&mut f, &ctx, 2.01, vec![], &settings).drop_without_applying_deltas(); + assert_eq!(fen4(&f.ui.board_position), after); + assert!(f.ui.board.animation_at(2.01).is_none()); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.ui.pending_sounds, [Sound::Move]); + } +} + +#[test] +fn reused_context_retry_stays_silent_and_responsive_and_persists_once() { + let mut f = Fixture::new( + "1. e4 e5 2. Nf3 Nc6 *", + LearningSide::White, + &["e2e4", "g1f3"], + "reuse-retry", + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, normal(), NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "own-answer".into(), at, NOW)); + let position = fen4(&f.ui.board_position); + assert_eq!(std::mem::take(&mut f.ui.pending_sounds), [Sound::Move]); + let valid_store = f.ui.store.clone(); + f.ui.synchronous_commits = false; + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + f.ui.tick_at(at + normal(), normal(), NOW); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(matches!( + f.ui.pending_commit.as_ref().unwrap().kind, + CommitKind::ReusedContext + )); + let reused_id = f.ui.pending_commit.as_ref().unwrap().attempts[0] + .client_attempt_id + .clone(); + assert_eq!(fen4(&f.ui.board_position), position); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.store = valid_store; + let lock = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(f.store.path().with_file_name("learning.json.lock")) + .unwrap(); + lock.lock().unwrap(); + let unlock = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(600)); + drop(lock); + }); + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + let frame = Instant::now(); + assert!(emitted_sounds(&mut f, &egui::Context::default(), &Settings::default()).is_empty()); + assert!( + frame.elapsed() < Duration::from_millis(300), + "reused context blocked the frame" + ); + assert_eq!(fen4(&f.ui.board_position), position); + assert!(!f.ui.can_input()); + unlock.join().unwrap(); + wait_for_commit(&mut f.ui); + assert!(f.ui.pending_sounds.is_empty()); + f.ui.debug_settle(); + assert_eq!(f.ui.visual_log, ["e7e5"]); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + let attempts = f.attempts(); + assert_eq!(attempts.len(), 3); + assert_eq!( + attempts + .iter() + .filter(|event| event.client_attempt_id == reused_id) + .count(), + 1 + ); + assert_eq!( + attempts + .iter() + .filter(|event| event.event_type.is_independent()) + .count(), + 1 + ); +} + +#[test] +fn async_failed_commit_preserves_event_for_retry_without_double_counting() { + let mut f = Fixture::new("1. e4 *", LearningSide::White, &["e2e4"], "async-retry"); + f.ui.synchronous_commits = false; + tick_with_prime(&mut f.ui, Instant::now(), normal(), NOW); + let valid_store = f.ui.store.clone(); + f.ui.store = LearningStore::with_legacy(valid_store.path(), valid_store.path()); + assert!(f.ui.play_uci_with_id_at("e2e4", "async-retry".to_owned(), Instant::now(), NOW)); + wait_for_commit(&mut f.ui); + assert!(f.ui.save_error.is_some()); + assert!(f.ui.has_unsaved()); + assert!(f.attempts().is_empty()); + f.ui.store = valid_store; + f.ui.retry_pending(Instant::now()); + f.ui.retry_pending(Instant::now()); + wait_for_commit(&mut f.ui); + assert!(!f.ui.has_unsaved()); + assert_eq!(f.attempts().len(), 1); + assert_eq!(f.attempts()[0].client_attempt_id, "async-retry"); +} diff --git a/apps/desktop/src/repertoire_editor.rs b/apps/desktop/src/repertoire_editor.rs deleted file mode 100644 index a3bebfc..0000000 --- a/apps/desktop/src/repertoire_editor.rs +++ /dev/null @@ -1,1070 +0,0 @@ -use chess_core::shakmaty::{Chess, Color, Position, san::SanPlus, uci::UciMove}; -use chess_core::{Game, MoveKind, NodeId}; -use egui::{RichText, Ui}; -use trainer::repertoire::{ - LearningData, LearningItemKey, LearningSide, Library, LibraryStore, MoveLearningAnalytics, - MoveLearningStatus, Repertoire, RepertoireError, RepertoireId, RepertoireTree, SrsSettings, - StatsScope, scoped_move_learning_analytics, -}; - -use crate::board::{BoardState, BoardView}; -use crate::i18n::tr; -use crate::settings::Settings; - -#[derive(Debug)] -pub enum RepertoireEditorAction { - Close, - OpenSettings, - Cancel, - Applied { - repertoire_id: RepertoireId, - library: Library, - }, - Error(String), -} - -pub struct RepertoireEditorUi { - original: Library, - draft: Library, - repertoire_id: RepertoireId, - tree: RepertoireTree, - selected: NodeId, - board: BoardState, - learning: Option, - analytics_cache: Option, String>>, - error: Option, -} - -impl RepertoireEditorUi { - pub fn new(library: &Library, repertoire_id: RepertoireId) -> Result { - let repertoire = library - .repertoire(&repertoire_id) - .ok_or_else(|| RepertoireError::NotFound(repertoire_id.clone()))?; - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let selected = tree.root(); - Ok(Self { - original: library.clone(), - draft: library.clone(), - repertoire_id, - tree, - selected, - board: BoardState::default(), - learning: None, - analytics_cache: None, - error: None, - }) - } - - pub fn set_learning(&mut self, learning: &LearningData) { - self.learning = Some(learning.clone()); - self.analytics_cache = None; - } - - pub fn has_unsaved(&self) -> bool { - self.draft.repertoire(&self.repertoire_id) != self.original.repertoire(&self.repertoire_id) - } - - pub fn show( - &mut self, - ui: &mut Ui, - settings: &Settings, - library_store: &LibraryStore, - ) -> Vec { - let mut actions = Vec::new(); - let mut commands = Vec::new(); - egui::Panel::top("repertoire_editor_header").show(ui, |ui| { - self.show_header(ui, &mut commands); - }); - let available = ui.available_rect_before_wrap(); - 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(), 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| { - 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); - egui::Frame::side_top_panel(ui.style()) - .show(ui, |ui| self.show_panel(ui, &mut commands)); - }); - } else { - 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); - } - EditorCommand::Save => match self.save(library_store) { - Ok(library) => actions.push(RepertoireEditorAction::Applied { - repertoire_id: self.repertoire_id.clone(), - library, - }), - Err(error) => { - self.error = Some(error.clone()); - actions.push(RepertoireEditorAction::Error(error)); - } - }, - EditorCommand::Select(node) => self.select(node), - EditorCommand::SetMainAnswer => { - if let Err(error) = self.set_selected_main_answer() { - self.error = Some(error.clone()); - actions.push(RepertoireEditorAction::Error(error)); - } - } - EditorCommand::ClearMainAnswer => { - self.clear_selected_main_answer(); - } - EditorCommand::SetDisabled(disabled) => { - if let Err(error) = self.set_selected_disabled(disabled) { - self.error = Some(error.clone()); - actions.push(RepertoireEditorAction::Error(error)); - } - } - EditorCommand::SetDepth(depth) => { - if let Some(repertoire) = self.draft.repertoire_mut(&self.repertoire_id) { - repertoire.set_max_plies(depth); - self.analytics_cache = None; - self.error = None; - } - } - } - } - actions - } - - fn show_header(&self, ui: &mut Ui, commands: &mut Vec) { - 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); - } - 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); - }); - } - }); - }); - } - - fn show_board(&mut self, ui: &mut Ui, settings: &Settings) { - let position = self - .tree - .position(self.selected) - .cloned() - .unwrap_or_default(); - let last_move = self - .tree - .game() - .game_move(self.selected) - .and_then(|game_move| match game_move.kind { - MoveKind::Normal(mv) => Some(( - mv.from().unwrap_or_else(|| mv.to()), - crate::board::ui_target(&mv), - )), - MoveKind::Null => None, - }); - let side = ui - .available_width() - .min(ui.available_height()) - .max(1.0) - .floor(); - let available = ui.available_size(); - let offset = egui::vec2( - ((available.x - side) / 2.0).max(0.0).floor(), - ((available.y - side) / 2.0).max(0.0).floor(), - ); - let rect = egui::Rect::from_min_size(ui.cursor().min + offset, egui::vec2(side, side)); - let orientation = settings - .repertoire_modes - .get(self.repertoire_id.as_str()) - .map_or(Color::White, |(mode, _)| match mode { - trainer::repertoire::TrainingMode::Black => Color::Black, - trainer::repertoire::TrainingMode::White - | trainer::repertoire::TrainingMode::Both => Color::White, - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - BoardView { - pos: &position, - orientation, - last_move, - arrows: &[], - circles: &[], - badge: None, - interactive: false, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: false, - alert: None, - } - .show(ui, &mut self.board); - }); - } - - fn show_panel(&mut self, ui: &mut Ui, commands: &mut Vec) { - 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| { - ui.set_width(ui.available_width()); - if let Some(error) = self.error.clone() { - ui.add( - egui::Label::new(RichText::new(&error).color(ui.visuals().error_fg_color)) - .truncate(), - ) - .on_hover_text(error); - ui.separator(); - } - if let Some(repertoire) = self.draft.repertoire(&self.repertoire_id) { - let mut 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(); - egui::CollapsingHeader::new(tr("Move analytics")) - .id_salt("repertoire_editor_analytics") - .show(ui, |ui| self.show_analytics(ui)); - }); - } - - fn show_selected(&self, ui: &mut Ui, commands: &mut Vec) { - let Some((position_fen4, expected_uci, _)) = self.selected_move_parts() else { - ui.label(tr("Select a move in the PGN tree")); - return; - }; - let game = self.tree.game(); - if let Some(label) = game.move_label(self.selected) { - ui.strong(crate::san::show(&label)); - } - let main_answer = game - .parent(self.selected) - .and_then(|parent| self.effective_main_answer(parent)); - let is_main = main_answer.as_deref() == Some(expected_uci.as_str()); - if let Some(main_answer) = main_answer { - let label = game - .position_before(self.selected) - .and_then(|position| san_for_uci(position, &main_answer)) - .unwrap_or_else(|| "—".to_owned()); - ui.label(format!("{}: {label}", tr("Preferred move"))); - } - let has_override = self - .draft - .repertoire(&self.repertoire_id) - .and_then(|repertoire| repertoire.main_answer_override(&position_fen4)) - .is_some(); - ui.add( - egui::Label::new(tr( - "All enabled variations are trained. The preferred move only affects their order.", - )) - .wrap(), - ); - let disabled = self - .draft - .repertoire(&self.repertoire_id) - .zip(self.tree.path(self.selected)) - .is_some_and(|(repertoire, path)| repertoire.is_prefix_disabled(path)); - ui.horizontal_wrapped(|ui| { - if ui - .add_enabled(!is_main, egui::Button::new(tr("Prefer this move"))) - .clicked() - { - commands.push(EditorCommand::SetMainAnswer); - } - if ui - .add_enabled(has_override, egui::Button::new(tr("PGN order"))) - .clicked() - { - commands.push(EditorCommand::ClearMainAnswer); - } - if ui - .button(if disabled { - tr("Enable") - } else { - tr("Disable") - }) - .clicked() - { - commands.push(EditorCommand::SetDisabled(!disabled)); - } - }); - if disabled { - ui.label(tr("Disabled for training")); - } - } - - fn show_tree(&self, ui: &mut Ui, commands: &mut Vec) { - ui.strong(tr("PGN tree")); - let root = self.tree.root(); - if ui - .add(egui::Button::selectable(self.selected == root, tr("Initial position")).truncate()) - .clicked() - { - commands.push(EditorCommand::Select(root)); - } - for row in tree_rows(&self.tree) { - let Some(label) = self.tree.game().move_label(row.node) else { - continue; - }; - let mut label = crate::san::show(&label).into_owned(); - if row.variation { - label = format!("↳ {label}"); - } - if self - .tree - .game() - .parent(row.node) - .and_then(|parent| self.tree.position_key(parent)) - .and_then(|position| { - self.draft - .repertoire(&self.repertoire_id)? - .main_answer_override(position) - }) - .zip(self.tree.game().game_move(row.node).and_then(|mv| mv.uci())) - .is_some_and(|(main, uci)| main == uci) - { - label.push_str(&format!(" · {}", tr("preferred"))); - } - if self - .draft - .repertoire(&self.repertoire_id) - .zip(self.tree.path(row.node)) - .is_some_and(|(repertoire, path)| repertoire.is_prefix_disabled(path)) - { - label.push_str(&format!(" · {}", tr("disabled"))); - } - ui.horizontal(|ui| { - let indentation = (row.indentation as f32 * 14.0).min(ui.available_width() * 0.35); - ui.add_space(indentation); - if ui - .add_sized( - [ui.available_width(), 24.0], - egui::Button::selectable(self.selected == row.node, "") - .left_text(label) - .truncate(), - ) - .clicked() - { - commands.push(EditorCommand::Select(row.node)); - } - }); - } - } - - fn show_analytics(&mut self, ui: &mut Ui) { - if self.selected == self.tree.root() { - ui.label(tr("Select a move to see its learning analytics")); - return; - } - if self.learning.is_none() { - ui.label(tr("Shared learning data is not connected")); - return; - } - match self.selected_analytics() { - Ok(Some(analytics)) => { - show_move_analytics(ui, &analytics, self.tree.game(), self.selected) - } - Ok(None) => { - ui.label(tr("No learning data for this move")); - } - Err(error) => { - ui.colored_label(ui.visuals().error_fg_color, error); - } - } - } - - fn select(&mut self, node: NodeId) { - if self.tree.game().is_attached(node) { - self.selected = node; - self.board.clear(); - self.analytics_cache = None; - } - } - - fn cancel(&mut self) { - self.draft = self.original.clone(); - self.selected = self.tree.root(); - self.board.clear(); - self.analytics_cache = None; - self.error = None; - } - - fn save(&mut self, library_store: &LibraryStore) -> Result { - let draft = self - .draft - .repertoire(&self.repertoire_id) - .cloned() - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - let original = self - .original - .repertoire(&self.repertoire_id) - .cloned() - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - let mut updated = original; - updated.max_plies = draft.max_plies; - updated.disabled_prefixes = draft.disabled_prefixes; - updated.main_answer_overrides = draft.main_answer_overrides; - let mut saved = self.original.clone(); - let slot = saved - .repertoire_mut(&self.repertoire_id) - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - *slot = updated; - library_store - .save(&mut saved) - .map_err(|error| error.to_string())?; - self.original = saved.clone(); - self.draft = saved.clone(); - self.analytics_cache = None; - self.error = None; - Ok(saved) - } - - fn selected_move_parts(&self) -> Option<(String, String, LearningSide)> { - let game = self.tree.game(); - let parent = game.parent(self.selected)?; - let expected_uci = game.game_move(self.selected)?.uci()?; - let position_fen4 = self.tree.position_key(parent)?.to_owned(); - let side = LearningSide::from(game.position(parent)?.turn()); - Some((position_fen4, expected_uci, side)) - } - - fn set_selected_main_answer(&mut self) -> Result<(), String> { - let (position_fen4, expected_uci, side) = self - .selected_move_parts() - .ok_or_else(|| tr("Select a move in the PGN tree").to_owned())?; - self.assign_main_answer_checked(&position_fen4, &expected_uci, side) - } - - fn assign_main_answer_checked( - &mut self, - position_fen4: &str, - expected_uci: &str, - side: LearningSide, - ) -> Result<(), String> { - let repertoire = self - .draft - .repertoire_mut(&self.repertoire_id) - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - repertoire - .set_main_answer_override(position_fen4, expected_uci, side) - .map_err(|_| { - tr("The selected move cannot be the main answer for this position").to_owned() - })?; - self.analytics_cache = None; - self.error = None; - Ok(()) - } - - fn clear_selected_main_answer(&mut self) { - let Some((position_fen4, _, _)) = self.selected_move_parts() else { - return; - }; - if let Some(repertoire) = self.draft.repertoire_mut(&self.repertoire_id) { - repertoire.clear_main_answer_override(&position_fen4); - self.analytics_cache = None; - self.error = None; - } - } - - fn set_selected_disabled(&mut self, disabled: bool) -> Result<(), String> { - let path = self - .tree - .path(self.selected) - .filter(|path| !path.is_empty()) - .map(<[String]>::to_vec) - .ok_or_else(|| tr("Select a move in the PGN tree").to_owned())?; - let repertoire = self - .draft - .repertoire_mut(&self.repertoire_id) - .ok_or_else(|| tr("Repertoire not found").to_owned())?; - if disabled { - repertoire - .set_prefix_disabled(&path, true) - .map_err(|_| tr("The selected PGN branch cannot be disabled").to_owned())?; - } else { - let blocking: Vec> = repertoire - .disabled_prefixes - .iter() - .filter(|prefix| path.starts_with(prefix)) - .cloned() - .collect(); - for prefix in blocking { - repertoire - .set_prefix_disabled(&prefix, false) - .map_err(|_| tr("The selected PGN branch cannot be enabled").to_owned())?; - } - } - self.analytics_cache = None; - self.error = None; - Ok(()) - } - - fn effective_main_answer(&self, parent: NodeId) -> Option { - let repertoire = self.draft.repertoire(&self.repertoire_id)?; - effective_main_answer(repertoire, &self.tree, parent) - } - - fn selected_analytics(&mut self) -> Result, String> { - if self.analytics_cache.is_none() { - let result = self.compute_selected_analytics(); - self.analytics_cache = Some(result); - } - self.analytics_cache.clone().unwrap_or(Ok(None)) - } - - fn compute_selected_analytics(&self) -> Result, String> { - let Some(learning) = &self.learning else { - return Ok(None); - }; - let Some((position_fen4, expected_uci, side)) = self.selected_move_parts() else { - return Ok(None); - }; - let key = LearningItemKey::local(position_fen4, expected_uci); - let mut scope = StatsScope::for_repertoire(self.repertoire_id.clone(), side, now()); - scope.only_active = false; - let analytics = - scoped_move_learning_analytics(&self.draft, learning, &scope, &SrsSettings::default()) - .map_err(|error| error.to_string())?; - Ok(analytics.into_iter().find(|item| item.key == key)) - } -} - -#[derive(Clone, Copy)] -enum EditorCommand { - Close, - OpenSettings, - Cancel, - Save, - Select(NodeId), - SetMainAnswer, - ClearMainAnswer, - SetDisabled(bool), - SetDepth(u32), -} - -#[derive(Clone, Copy)] -struct TreeRow { - node: NodeId, - indentation: u32, - variation: bool, -} - -fn tree_rows(tree: &RepertoireTree) -> Vec { - fn append(game: &Game, parent: NodeId, indentation: u32, rows: &mut Vec) { - for (index, child) in game.children(parent).iter().copied().enumerate() { - let variation = index > 0; - let child_indentation = indentation + u32::from(variation); - rows.push(TreeRow { - node: child, - indentation: child_indentation, - variation, - }); - append(game, child, child_indentation, rows); - } - } - - let mut rows = Vec::new(); - append(tree.game(), tree.root(), 0, &mut rows); - rows -} - -fn effective_main_answer( - repertoire: &Repertoire, - tree: &RepertoireTree, - parent: NodeId, -) -> Option { - let position_fen4 = tree.position_key(parent)?; - let mut candidates = Vec::new(); - for transposition in tree.transpositions(parent) { - if tree.path(*transposition).is_none() { - continue; - } - for child in tree.game().children(*transposition) { - if tree.path(*child).is_none() { - continue; - } - let Some(uci) = tree.game().game_move(*child).and_then(|mv| mv.uci()) else { - continue; - }; - if !candidates.contains(&uci) { - candidates.push(uci); - } - } - } - repertoire - .main_answer_override(position_fen4) - .filter(|override_uci| candidates.iter().any(|uci| uci == override_uci)) - .map(str::to_owned) - .or_else(|| candidates.into_iter().next()) -} - -fn show_move_analytics( - ui: &mut Ui, - analytics: &MoveLearningAnalytics, - game: &Game, - selected: NodeId, -) { - egui::Grid::new("repertoire_editor_move_analytics") - .num_columns(2) - .spacing([12.0, 4.0]) - .show(ui, |ui| { - ui.label(tr("Status")); - ui.label(move_status_label(analytics.status)); - ui.end_row(); - ui.label(tr("Accuracy")); - ui.label( - analytics - .accuracy_percent - .map_or_else(|| "—".to_owned(), |value| format!("{value:.0} %")), - ); - ui.end_row(); - ui.label(tr("Correct streak")); - ui.label(analytics.correct_streak.to_string()); - ui.end_row(); - ui.label(tr("Wrong streak")); - ui.label(analytics.wrong_streak.to_string()); - ui.end_row(); - ui.label(tr("Next due")); - ui.label(format_time(analytics.next_review_at)); - ui.end_row(); - ui.label(tr("Response median")); - ui.label( - analytics - .response_time_median_ms - .map_or_else(|| "—".to_owned(), format_duration_ms), - ); - ui.end_row(); - }); - ui.horizontal_wrapped(|ui| { - ui.label(format!("{}:", tr("Wrong moves"))); - if analytics.wrong_move_histogram.is_empty() { - ui.label("—"); - } else { - for (uci, stats) in &analytics.wrong_move_histogram { - let label = game - .position_before(selected) - .and_then(|position| san_for_uci(position, uci)) - .unwrap_or_else(|| tr("Unknown move").to_owned()); - ui.label(format!("{label} × {}", stats.count)); - } - } - }); -} - -fn move_status_label(status: MoveLearningStatus) -> &'static str { - tr(match status { - MoveLearningStatus::Unseen => "Unseen", - MoveLearningStatus::Learning => "Learning", - MoveLearningStatus::LearntFresh => "Learnt", - MoveLearningStatus::Uncertain => "Uncertain", - }) -} - -fn san_for_uci(position: &Chess, uci: &str) -> Option { - let mv = uci.parse::().ok()?.to_move(position).ok()?; - Some(crate::san::show(&SanPlus::from_move(position.clone(), mv).to_string()).into_owned()) -} - -fn format_duration_ms(milliseconds: f64) -> String { - if milliseconds >= 1000.0 { - format!("{:.2} s", milliseconds / 1000.0) - } else { - format!("{milliseconds:.0} ms") - } -} - -fn format_time(at: Option) -> String { - at.and_then(|at| chrono::DateTime::from_timestamp(at, 0)) - .map(|at| { - at.with_timezone(&chrono::Local) - .format("%Y-%m-%d %H:%M") - .to_string() - }) - .unwrap_or_else(|| "—".to_owned()) -} - -fn now() -> i64 { - chrono::Local::now().timestamp() -} - -#[cfg(test)] -mod tests { - use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, Ordering}; - - use trainer::repertoire::{LearningStore, LearningStoreData, WrongMoveStats, fen4}; - - use super::*; - - static NEXT_TEST: AtomicU64 = AtomicU64::new(1); - - struct TestDir(PathBuf); - - impl TestDir { - fn new(name: &str) -> Self { - let path = std::env::temp_dir().join(format!( - "cp-repertoire-editor-{}-{}-{name}", - std::process::id(), - NEXT_TEST.fetch_add(1, Ordering::Relaxed) - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn join(&self, path: impl AsRef) -> PathBuf { - self.0.join(path) - } - } - - impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } - } - - fn library() -> (Library, RepertoireId) { - let mut library = Library::default(); - let id = library - .create( - "King and queen pawn", - &chess_core::parse_str("1. e4 (1. d4) e5 *").game, - ) - .unwrap(); - (library, id) - } - - fn child(editor: &RepertoireEditorUi, index: usize) -> NodeId { - editor.tree.game().children(editor.tree.root())[index] - } - - #[test] - fn 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(); - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - let root_fen = fen4(editor.tree.game().start().position()); - let pgn = library.repertoire(&id).unwrap().pgn.clone(); - - let wrong_side = editor - .assign_main_answer_checked(&root_fen, "d2d4", LearningSide::Black) - .unwrap_err(); - assert!(!wrong_side.contains("d2d4")); - let missing_move = editor - .assign_main_answer_checked(&root_fen, "c2c4", LearningSide::White) - .unwrap_err(); - assert!(!missing_move.contains("c2c4")); - assert!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_overrides - .is_empty() - ); - - editor.select(child(&editor, 1)); - editor.set_selected_main_answer().unwrap(); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - Some("d2d4") - ); - assert_eq!( - editor.effective_main_answer(editor.tree.root()).as_deref(), - Some("d2d4") - ); - assert_eq!(editor.tree.game().children(editor.tree.root()).len(), 2); - assert_eq!(editor.draft.repertoire(&id).unwrap().pgn, pgn); - - editor.clear_selected_main_answer(); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - None - ); - assert_eq!( - editor.effective_main_answer(editor.tree.root()).as_deref(), - Some("e2e4") - ); - assert_eq!(editor.tree.game().children(editor.tree.root()).len(), 2); - assert_eq!(editor.draft.repertoire(&id).unwrap().pgn, pgn); - } - - #[test] - fn depth_disable_and_override_roundtrip_preserve_source_and_shared_learning() { - let dir = TestDir::new("roundtrip"); - let source = dir.join("source.pgn"); - let source_bytes = b"[Event \"Original\"]\n\n1. e4 (1. d4) e5 *\n"; - std::fs::write(&source, source_bytes).unwrap(); - let (mut library, id) = library(); - let second = library - .create( - "Shared transposition", - &chess_core::parse_str("1. e4 (1. d4) e5 *").game, - ) - .unwrap(); - library.repertoire_mut(&id).unwrap().path = Some(source.clone()); - let original_pgn = library.repertoire(&id).unwrap().pgn.clone(); - let library_store = LibraryStore::new(dir.join("library.json")); - library_store.save(&mut library).unwrap(); - - let mut learning = LearningData::default(); - let root_fen = fen4(library.repertoire(&id).unwrap().game().start().position()); - let key = LearningItemKey::local(root_fen.clone(), "d2d4"); - let shared_item = { - let item = learning.ensure_item(key.clone()); - item.introduced = true; - item.correct_streak = 4; - item.correct_count = 7; - item.wrong_count = 2; - item.next_review_at = Some(1_900_000_000); - item.independent_response_times_ms = vec![500, 700, 900]; - item.wrong_move_histogram.insert( - "c2c4".into(), - WrongMoveStats { - count: 2, - last_at: 1_800_000_000, - }, - ); - item.clone() - }; - let learning_store = LearningStore::new(dir.join("learning.json")); - let learning_data = LearningStoreData { - learning: learning.clone(), - ..LearningStoreData::default() - }; - std::fs::write( - learning_store.path(), - serde_json::to_vec_pretty(&learning_data).unwrap(), - ) - .unwrap(); - let learning_bytes = std::fs::read(learning_store.path()).unwrap(); - - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - editor.set_learning(&learning); - editor.select(child(&editor, 1)); - editor.set_selected_main_answer().unwrap(); - editor.set_selected_disabled(true).unwrap(); - editor.draft.repertoire_mut(&id).unwrap().set_max_plies(7); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - Some("d2d4") - ); - assert_eq!( - editor.effective_main_answer(editor.tree.root()).as_deref(), - Some("d2d4") - ); - - let analytics = editor.selected_analytics().unwrap().unwrap(); - assert_eq!(analytics.key, key); - assert_eq!(analytics.correct_streak, 4); - assert_eq!(analytics.correct_count, 7); - assert_eq!(analytics.response_time_median_ms, Some(700.0)); - - let saved = editor.save(&library_store).unwrap(); - assert!(!editor.has_unsaved()); - assert_eq!(saved.repertoire(&id).unwrap().max_plies, 7); - assert_eq!(saved.repertoire(&id).unwrap().disabled_prefixes.len(), 1); - assert_eq!(saved.repertoire(&id).unwrap().pgn, original_pgn); - assert!(saved.repertoire(&second).is_some()); - assert_eq!(std::fs::read(&source).unwrap(), source_bytes); - assert_eq!( - std::fs::read(learning_store.path()).unwrap(), - learning_bytes - ); - - editor.set_selected_disabled(false).unwrap(); - assert_eq!( - editor - .draft - .repertoire(&id) - .unwrap() - .main_answer_override(&root_fen), - Some("d2d4") - ); - let saved = editor.save(&library_store).unwrap(); - assert!(saved.repertoire(&id).unwrap().disabled_prefixes.is_empty()); - assert_eq!(saved.repertoire(&id).unwrap().pgn, original_pgn); - assert_eq!(std::fs::read(&source).unwrap(), source_bytes); - assert_eq!( - std::fs::read(learning_store.path()).unwrap(), - learning_bytes - ); - - let loaded = library_store.load().unwrap(); - assert_eq!(loaded.repertoire(&id).unwrap().max_plies, 7); - assert!(loaded.repertoire(&id).unwrap().disabled_prefixes.is_empty()); - assert_eq!(loaded.repertoire(&id).unwrap().pgn, original_pgn); - let restored_learning = learning_store.load().unwrap(); - assert_eq!(restored_learning.learning.item(&key), Some(&shared_item)); - } - - #[test] - fn cancel_restores_the_whole_draft_without_saving() { - let dir = TestDir::new("cancel"); - let (mut library, id) = library(); - let library_store = LibraryStore::new(dir.join("library.json")); - library_store.save(&mut library).unwrap(); - let before = std::fs::read(library_store.path()).unwrap(); - let original = library.repertoire(&id).unwrap().clone(); - let mut editor = RepertoireEditorUi::new(&library, id.clone()).unwrap(); - editor.select(child(&editor, 1)); - editor.set_selected_main_answer().unwrap(); - editor.set_selected_disabled(true).unwrap(); - editor.draft.repertoire_mut(&id).unwrap().set_max_plies(3); - assert!(editor.has_unsaved()); - - editor.cancel(); - - assert!(!editor.has_unsaved()); - assert_eq!(editor.draft.repertoire(&id), Some(&original)); - assert_eq!(editor.selected, editor.tree.root()); - assert_eq!(std::fs::read(library_store.path()).unwrap(), before); - } - - #[test] - fn rav_rows_are_indented_without_flattening_the_mainline() { - let (library, id) = library(); - let editor = RepertoireEditorUi::new(&library, id).unwrap(); - let rows = tree_rows(&editor.tree); - assert_eq!(rows.len(), 3); - assert_eq!(rows[0].indentation, 0); - assert!(!rows[0].variation); - assert_eq!(rows[1].indentation, 0); - assert!(!rows[1].variation); - assert_eq!(rows[2].indentation, 1); - assert!(rows[2].variation); - } -} diff --git a/apps/desktop/src/repertoire_training.rs b/apps/desktop/src/repertoire_training.rs deleted file mode 100644 index b31d060..0000000 --- a/apps/desktop/src/repertoire_training.rs +++ /dev/null @@ -1,1604 +0,0 @@ -#![allow(dead_code)] - -use std::{sync::mpsc, time::Duration}; - -use chess_core::shakmaty::{Chess, Color, Move, Position, Square, uci::UciMove}; -use chess_core::{Annotation, CommentPart, MoveKind, parse_comment}; -use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Ui, vec2}; -use trainer::repertoire::{ - Candidate, QueueMode, Repertoire, RepertoireTree, SessionError, SrsPolicy, StatsData, - StatsStore, TrainingMode, TrainingScope, TrainingSession, TrainingVerdict, -}; - -use crate::assets::Sound; -use crate::board::{Arrow, Badge, BoardState, BoardView}; -use crate::i18n::{tr, trf}; -use crate::settings::Settings; - -const WRONG_SHOWN: Duration = Duration::from_millis(400); - -pub enum TrainingAction { - Back, - Sound(Sound), - Toast(String), -} - -struct Flash { - after: Chess, - from: Square, - to: Square, - until: web_time::Instant, - wrong: bool, -} - -struct NextPathJob { - generation: u64, - rx: mpsc::Receiver<(u64, Result)>, -} - -#[derive(Default)] -pub(crate) struct BoardAnnotations { - pub(crate) arrows: Vec, - pub(crate) circles: Vec<(Square, Color32)>, - pub(crate) badge: Option, -} - -pub struct TrainingUi { - repertoire: Repertoire, - saved_stats: StatsData, - discard_requested: bool, - next_job: Option, - next_generation: u64, - mode: TrainingMode, - queue_mode: QueueMode, - policy: SrsPolicy, - session: TrainingSession, - store: StatsStore, - board: BoardState, - flipped: bool, - positions: Vec, - position_path_len: usize, - position_task_start: usize, - task_start: usize, - task_origin: Chess, - view_ply: usize, - flash: Option, - hint: Option<(Square, Square)>, - message: Option, - save_error: Option, - confirm_discard: bool, - completed_targets: usize, - target_limit: usize, -} - -impl TrainingUi { - #[cfg(test)] - pub fn new( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - store: StatsStore, - flipped: bool, - ) -> Result { - let policy = initial_policy(repertoire, &scope, mode, queue_mode, &stats); - Self::new_with_policy( - repertoire, scope, mode, queue_mode, stats, store, flipped, policy, - ) - } - - pub fn new_random( - repertoire: &Repertoire, - mode: TrainingMode, - stats: StatsData, - store: StatsStore, - flipped: bool, - ) -> Result { - let session = TrainingSession::new_random(repertoire, mode, stats, now())?; - let task_origin = if session.scope().include_context { - repertoire.game().start().position().clone() - } else { - session.scope_start_position().clone() - }; - let mut training = Self { - repertoire: repertoire.clone(), - saved_stats: session.stats().clone(), - discard_requested: false, - next_job: None, - next_generation: 0, - mode, - queue_mode: QueueMode::Practice, - policy: SrsPolicy::Due, - session, - store, - board: BoardState::default(), - flipped: match mode { - TrainingMode::White => false, - TrainingMode::Black => true, - TrainingMode::Both => flipped, - }, - positions: Vec::new(), - position_path_len: usize::MAX, - position_task_start: usize::MAX, - task_start: 0, - task_origin, - view_ply: 0, - flash: None, - hint: None, - message: None, - save_error: None, - confirm_discard: false, - completed_targets: 0, - target_limit: usize::MAX, - }; - training.save(); - Ok(training) - } - - #[allow(clippy::too_many_arguments, dead_code)] - pub fn new_with_policy( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - store: StatsStore, - flipped: bool, - policy: SrsPolicy, - ) -> Result { - let target_limit = target_count(repertoire, &scope, mode, queue_mode, policy, &stats); - let saved_stats = stats.clone(); - let session = if queue_mode == QueueMode::SpacedRepetition { - TrainingSession::scoped_srs(repertoire, scope, mode, stats, now(), policy)? - } else { - TrainingSession::scoped(repertoire, scope, mode, queue_mode, stats, now())? - }; - let task_origin = if session.scope().include_context { - repertoire.game().start().position().clone() - } else { - session.scope_start_position().clone() - }; - Ok(Self { - repertoire: repertoire.clone(), - saved_stats, - discard_requested: false, - next_job: None, - next_generation: 0, - mode, - queue_mode, - policy, - session, - store, - board: BoardState::default(), - flipped: match mode { - TrainingMode::White => false, - TrainingMode::Black => true, - TrainingMode::Both => flipped, - }, - positions: Vec::new(), - position_path_len: usize::MAX, - position_task_start: usize::MAX, - task_start: 0, - task_origin, - view_ply: 0, - flash: None, - hint: None, - message: None, - save_error: None, - confirm_discard: false, - completed_targets: 0, - target_limit, - }) - } - - fn is_path_practice(&self) -> bool { - self.mode == TrainingMode::Both || self.queue_mode == QueueMode::Practice - } - - pub fn repertoire_id(&self) -> &trainer::repertoire::RepertoireId { - &self.repertoire.id - } - - pub fn target_available(&self) -> bool { - !self.session.is_done() - && (self.session.target().is_some() - || (self.is_path_practice() && !self.session.candidates().is_empty())) - } - - pub fn stats(&self) -> &StatsData { - &self.saved_stats - } - - pub fn has_unsaved(&self) -> bool { - self.save_error.is_some() - } - - pub fn is_finished(&self) -> bool { - self.session.is_done() - } - - fn refresh_positions(&mut self) { - if self.position_path_len == self.session.path().len() - && self.position_task_start == self.task_start - { - return; - } - self.position_path_len = self.session.path().len(); - self.position_task_start = self.task_start; - self.positions.clear(); - // Replay the actual section from its full starting position. FEN4 is an - // identity key only: it deliberately omits move counters and history. - let mut position = self.task_origin.clone(); - self.positions.push(position.clone()); - for played in &self.session.path()[self.task_start..] { - let Some(mv) = played - .uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&position).ok()) - else { - self.positions.clear(); - self.positions.push(self.session.position().clone()); - self.view_ply = 0; - return; - }; - position.play_unchecked(mv); - self.positions.push(position.clone()); - } - self.view_ply = self.view_ply.min(self.positions.len().saturating_sub(1)); - if self.view_ply == 0 && !self.positions.is_empty() { - self.view_ply = self.positions.len() - 1; - } - } - - fn go_end(&mut self) { - self.view_ply = self.positions.len().saturating_sub(1); - } - - fn save(&mut self) { - match self.store.save(self.session.stats_mut()) { - Ok(()) => { - self.saved_stats = self.session.stats().clone(); - self.save_error = None; - } - Err(error) => self.save_error = Some(error.to_string()), - } - } - - fn play(&mut self, mv: Move) { - if self.is_finished() - || self.flash.is_some() - || self.save_error.is_some() - || self.next_job.is_some() - { - return; - } - let mut after = self.session.position().clone(); - after.play_unchecked(mv); - let from = mv.from().unwrap_or_else(|| mv.to()); - let to = crate::board::ui_target(&mv); - let verdict = self.session.play(mv, now()); - match verdict { - Ok(TrainingVerdict::Right | TrainingVerdict::Finished) => { - self.completed_targets += usize::from(self.mode != TrainingMode::Both); - self.hint = None; - self.message = Some( - if self.queue_mode == QueueMode::SpacedRepetition - && self.session.attempts().last().is_some_and(|a| a.hinted) - { - tr("Accepted · it will be repeated sooner").to_owned() - } else { - tr("Move accepted").to_owned() - }, - ); - self.update_task_start(); - self.save(); - self.refresh_positions(); - self.go_end(); - } - Ok(TrainingVerdict::Wrong) => { - self.message = Some(tr("This move is not in the enabled repertoire. Try another move or show a hint.").to_owned()); - self.flash = Some(Flash { - after, - from, - to, - until: web_time::Instant::now() + WRONG_SHOWN, - wrong: true, - }); - self.save(); - } - Ok(TrainingVerdict::TryAgain) => { - self.message = - Some(tr("Choose a move from your repertoire or show a hint.").to_owned()); - } - Ok(TrainingVerdict::Done) => {} - Err(error) => self.message = Some(error.to_string()), - } - } - - fn restart(&mut self) { - if self.save_error.is_some() || self.next_job.is_some() { - return; - } - match self.session.restart(now()) { - Ok(()) => self.after_run_reset(), - Err(error) => self.message = Some(error.to_string()), - } - } - - fn next_path(&mut self) { - if self.save_error.is_some() || self.next_job.is_some() || !self.is_path_practice() { - return; - } - let prepared = match self.session.prepare_next_path() { - Ok(prepared) => prepared, - Err(error) => { - self.message = Some(error.to_string()); - return; - } - }; - let repertoire = self.repertoire.clone(); - let (tx, rx) = mpsc::channel(); - self.next_generation = self.next_generation.wrapping_add(1); - let generation = self.next_generation; - self.next_job = Some(NextPathJob { generation, rx }); - if let Err(error) = crate::platform::spawn("repertoire-training-next", move || { - let result = prepared - .run(&repertoire, now()) - .map_err(|error| error.to_string()); - let _ = tx.send((generation, result)); - }) { - self.next_job = None; - self.message = Some(error.to_string()); - } - } - - fn poll_next(&mut self) { - let (generation, result) = { - let Some(job) = &self.next_job else { - return; - }; - match job.rx.try_recv() { - Ok(result) => result, - Err(mpsc::TryRecvError::Empty) => return, - Err(mpsc::TryRecvError::Disconnected) => ( - job.generation, - Err("next-path worker stopped without a result".to_owned()), - ), - } - }; - self.apply_next(generation, result); - } - - fn apply_next(&mut self, generation: u64, result: Result) { - if generation != self.next_generation - || self - .next_job - .as_ref() - .is_none_or(|job| job.generation != generation) - { - return; - } - self.next_job = None; - match result { - Ok(session) => { - self.session = session; - self.after_run_reset(); - self.save(); - } - Err(error) => self.message = Some(error.to_string()), - } - } - - #[cfg(test)] - fn deliver_next(&mut self) { - let (generation, result) = self - .next_job - .as_ref() - .expect("a pending next-path job") - .rx - .recv_timeout(Duration::from_secs(5)) - .expect("next-path worker result"); - self.apply_next(generation, result); - } - - fn after_run_reset(&mut self) { - self.completed_targets = 0; - self.target_limit = target_count( - &self.repertoire, - self.session.scope(), - self.mode, - self.queue_mode, - self.policy, - self.session.stats(), - ); - self.task_start = 0; - self.task_origin = if self.session.scope().include_context { - self.repertoire.game().start().position().clone() - } else { - self.session.scope_start_position().clone() - }; - self.flash = None; - self.hint = None; - self.message = None; - self.position_path_len = usize::MAX; - self.position_task_start = usize::MAX; - self.view_ply = 0; - self.board.clear(); - self.refresh_positions(); - self.go_end(); - } - - fn update_task_start(&mut self) { - if self.is_path_practice() { - return; - } - if self.session.target().is_some() { - self.task_origin = if self.session.scope().include_context { - self.repertoire.game().start().position().clone() - } else { - self.session.position().clone() - }; - } - self.task_start = match self.session.target() { - Some(target) if self.session.scope().include_context => { - self.session.path().len().saturating_sub(target.path.len()) - } - Some(_) => self.session.path().len(), - None => self.task_start, - }; - } - - fn keyboard(&mut self, ui: &Ui, actions: &mut Vec) { - if ui.ctx().egui_wants_keyboard_input() || self.next_job.is_some() { - return; - } - let mut command = None; - ui.input_mut(|input| { - if input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, Key::W)) - || (!self.board.is_busy() && input.consume_key(Modifiers::NONE, Key::Escape)) - { - command = Some("back"); - } else if input.consume_key(Modifiers::NONE, Key::F) { - command = Some("flip"); - } else if input.consume_key(Modifiers::NONE, Key::L) - || input.consume_shortcut(&KeyboardShortcut::new(Modifiers::SHIFT, Key::A)) - { - command = Some("engine"); - } else if self.is_finished() && input.consume_key(Modifiers::NONE, Key::Enter) { - command = Some(if self.is_path_practice() { - "next" - } else { - "restart" - }); - } else if input.consume_key(Modifiers::NONE, Key::ArrowLeft) { - command = Some("left"); - } else if input.consume_key(Modifiers::NONE, Key::ArrowRight) { - command = Some("right"); - } else if input.consume_key(Modifiers::NONE, Key::Home) { - command = Some("home"); - } else if input.consume_key(Modifiers::NONE, Key::End) { - command = Some("end"); - } - }); - match command { - Some("back") => { - if self.save_error.is_some() { - self.confirm_discard = true; - } else { - actions.push(TrainingAction::Back); - } - } - Some("flip") => self.flipped = !self.flipped, - Some("engine") => actions.push(TrainingAction::Toast( - tr("The engine is off while training").to_owned(), - )), - Some("restart") => self.restart(), - Some("next") => self.next_path(), - Some("left") => self.view_ply = self.view_ply.saturating_sub(1), - Some("right") => { - self.view_ply = (self.view_ply + 1).min(self.positions.len().saturating_sub(1)); - } - Some("home") => self.view_ply = 0, - Some("end") => self.go_end(), - _ => {} - } - } - - fn board(&mut self, ui: &mut Ui, settings: &Settings, actions: &mut Vec) { - self.refresh_positions(); - let normal = self - .positions - .get(self.view_ply) - .cloned() - .unwrap_or_else(|| self.session.position().clone()); - let (position, alert) = match &self.flash { - Some(flash) => ( - flash.after.clone(), - flash.wrong.then_some((flash.from, flash.to)), - ), - None => (normal, None), - }; - let last_move = self.flash.as_ref().map(|f| (f.from, f.to)).or_else(|| { - self.view_ply.checked_sub(1).and_then(|index| { - let mv = self.session.path().get(self.task_start + index)?; - let before = self.positions.get(index)?; - let mv = mv.uci.parse::().ok()?.to_move(before).ok()?; - Some(( - mv.from().unwrap_or_else(|| mv.to()), - crate::board::ui_target(&mv), - )) - }) - }); - let annotations = if self.view_ply + 1 == self.positions.len() { - pgn_annotations(&self.session) - } else { - BoardAnnotations::default() - }; - let mut arrows = annotations.arrows; - arrows.extend(self.hint.map(|(from, to)| Arrow { - from, - to, - color: Color32::from_rgba_unmultiplied(21, 120, 27, 190), - weight: 1.0, - })); - let circles = annotations.circles; - let area = ui.available_rect_before_wrap(); - let side = area.width().min(area.height()).max(1.0).floor(); - let left = area.left() + ((area.width() - side) / 2.0).max(0.0).floor(); - let top = area.top() + ((area.height() - side) / 2.0).max(0.0).floor(); - let rect = egui::Rect::from_min_size(egui::pos2(left, top), vec2(side, side)); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - let view = BoardView { - pos: &position, - orientation: if self.flipped { - Color::Black - } else { - Color::White - }, - last_move, - arrows: &arrows, - circles: &circles, - badge: annotations.badge, - interactive: !self.is_finished() - && self.flash.is_none() - && self.save_error.is_none() - && self.next_job.is_none() - && self.view_ply + 1 == self.positions.len(), - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: false, - alert, - }; - if let Some(mv) = view.show(ui, &mut self.board) { - if self.view_ply + 1 == self.positions.len() { - self.play(mv); - if self.flash.is_some() { - if self.flash.as_ref().is_some_and(|f| f.wrong) { - actions.push(TrainingAction::Sound(Sound::Wrong)); - } - } else if self.is_finished() { - actions.push(TrainingAction::Sound(Sound::Success)); - } else { - actions.push(TrainingAction::Sound(Sound::Move)); - } - } else { - self.go_end(); - } - } - }); - } - - fn task_card(&self, ui: &mut Ui) { - let frame = card(ui, self.flash.as_ref().is_some_and(|f| f.wrong)); - frame.show(ui, |ui| { - ui.set_width(ui.available_width()); - let position = self.session.position(); - let heading = if self.is_path_practice() { - tr("Continue the variation").to_owned() - } else { - trf( - "Task {current} of {total}", - &[ - ( - "current", - &(self.completed_targets + 1).min(self.target_limit.max(1)), - ), - ("total", &self.target_limit), - ], - ) - }; - ui.label(RichText::new(heading).strong().size(15.0)); - ui.label( - RichText::new(if position.turn() == Color::White { - tr("♔ White to move") - } else { - tr("♚ Black to move") - }) - .strong(), - ); - ui.label(tr(if self.mode == TrainingMode::Both { - "Play both sides. Any enabled move is accepted." - } else { - "Your turn: play any move from your repertoire. The program will reply." - })); - if self.session.candidates().len() > 1 { - ui.label(tr("Several continuations are available. Choose the variation you want to practise.")); - } - }); - } - - fn user_card(&mut self, ui: &mut Ui) { - let alert = self.flash.as_ref().is_some_and(|f| f.wrong); - card(ui, alert).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label( - RichText::new(trf( - "Mistakes: {n}", - &[("n", &self.session.total_mistakes())], - )) - .size(15.0), - ); - if let Some(message) = &self.message { - ui.label(RichText::new(message).color(if alert { - ui.visuals().error_fg_color - } else { - ui.visuals().text_color() - })); - } - if self.session.hinted() { - ui.label(RichText::new(tr("With hint")).weak()); - } - if self.session.may_hint() - && self.hint.is_none() - && self.flash.is_none() - && ui.link(tr("I don't remember — show a move")).clicked() - && let Some(candidate) = self.session.hint(now()) - { - self.hint = move_squares(&candidate); - self.save(); - } - }); - } - - fn preparing(&self, ui: &mut Ui) { - card(ui, false).show(ui, |ui| { - ui.horizontal(|ui| { - ui.spinner(); - ui.label(tr("Preparing the training session…")); - }); - }); - } - - fn result(&mut self, ui: &mut Ui, actions: &mut Vec) { - card(ui, false).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label( - RichText::new(if self.is_path_practice() { - tr("Branch complete") - } else { - tr("Training complete") - }) - .strong() - .size(17.0), - ); - if let Some(message) = &self.message { - ui.label(message); - } - if self.is_path_practice() { - let played = self - .session - .path() - .iter() - .filter(|mv| !mv.automatic) - .count(); - ui.label(trf( - "Your moves: {n} · mistakes: {m}", - &[("n", &played), ("m", &self.session.total_mistakes())], - )); - ui.label(if self.session.hinted() { - tr("With hint") - } else { - tr("Without hint") - }); - } else { - let correct = self.session.attempts().iter().filter(|a| a.correct).count(); - ui.label(trf( - "Tasks: {n} · correct: {c} · wrong attempts: {w} · with hint: {h}", - &[ - ("n", &self.completed_targets), - ("c", &correct), - ("w", &self.session.total_mistakes()), - ( - "h", - &self.session.attempts().iter().filter(|a| a.hinted).count(), - ), - ], - )); - } - ui.add_space(6.0); - ui.horizontal_wrapped(|ui| { - if self.is_path_practice() { - if crate::widgets::primary(ui, tr("Next variation")) - .on_hover_text("Enter") - .clicked() - { - self.next_path(); - } - if ui.button(tr("Repeat path")).clicked() { - self.restart(); - } - } else if crate::widgets::primary(ui, tr("↻ Again")) - .on_hover_text("Enter") - .clicked() - { - self.restart(); - } - if ui.button(tr("Back to repertoire")).clicked() { - actions.push(TrainingAction::Back); - } - }); - }); - } - - fn save_strip(&mut self, ui: &mut Ui) { - let Some(error) = self.save_error.clone() else { - return; - }; - egui::Frame::new() - .fill(ui.visuals().extreme_bg_color) - .stroke(egui::Stroke::new(1.0, ui.visuals().error_fg_color)) - .inner_margin(egui::Margin::symmetric(8, 6)) - .show(ui, |ui| { - ui.label( - RichText::new(trf("Could not save changes: {error}", &[("error", &error)])) - .color(ui.visuals().error_fg_color), - ); - ui.horizontal_wrapped(|ui| { - if ui.button(tr("Retry")).clicked() { - self.save(); - } - if self.confirm_discard { - if ui.button(tr("Leave without saving")).clicked() { - self.discard_requested = true; - } - } else if ui.button(tr("Back to repertoire")).clicked() { - self.confirm_discard = true; - } - }); - if self.confirm_discard { - ui.label( - RichText::new(tr( - "Only the events that could not be saved will be discarded", - )) - .weak(), - ); - } - }); - } - - pub fn show( - &mut self, - ui: &mut Ui, - settings: &Settings, - name: &str, - mut manager: impl FnMut(&mut Ui), - ) -> Vec { - self.poll_next(); - let mut actions = Vec::new(); - if self.next_job.is_some() { - ui.ctx().request_repaint_after(Duration::from_millis(50)); - } - if let Some(flash) = &self.flash { - let left = flash - .until - .saturating_duration_since(web_time::Instant::now()); - if left.is_zero() { - self.flash = None; - } else { - ui.ctx().request_repaint_after(left); - } - } - self.keyboard(ui, &mut actions); - egui::Panel::top("repertoire_training_header").show(ui, |ui| { - ui.horizontal(|ui| { - if ui - .add_enabled( - self.next_job.is_none(), - egui::Button::new(format!("← {}", tr("Back to repertoire"))), - ) - .clicked() - { - if self.save_error.is_some() { - self.confirm_discard = true; - } else { - actions.push(TrainingAction::Back); - } - } - ui.separator(); - ui.label(mode_label(self.mode)); - ui.add(egui::Label::new(RichText::new(name).heading()).truncate()) - .on_hover_text(name); - }); - }); - let width = ui.available_width(); - let height = ui.available_height(); - let stacked = width < 900.0 && height > width; - if stacked { - let available = ui.available_rect_before_wrap(); - 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(), available.bottom() - panel_height), - ); - let side_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| { - egui::CentralPanel::default().show(ui, |ui| self.board(ui, settings, &mut actions)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(side_rect), |ui| { - ui.set_clip_rect(side_rect); - egui::Frame::side_top_panel(ui.style()) - .show(ui, |ui| self.side(ui, &mut actions, &mut manager)); - }); - } else { - let side = 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.side(ui, &mut actions, &mut manager)); - crate::widgets::check_panel("repertoire_training_side", &side.response); - egui::CentralPanel::default().show(ui, |ui| self.board(ui, settings, &mut actions)); - } - if self.next_job.is_some() { - self.discard_requested = false; - actions.retain(|action| !matches!(action, TrainingAction::Back)); - } - if self.save_error.is_some() && !self.discard_requested { - if actions - .iter() - .any(|action| matches!(action, TrainingAction::Back)) - { - self.confirm_discard = true; - } - actions.retain(|action| !matches!(action, TrainingAction::Back)); - } - if std::mem::take(&mut self.discard_requested) { - actions.push(TrainingAction::Back); - } - actions - } - - fn side( - &mut self, - ui: &mut Ui, - actions: &mut Vec, - manager: &mut impl FnMut(&mut Ui), - ) { - ui.spacing_mut().item_spacing.y = 8.0; - self.save_strip(ui); - if self.next_job.is_some() { - self.preparing(ui); - } else if self.is_finished() { - self.result(ui, actions); - } else { - self.task_card(ui); - self.user_card(ui); - } - if self.next_job.is_none() { - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - if ui - .add_sized([30.0, 26.0], egui::Button::new("🔃")) - .on_hover_text(tr("Flip board (F)")) - .clicked() - { - self.flipped = !self.flipped; - } - if !self.is_finished() && ui.button(tr("↻ Restart")).clicked() { - self.restart(); - } - }); - } - if self.next_job.is_none() - && self.view_ply + 1 < self.positions.len() - && ui - .link(tr("Viewing an earlier position · back to training — End")) - .clicked() - { - self.go_end(); - } - ui.separator(); - manager(ui); - } - - pub fn debug_hint(&mut self) { - if self.next_job.is_some() { - return; - } - if let Some(candidate) = self.session.hint(now()) { - self.hint = move_squares(&candidate); - self.save(); - } - } - - pub fn debug_moves(&mut self, moves: &str) { - for text in moves.split_whitespace() { - match text { - "hint" => self.debug_hint(), - "next" => { - self.next_path(); - #[cfg(test)] - if self.next_job.is_some() { - self.deliver_next(); - } - } - "repeat" => self.restart(), - _ => {} - } - if matches!(text, "hint" | "next" | "repeat") { - continue; - } - self.flash = None; - self.refresh_positions(); - let mv = text - .parse::() - .ok() - .and_then(|uci| uci.to_move(self.session.position()).ok()); - if let Some(mv) = mv { - self.play(mv); - } else { - self.message = Some(tr("Illegal move in the current position").to_owned()); - } - } - self.refresh_positions(); - self.go_end(); - } -} - -#[cfg(test)] -fn initial_policy( - repertoire: &Repertoire, - scope: &TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: &StatsData, -) -> SrsPolicy { - if queue_mode != QueueMode::SpacedRepetition { - return SrsPolicy::Due; - } - let tree = RepertoireTree::new(repertoire); - let due = stats.srs_queue(&tree, &repertoire.id, mode, now(), scope, SrsPolicy::Due); - if due.is_empty() { - SrsPolicy::Introduce - } else { - SrsPolicy::Due - } -} - -fn target_count( - repertoire: &Repertoire, - scope: &TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - policy: SrsPolicy, - stats: &StatsData, -) -> usize { - if mode == TrainingMode::Both || queue_mode == QueueMode::Practice { - return usize::MAX; - } - let tree = RepertoireTree::new(repertoire); - if queue_mode == QueueMode::SpacedRepetition { - stats - .srs_queue(&tree, &repertoire.id, mode, now(), scope, policy) - .len() - } else { - stats - .scoped_queue(&tree, &repertoire.id, mode, queue_mode, now(), scope) - .len() - } -} - -fn card(ui: &Ui, alert: bool) -> egui::Frame { - egui::Frame::new() - .inner_margin(egui::Margin::symmetric(10, 6)) - .corner_radius(4) - .stroke(egui::Stroke::new( - if alert { 1.5 } else { 1.0 }, - if alert { - ui.visuals().error_fg_color - } else { - ui.visuals().widgets.noninteractive.bg_stroke.color - }, - )) -} - -fn move_squares(candidate: &Candidate) -> Option<(Square, Square)> { - Some(( - candidate.mv.from().unwrap_or_else(|| candidate.mv.to()), - crate::board::ui_target(&candidate.mv), - )) -} - -fn pgn_annotations(session: &TrainingSession) -> BoardAnnotations { - pgn_annotations_at(session.game(), session.current_node()) -} - -pub(crate) fn pgn_annotations_at( - game: &chess_core::Game, - at: chess_core::NodeId, -) -> BoardAnnotations { - let mut out = BoardAnnotations::default(); - let Some(node) = game.node(at) else { - return out; - }; - let square = node.game_move().and_then(|game_move| match game_move.kind { - MoveKind::Normal(mv) => Some(crate::board::ui_target(&mv)), - MoveKind::Null => None, - }); - if let Some(square) = square { - out.badge = node - .nags() - .iter() - .copied() - .find(|nag| nag.is_move_assessment()) - .and_then(|nag| { - Some(Badge { - square, - text: nag.symbol()?, - color: crate::notation::assessment_color(nag)?, - }) - }); - } - for comment in node.comments_after() { - for part in parse_comment(comment) { - match part { - CommentPart::Annotation(Annotation::Arrows(list)) => { - out.arrows - .extend(list.into_iter().map(|(color, from, to)| Arrow { - from, - to, - color: crate::game_view::shape_color(color), - weight: 0.9, - })); - } - CommentPart::Annotation(Annotation::Squares(list)) => { - out.circles.extend( - list.into_iter() - .map(|(color, square)| (square, crate::game_view::shape_color(color))), - ); - } - CommentPart::Text(_) | CommentPart::Annotation(_) => {} - } - } - } - out -} - -pub fn mode_label(mode: TrainingMode) -> &'static str { - tr(match mode { - TrainingMode::White => "White", - TrainingMode::Black => "Black", - TrainingMode::Both => "Both", - }) -} - -pub fn now() -> i64 { - chrono::Local::now().timestamp() -} - -#[cfg(test)] -mod tests { - use super::*; - use chess_core::parse_str; - - fn training(pgn: &str, mode: TrainingMode, name: &str) -> TrainingUi { - training_queue( - pgn, - mode, - name, - QueueMode::ReviewInOrder, - TrainingScope::whole(), - ) - } - fn training_queue( - pgn: &str, - mode: TrainingMode, - name: &str, - queue: QueueMode, - scope: TrainingScope, - ) -> TrainingUi { - let game = parse_str(pgn).game; - let mut library = trainer::repertoire::Library::default(); - let id = library.create("Test", &game).unwrap(); - let store = StatsStore::new(std::env::temp_dir().join(format!( - "cp-desktop-training-{}-{name}-{}.json", - std::process::id(), - std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() - ))); - TrainingUi::new( - library.repertoire(&id).unwrap(), - scope, - mode, - queue, - StatsData::default(), - store, - false, - ) - .unwrap() - } - - fn assert_board_matches_session(training: &TrainingUi) { - let shown = training.positions.last().unwrap(); - assert_eq!( - trainer::repertoire::fen4(shown), - training.session.position_key() - ); - assert_eq!(training.view_ply + 1, training.positions.len()); - assert_eq!(shown.fullmoves(), training.session.position().fullmoves()); - assert_eq!(shown.halfmoves(), training.session.position().halfmoves()); - } - - #[test] - fn pgn_node_badges_keep_the_existing_palette_and_special_move_destinations() { - for (nag, symbol) in [ - (1, "!"), - (2, "?"), - (3, "!!"), - (4, "??"), - (5, "!?"), - (6, "?!"), - ] { - let game = chess_core::parse_str(&format!("1. e4 ${nag} *")).game; - let node = game.main_child(chess_core::NodeId::ROOT).unwrap(); - let badge = pgn_annotations_at(&game, node).badge.unwrap(); - assert_eq!(badge.text, symbol); - assert_eq!(badge.square, Square::E4); - assert_eq!( - badge.color, - crate::notation::assessment_color(chess_core::Nag(nag)).unwrap() - ); - } - for (fen, san, expected) in [ - ("4k3/8/8/8/8/8/8/4K2R w K - 0 1", "O-O!!", Square::G1), - ("4k3/P7/8/8/8/8/8/4K3 w - - 0 1", "a8=Q+!", Square::A8), - ] { - let game = - chess_core::parse_str(&format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n1. {san} *")) - .game; - let node = game.main_child(chess_core::NodeId::ROOT).unwrap(); - assert_eq!( - pgn_annotations_at(&game, node).badge.unwrap().square, - expected - ); - } - let game = chess_core::parse_str("1. e4 $14 *").game; - let node = game.main_child(chess_core::NodeId::ROOT).unwrap(); - assert!( - pgn_annotations_at(&game, node).badge.is_none(), - "position assessments are not move badges" - ); - } - - #[test] - fn pgn_badges_and_shapes_are_shown_for_the_current_move() { - use chess_core::{Nag, ShapeColor}; - - let mut training = training( - "1. e4!! {[%cal Re2e4,Ge7e5] [%csl Ye4,Re5]} e5?! {[%cal Bg1f3]} *", - TrainingMode::Both, - "annotations", - ); - training.debug_moves("e2e4"); - let annotations = pgn_annotations(&training.session); - let badge = annotations.badge.unwrap(); - assert_eq!(badge.text, "!!"); - assert_eq!(badge.square, Square::E4); - assert_eq!( - badge.color, - crate::notation::assessment_color(Nag::BRILLIANT_MOVE).unwrap() - ); - assert_eq!(annotations.arrows.len(), 2); - assert!(annotations.arrows.iter().any(|arrow| { - arrow.from == Square::E2 - && arrow.to == Square::E4 - && arrow.color == crate::game_view::shape_color(ShapeColor::Red) - })); - assert!(annotations.arrows.iter().any(|arrow| { - arrow.from == Square::E7 - && arrow.to == Square::E5 - && arrow.color == crate::game_view::shape_color(ShapeColor::Green) - })); - assert_eq!(annotations.circles.len(), 2); - assert!(annotations.circles.iter().any(|(square, color)| { - *square == Square::E4 && *color == crate::game_view::shape_color(ShapeColor::Yellow) - })); - assert!(annotations.circles.iter().any(|(square, color)| { - *square == Square::E5 && *color == crate::game_view::shape_color(ShapeColor::Red) - })); - - training.debug_moves("e7e5"); - let annotations = pgn_annotations(&training.session); - assert_eq!(annotations.badge.unwrap().text, "?!"); - assert!(annotations.arrows.iter().any(|arrow| { - arrow.from == Square::G1 - && arrow.to == Square::F3 - && arrow.color == crate::game_view::shape_color(ShapeColor::Blue) - })); - } - - #[test] - fn practice_accepts_users_branch_and_keeps_board_in_sync_for_both_single_colors() { - let pgn = "1. e4 (1. d4 d5 2. c4) e5 (1... c5 2. Nf3) 2. Bc4 *"; - let mut white = training_queue( - pgn, - TrainingMode::White, - "practice-white", - QueueMode::Practice, - TrainingScope::whole(), - ); - assert!(white.target_available()); - assert!(white.session.may_hint()); - white.debug_moves("d2d4 c2c4"); - assert!(white.is_finished()); - assert_eq!(white.session.total_mistakes(), 0); - assert_board_matches_session(&white); - white.debug_moves("next"); - assert!(!white.is_finished()); - assert_board_matches_session(&white); - - let mut black = training_queue( - pgn, - TrainingMode::Black, - "practice-black", - QueueMode::Practice, - TrainingScope::whole().with_context(false), - ); - assert!(black.target_available()); - black.debug_moves("c7c5"); - assert!(black.is_finished()); - assert_board_matches_session(&black); - black.debug_moves("repeat"); - assert!(!black.is_finished()); - assert_board_matches_session(&black); - } - - #[test] - fn replay_preserves_fen_counters_and_move_numbers() { - let mut training = training( - "[SetUp \"1\"]\n[FEN \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 7 17\"]\n\n17. Nf3 Nf6 18. Nc3 Nc6 *", - TrainingMode::Both, - "fen-counters", - ); - training.debug_moves("g1f3 g8f6 b1c3 b8c6"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - assert_eq!( - training - .positions - .iter() - .map(|p| p.fullmoves().get()) - .collect::>(), - vec![17, 17, 18, 18, 19] - ); - assert_eq!(training.positions[0].halfmoves(), 7); - assert_eq!(training.positions.last().unwrap().halfmoves(), 11); - } - - #[test] - fn explicit_due_does_not_silently_introduce_new_targets() { - let mut training = training("1. e4 e5 *", TrainingMode::White, "explicit-due"); - let due = TrainingUi::new_with_policy( - &training.repertoire, - TrainingScope::whole(), - TrainingMode::White, - QueueMode::SpacedRepetition, - StatsData::default(), - training.store.clone(), - false, - SrsPolicy::Due, - ) - .unwrap(); - assert!(!due.target_available()); - training.debug_moves("e2e4"); - assert!(training.is_finished()); - } - - #[test] - fn context_hidden_sections_replay_from_their_actual_start() { - let seed = training( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - TrainingMode::White, - "hidden-context", - ); - let mut training = TrainingUi::new( - &seed.repertoire, - TrainingScope::from_prefix(vec!["e2e4".into(), "e7e5".into(), "g1f3".into()]) - .with_context(false), - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - seed.store.clone(), - false, - ) - .unwrap(); - training.debug_moves("g1f3"); - assert_board_matches_session(&training); - assert_eq!(training.positions[0].fullmoves().get(), 3); - training.debug_moves("f1b5"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - assert_eq!(training.positions.last().unwrap().fullmoves().get(), 4); - } - - #[test] - fn one_side_targets_have_independent_paths_and_current_boards() { - let mut training = training( - "1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 *", - TrainingMode::White, - "sections", - ); - training.debug_moves("e2e4"); - assert_eq!(training.session.target().unwrap().expected_uci, "g1f3"); - assert_eq!(training.task_start, 2); - assert_board_matches_session(&training); - - training.debug_moves("g1f3"); - assert_eq!(training.session.target().unwrap().expected_uci, "d2d4"); - assert_eq!(training.task_start, 6); - assert_board_matches_session(&training); - - training.debug_moves("d2d4"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - let section = &training.session.path()[training.task_start..]; - assert_eq!(section.last().unwrap().uci, "c5d4"); - } - - #[test] - fn pgn_answers_one_side_but_both_has_no_automatic_moves() { - let pgn = "1. e4 e5 2. Nf3 Nc6 *"; - let mut black = training(pgn, TrainingMode::Black, "pgn-black"); - assert_eq!(black.session.path().len(), 1); - assert_eq!(black.session.path()[0].uci, "e2e4"); - assert!(black.session.path()[0].automatic); - black.debug_moves("e7e5"); - assert!( - black - .session - .path() - .iter() - .any(|played| { played.uci == "g1f3" && played.automatic }) - ); - assert!( - black - .session - .path() - .iter() - .filter(|played| !played.automatic) - .all(|played| played.uci == "e7e5") - ); - - let mut both = training(pgn, TrainingMode::Both, "pgn-both"); - assert!(both.session.path().is_empty()); - both.debug_moves("e2e4 e7e5 g1f3 b8c6"); - assert!(both.is_finished()); - assert!(both.session.path().iter().all(|played| !played.automatic)); - } - - #[test] - fn both_next_path_and_result_finish_on_the_actual_last_move() { - let mut training = training( - "1. e4 e5 (1... c5) 2. Nf3 (2. c4) *", - TrainingMode::Both, - "next-path", - ); - training.debug_moves("e2e4 c7c5"); - assert!(training.is_finished()); - assert_board_matches_session(&training); - - training.debug_moves("next e2e4 e7e5 c2c4"); - assert!(training.is_finished()); - assert_eq!(training.session.path().last().unwrap().uci, "c2c4"); - assert_board_matches_session(&training); - } - - #[test] - fn random_next_saves_its_cursor_without_a_move_and_repeat_does_not_advance_it() { - let fixture = training( - "1. e4 e5 (1... c5) 2. Nf3 (2. c4) *", - TrainingMode::Both, - "random-cursor-save", - ); - let mut random = TrainingUi::new_random( - &fixture.repertoire, - TrainingMode::Both, - StatsData::default(), - fixture.store.clone(), - false, - ) - .unwrap(); - assert!(random.save_error.is_none()); - assert_eq!(random.session.queue_mode(), QueueMode::Practice); - let initial = serde_json::to_value(random.session.stats()).unwrap(); - assert_eq!(initial["random_practice_cursors"][0]["position"], 1); - assert_eq!( - serde_json::to_value(random.store.load().unwrap()).unwrap(), - initial - ); - - random.debug_moves("next"); - assert!(random.save_error.is_none()); - assert!(random.session.attempts().is_empty()); - assert_board_matches_session(&random); - let next = serde_json::to_value(random.session.stats()).unwrap(); - assert_eq!(next["random_practice_cursors"][0]["position"], 2); - assert_eq!( - serde_json::to_value(random.store.load().unwrap()).unwrap(), - next - ); - - random.debug_moves("repeat"); - assert_eq!(serde_json::to_value(random.session.stats()).unwrap(), next); - assert_board_matches_session(&random); - } - - #[test] - fn async_next_blocks_duplicate_work_and_applies_delivery_exactly_once() { - let fixture = training( - "1. e4 e5 (1... c5) 2. Nf3 (2. c4) *", - TrainingMode::Both, - "async-next-delivery", - ); - let mut random = TrainingUi::new_random( - &fixture.repertoire, - TrainingMode::Both, - StatsData::default(), - fixture.store.clone(), - false, - ) - .unwrap(); - random.debug_moves(""); - let old_path = random.session.path().to_vec(); - let old_scope = random.session.scope().clone(); - let old_positions = random.positions.clone(); - let old_stats = serde_json::to_vec(random.session.stats()).unwrap(); - let generation = random.next_generation; - - random.next_path(); - assert!(random.next_job.is_some()); - assert_eq!(random.next_generation, generation.wrapping_add(1)); - assert_eq!(random.session.path(), old_path); - assert_eq!(random.positions, old_positions); - assert_eq!( - serde_json::to_vec(random.session.stats()).unwrap(), - old_stats - ); - random.next_path(); - assert_eq!(random.next_generation, generation.wrapping_add(1)); - random.restart(); - assert_eq!(random.session.scope(), &old_scope); - assert_eq!(random.session.path(), old_path); - - random.deliver_next(); - assert!(random.next_job.is_none()); - assert!(random.session.attempts().is_empty()); - assert_board_matches_session(&random); - let delivered_stats = serde_json::to_value(random.session.stats()).unwrap(); - assert_eq!(delivered_stats["random_practice_cursors"][0]["position"], 2); - assert_eq!( - serde_json::to_value(random.store.load().unwrap()).unwrap(), - delivered_stats - ); - let delivered_path = random.session.path().to_vec(); - random.poll_next(); - assert_eq!(random.session.path(), delivered_path); - assert_eq!( - serde_json::to_value(random.session.stats()).unwrap(), - delivered_stats - ); - } - - #[test] - fn async_next_computation_error_preserves_the_current_session() { - let mut training = training_queue( - "1. e4 e5 *", - TrainingMode::Both, - "async-next-error", - QueueMode::Practice, - TrainingScope::from_prefix(vec!["e2e4".into()]), - ); - training.debug_moves(""); - let old_path = training.session.path().to_vec(); - let old_scope = training.session.scope().clone(); - let old_positions = training.positions.clone(); - let old_stats = serde_json::to_vec(training.session.stats()).unwrap(); - training.repertoire.pgn = parse_str("1. d4 d5 *").game.to_pgn(); - - training.next_path(); - training.deliver_next(); - assert!(training.next_job.is_none()); - assert!( - training - .message - .as_ref() - .is_some_and(|message| message.contains("invalid training scope")) - ); - assert_eq!(training.session.path(), old_path); - assert_eq!(training.session.scope(), &old_scope); - assert_eq!(training.positions, old_positions); - assert_eq!( - serde_json::to_vec(training.session.stats()).unwrap(), - old_stats - ); - assert_board_matches_session(&training); - } - - #[test] - fn async_next_save_error_remains_visible_after_successful_computation() { - let fixture = training( - "1. e4 e5 (1... c5) 2. Nf3 *", - TrainingMode::Both, - "async-next-save-error", - ); - let mut random = TrainingUi::new_random( - &fixture.repertoire, - TrainingMode::Both, - StatsData::default(), - fixture.store.clone(), - false, - ) - .unwrap(); - let mut external = random.store.load().unwrap(); - random.store.save(&mut external).unwrap(); - - random.next_path(); - random.deliver_next(); - assert!(random.next_job.is_none()); - assert!(random.save_error.is_some()); - assert!(random.has_unsaved()); - assert_eq!(random.session.stats().revision, 1); - assert_board_matches_session(&random); - } - - #[test] - fn late_mainline_scope_end_is_accepted() { - let game = - parse_str("1. e4 e5 (1... c5) 2. Nf3 (2. c4) Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *").game; - let mut library = trainer::repertoire::Library::default(); - let id = library.create("Scoped", &game).unwrap(); - let repertoire = library.repertoire(&id).unwrap(); - let end = [ - "e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4", "g8f6", - ] - .map(str::to_owned) - .to_vec(); - let tree = RepertoireTree::new(repertoire); - let actual = tree - .game() - .mainline() - .into_iter() - .filter_map(|node| tree.game().game_move(node).and_then(|mv| mv.uci())) - .take(end.len()) - .collect::>(); - assert_eq!(actual, end); - assert!(tree.node_at_path(&end).is_some()); - let scope = - TrainingScope::between(["e2e4", "e7e5", "g1f3"].map(str::to_owned).to_vec(), end); - TrainingSession::scoped( - repertoire, - scope, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - } -} diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 6cb4ba5..623b470 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -1,33 +1,39 @@ +//! Opening training (docs/design/opening-trainer-v2-spec.md): the «Repertoires» screen +//! with its card and dialogs, and the way to the «Session» and «Lines» screens. + use std::collections::{BTreeSet, HashMap}; use std::path::{Path, PathBuf}; use std::sync::{ Arc, - atomic::{AtomicBool, Ordering}, + atomic::{AtomicBool, AtomicU64, Ordering}, mpsc::{self, Receiver, Sender}, }; +use std::time::Duration; -use chess_core::shakmaty::{Position, uci::UciMove}; +use chess_core::shakmaty::{Chess, Color, Position, Square}; use chess_core::{Game, NodeId, PgnDatabase, Severity}; -use egui::{Key, Modifiers, RichText, Ui}; +use egui::{Key, Modifiers, RichText, Ui, vec2}; use trainer::repertoire::{ - LearningAggregate, LearningItemKey, LearningPriority, LearningSessionPhase, - LearningSessionSnapshot, LearningSide, LearningStore, LearningStoreData, Library, LibraryStore, - MergeReport, QueueMode, RepertoireId, RepertoireTree, ResetImpactProjection, - ScopedLearningAggregate, SrsSettings, StatsScope, TrainingMode, TrainingScope, + LearningData, LearningItemKey, LearningSide, LearningStore, LearningStoreData, Library, + LibraryStore, MergeReport, RepertoireId, ResetImpactProjection, SrsSettings, StatsScope, active_learning_keys, aggregate_scope, fen4, reset_impact, }; +use web_time::Instant; -use crate::board::{BoardState, BoardView}; +use crate::board::BoardState; 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}; +use crate::opening_layout::{self as layout, BoardAnnotations, GAP, NEW_PER_SESSION}; +use crate::opening_lines::{LinesAction, OpeningLinesUi}; +use crate::opening_session::{ + OpeningSessionUi, PreparingView, SessionAction, SessionKind, show_preparing, +}; use crate::settings::Settings; pub enum RepertoireAction { Close, OpenSettings, Sound(crate::assets::Sound), + #[allow(dead_code)] Toast(String), SettingsChanged, Added { @@ -37,94 +43,211 @@ pub enum RepertoireAction { }, } -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -struct OpeningLabel { - eco: String, - name: String, +const CARD_H: f32 = 166.0; +const ROW_H: f32 = 24.0; +const HEADER_H: f32 = 26.0; +const MESSAGE_H: f32 = 20.0; +const BOTTOM_H: f32 = 30.0; +const BOTTOM_W: f32 = 150.0; +const MAIN_W: f32 = 170.0; +const LINES_W: f32 = 110.0; +const THIRD_W: f32 = 150.0; +const DIALOG_W: f32 = 460.0; +/// A session appears at once when it is ready this fast; otherwise «Preparing…». +const PREPARING_SHOWN_AFTER: Duration = Duration::from_millis(300); +const MESSAGE_SHOWN: Duration = Duration::from_secs(6); +/// Seconds per question in «About {t} min». +const SECONDS_PER_MOVE: usize = 20; +const WARNING_ROWS: usize = 3; +static NEXT_JOB: AtomicU64 = AtomicU64::new(1); + +/// What the table and the board need of a repertoire, from its PGN (indexed off the +/// frame). +#[derive(Clone)] +struct RowIndex { + start: Chess, + last_move: Option<(Square, Square)>, + has_moves: bool, } -struct LibraryRow { - id: RepertoireId, - name: String, - openings: Vec, +/// The counts of a repertoire for its colour, "today" meaning until the end of the day. +#[derive(Clone, Debug, Default, PartialEq)] +struct RowStats { + total: usize, + due: usize, + unseen: usize, + learning: usize, + learnt: usize, + /// The next review after today and how many moves are due that day. + next: Option<(i64, usize)>, } -const OPENING_LINES: usize = 5; -const ROW_VERTICAL_PADDING: f32 = 8.0; -const ROW_BOTTOM_PADDING: f32 = 4.0; -const TITLE_HEIGHT: f32 = 24.0; -const TITLE_GAP: f32 = 12.0; -const OPENING_HEIGHT: f32 = 20.0; -const OPENING_GAP: f32 = 2.0; - -impl LibraryRow { - fn height() -> f32 { - ROW_VERTICAL_PADDING - + ROW_BOTTOM_PADDING - + TITLE_HEIGHT - + TITLE_GAP - + OPENING_HEIGHT * OPENING_LINES as f32 - + OPENING_GAP * (OPENING_LINES - 1) as f32 +impl RowStats { + fn new_today(&self) -> usize { + self.unseen.min(NEW_PER_SESSION) } - fn visible_openings(&self) -> &[OpeningLabel] { - &self.openings[..self.openings.len().min(OPENING_LINES)] + fn today(&self) -> usize { + self.due + self.new_today() } } +#[derive(Clone, Debug, PartialEq, Eq)] +struct StatsKey { + library_revision: u64, + learning_revision: u64, + sides: Vec<(RepertoireId, LearningSide)>, + day: i64, +} + +/// The card's states (spec §3). +#[derive(Clone, Debug, PartialEq)] +enum CardState { + Review { due: usize, new: usize }, + OnlyNew { new: usize }, + Done { next: Option<(i64, usize)> }, + Empty, + OtherColor, + Counting, + Failed(String), +} + +fn card_state(has_moves: Option, stats: Option<&Result>) -> CardState { + match stats { + None => CardState::Counting, + Some(Err(error)) => CardState::Failed(error.clone()), + Some(Ok(stats)) if stats.total == 0 => { + if has_moves == Some(true) { + CardState::OtherColor + } else { + CardState::Empty + } + } + Some(Ok(stats)) if stats.due > 0 => CardState::Review { + due: stats.due, + new: stats.new_today(), + }, + Some(Ok(stats)) if stats.unseen > 0 => CardState::OnlyNew { + new: stats.new_today(), + }, + Some(Ok(stats)) => CardState::Done { next: stats.next }, + } +} + +/// A PGN read for «Import PGN» or «Add PGN to this repertoire». struct ImportPreview { library: Library, id: RepertoireId, - records: usize, + base_revision: u64, + games: usize, + /// Lines of the result, and before the merge (an added file). + lines: usize, + lines_before: usize, + /// Own moves for White and for Black. + own: [usize; 2], + suggested: LearningSide, + default_name: String, + warnings: Vec, report: MergeReport, - name: String, +} + +impl ImportPreview { + fn own(&self, side: LearningSide) -> usize { + match side { + LearningSide::White => self.own[0], + LearningSide::Black => self.own[1], + } + } +} + +struct ImportDialog { + job: u64, + /// `None`: a new repertoire. target: Option, -} - -struct LibraryLoadError { - message: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -struct AggregateKey { - id: RepertoireId, + preview: Option, + name: String, side: LearningSide, - library_revision: u64, - learning_revision: u64, - minute: i64, + error: Option, + cancel: Arc, +} + +enum Dialog { + Import(ImportDialog), + New { + name: String, + side: LearningSide, + error: Option, + }, + Rename { + id: RepertoireId, + name: String, + error: Option, + select_all: bool, + }, + Color { + id: RepertoireId, + to: LearningSide, + job: u64, + count: Option, + }, + Reset { + id: RepertoireId, + job: u64, + impact: Option<(ResetImpactProjection, BTreeSet)>, + busy: bool, + }, + Delete { + id: RepertoireId, + }, +} + +enum Screen { + Repertoires, + Session(Box), + Lines(Box), +} + +struct Preparing { + job: u64, + since: Instant, + id: RepertoireId, + name: String, + kind: SessionKind, +} + +struct Message { + text: String, + error: bool, + until: Option, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum StartKind { - Review, - IntroduceNew, - Unavailable, -} - -struct SharedReset { - impact: Option, - keys: BTreeSet, - confirmed: bool, - busy: bool, +enum MenuItem { + Train, + ReviewAll, + Lines, + Rename, + SwitchColor, + AddPgn, + Export, + Reset, + Delete, } enum Event { - Aggregated(AggregateKey, Box>), + Indexed(u64, HashMap), + Stats(StatsKey, HashMap>), + Imported(u64, Result), + Exported(Result, String>), + SessionReady(u64, Result, String>), + LinesReady(u64, Option>), + LearningLoaded(Result), + OtherSide(u64, Result), ResetImpact( u64, - Box), String>>, + Result<(ResetImpactProjection, BTreeSet), String>, ), - LearningReset(u64, Box>), - ReviewReset(u64, Box>), - Indexed( - u64, - HashMap>, - HashMap>, - HashMap, - ), - TrainingReady(u64, Result, String>), - Imported(Result), - Exported(Result<(), String>), + ResetDone(u64, Result), } struct AddFromGame { @@ -132,19 +255,7 @@ struct AddFromGame { at: NodeId, selected: Option, name: String, -} - -#[cfg(test)] -#[derive(Clone, Copy, Debug, Default)] -struct TestLayout { - status: Option, - message: Option, - retry: Option, - cancel: Option, - table: Option, - reset_review: Option, - editor: Option, - action_buttons: [Option; 3], + side: LearningSide, } pub struct RepertoireUi { @@ -154,46 +265,31 @@ pub struct RepertoireUi { learning: LearningStoreData, library_error: Option, learning_error: Option, - error: Option, selected: Option, - initial_selection_pending: bool, - parameters_open: bool, + index: HashMap, + index_job: u64, + stats: HashMap>, + stats_key: Option, + screen: Screen, + /// The «Lines» screen a branch session was started from. + lines_return: Option>, + preparing: Option, + lines_job: Option, + /// The answers are being read again after a session. + learning_loading: bool, + dialog: Option, + message: Option, + search: String, scroll_to_selected: bool, - tree: Option>, - trees: HashMap>, - openings: HashMap>, - variant_counts: HashMap, - aggregates: HashMap>>, - index_generation: u64, - indexing: bool, - preparing: bool, - training_generation: u64, - board: BoardState, - side: LearningSide, - queue: QueueMode, - priority: LearningPriority, - shared_reset: Option, - reset_generation: u64, - review_reset_pending: bool, - training: Option, - training_visible: bool, - training_name: String, - editor: Option, - editor_id: Option, - dashboard: Option, return_to_game: Option, add: Option, - edit_name: Option<(Option, String)>, - delete: Option, - search: String, - import: Option, - cancel: Option>, + board: BoardState, tx: Sender, rx: Receiver, + initial_selection_pending: bool, debug_start: Option, debug_pending_moves: Option, - #[cfg(test)] - debug_layout: TestLayout, + debug_menu: bool, } impl RepertoireUi { @@ -201,16 +297,16 @@ impl RepertoireUi { let (library_store, learning_store) = stores(); Self::with_stores(library_store, learning_store) } + fn with_stores(library_store: LibraryStore, learning_store: LearningStore) -> Self { let (library, library_error) = match load_library(&library_store) { Ok(data) => (data, None), - Err(e) => (Library::default(), Some(e.message)), + Err(error) => (Library::default(), Some(error)), }; let (learning, learning_error) = match learning_store.load() { Ok(data) => (data, None), - Err(e) => (LearningStoreData::default(), Some(e.to_string())), + Err(error) => (LearningStoreData::default(), Some(error.to_string())), }; - let selected = library.repertoires.first().map(|r| r.id.clone()); let (tx, rx) = mpsc::channel(); let mut this = Self { library_store, @@ -219,140 +315,57 @@ impl RepertoireUi { learning, library_error, learning_error, - error: None, - selected, - initial_selection_pending: true, - parameters_open: false, + selected: None, + index: HashMap::new(), + index_job: 0, + stats: HashMap::new(), + stats_key: None, + screen: Screen::Repertoires, + lines_return: None, + preparing: None, + lines_job: None, + learning_loading: false, + dialog: None, + message: None, + search: String::new(), scroll_to_selected: true, - tree: None, - trees: HashMap::new(), - openings: HashMap::new(), - variant_counts: HashMap::new(), - aggregates: HashMap::new(), - index_generation: 0, - indexing: false, - preparing: false, - training_generation: 0, - board: BoardState::default(), - side: LearningSide::White, - queue: QueueMode::SpacedRepetition, - priority: LearningPriority::default(), - shared_reset: None, - reset_generation: 0, - review_reset_pending: false, - training: None, - training_visible: false, - training_name: String::new(), - editor: None, - editor_id: None, - dashboard: None, return_to_game: None, add: None, - edit_name: None, - delete: None, - search: String::new(), - import: None, - cancel: None, + board: BoardState::default(), tx, rx, + initial_selection_pending: true, debug_start: None, debug_pending_moves: None, - #[cfg(test)] - debug_layout: TestLayout::default(), + debug_menu: false, }; - this.rebuild_tree(); + this.selected = this.sorted_ids().first().cloned(); + this.reindex(); this } pub fn has_unsaved(&self) -> bool { - self.training - .as_ref() - .is_some_and(LearningTrainingUi::has_unsaved) - || self - .editor - .as_ref() - .is_some_and(RepertoireEditorUi::has_unsaved) - } - pub fn resolve_unsaved(&mut self) { - if self - .training - .as_ref() - .is_some_and(LearningTrainingUi::has_unsaved) - { - self.training_visible = true; + match &self.screen { + Screen::Session(session) => session.has_unsaved(), + Screen::Repertoires | Screen::Lines(_) => false, } } - fn open_dashboard(&mut self) { - if self.has_unsaved() || self.training_visible || self.preparing || self.editor.is_some() { - return; - } - self.dashboard = Some(match self.selected.clone() { - Some(id) if self.library.repertoire(&id).is_some() => { - LearningDashboardUi::new_for_repertoire( - self.library.clone(), - self.learning_store.clone(), - id, - self.side, - ) - } - _ => LearningDashboardUi::new(self.library.clone(), self.learning_store.clone()), - }); - } - fn open_editor(&mut self) { - if self.has_unsaved() || self.training_visible || self.preparing || self.editor.is_some() { - return; - } - let Some(id) = self.selected.clone() else { - return; - }; - match RepertoireEditorUi::new(&self.library, id.clone()) { - Ok(mut editor) => { - editor.set_learning(&self.learning.learning); - self.editor = Some(editor); - self.editor_id = Some(id); - self.error = None; - } - Err(error) => self.error = Some(error.to_string()), - } - } - fn close_editor(&mut self) { - self.editor = None; - self.editor_id = None; - } - fn handle_editor_action(&mut self, action: RepertoireEditorAction) -> Option { - match action { - RepertoireEditorAction::OpenSettings => return Some(RepertoireAction::OpenSettings), - RepertoireEditorAction::Close | RepertoireEditorAction::Cancel => self.close_editor(), - RepertoireEditorAction::Applied { - repertoire_id, - library, - } => { - let current = self.editor_id.as_ref() == Some(&repertoire_id) - && self.selected.as_ref() == Some(&repertoire_id) - && self.library.revision.saturating_add(1) == library.revision; - if current { - self.library = library; - self.error = None; - self.rebuild_tree(); - } - self.close_editor(); - } - RepertoireEditorAction::Error(error) => self.error = Some(error), - } - None - } + + /// The window is being closed with an answer not saved: show the session. + pub fn resolve_unsaved(&mut self) {} + pub fn open_library(&mut self) { - self.preparing = false; self.scroll_to_selected = true; - if self.training.is_some() { - self.reload_learning(); + if !matches!(self.screen, Screen::Session(_)) { + self.screen = Screen::Repertoires; } - self.training_visible = false; } - pub fn open_from_toast(&mut self, id: RepertoireId, title: String, settings: &Settings) { + + pub fn open_from_toast(&mut self, id: RepertoireId, title: String, _settings: &Settings) { self.return_to_game = Some(title); - self.select(id, settings); + self.select(id); } + pub fn open_add_from_game(&mut self, source: Game, at: NodeId, title: String) { self.return_to_game = Some(title); let start = fen4(source.start().position()); @@ -360,265 +373,161 @@ impl RepertoireUi { .library .repertoires .iter() - .find(|r| { - self.trees - .get(&r.id) - .is_some_and(|tree| fen4(tree.game().start().position()) == start) - }) + .find(|r| fen4(r.game().start().position()) == start) .map(|r| r.id.clone()); + // The colour of the move chosen in the game. + let side = match source.position_before(at).map(|p| p.turn()) { + Some(Color::Black) => LearningSide::Black, + _ => LearningSide::White, + }; self.add = Some(AddFromGame { source, at, selected, name: String::new(), + side, }); } - fn select(&mut self, id: RepertoireId, settings: &Settings) { + + fn sorted_ids(&self) -> Vec { + let mut rows: Vec<_> = self + .library + .repertoires + .iter() + .map(|r| (r.name.to_lowercase(), r.id.clone())) + .collect(); + rows.sort(); + rows.into_iter().map(|(_, id)| id).collect() + } + + fn select(&mut self, id: RepertoireId) { self.initial_selection_pending = false; - if self - .editor - .as_ref() - .is_some_and(RepertoireEditorUi::has_unsaved) - { - return; + if self.library.repertoire(&id).is_some() { + self.selected = Some(id); + self.scroll_to_selected = true; } - self.close_editor(); - self.preparing = false; - self.training_visible = false; - self.training = None; - self.scroll_to_selected = true; - self.selected = Some(id.clone()); - let (side, queue) = settings - .repertoire_modes - .get(id.as_str()) - .map(|(mode, queue)| { - let side = match mode { - TrainingMode::Black => LearningSide::Black, - TrainingMode::White | TrainingMode::Both => LearningSide::White, - }; - (side, *queue) - }) - .unwrap_or((LearningSide::White, QueueMode::SpacedRepetition)); - self.side = side; - self.queue = match queue { - QueueMode::ReviewInOrder | QueueMode::LeastRecent => queue, - QueueMode::Practice | QueueMode::SpacedRepetition => QueueMode::SpacedRepetition, - }; - self.priority = settings - .repertoire_priorities - .get(id.as_str()) - .copied() - .unwrap_or_default(); - self.invalidate_reset_jobs(); - self.update_selected_tree(); } - fn update_selected_tree(&mut self) { - self.tree = self - .selected + + fn selected_name(&self) -> String { + self.selected .as_ref() - .and_then(|id| self.trees.get(id)) - .cloned(); + .and_then(|id| self.library.repertoire(id)) + .map(|r| r.name.clone()) + .unwrap_or_default() } - fn rebuild_tree(&mut self) { - self.invalidate_reset_jobs(); - self.aggregates.clear(); - self.variant_counts.clear(); - self.index_generation += 1; - self.indexing = true; - self.preparing = false; - self.trees.clear(); - self.openings.clear(); - self.update_selected_tree(); - let generation = self.index_generation; + + fn show_message(&mut self, text: impl Into, error: bool) { + self.message = Some(Message { + text: text.into(), + error, + until: (!error).then(|| Instant::now() + MESSAGE_SHOWN), + }); + } + + fn reindex(&mut self) { + self.index_job = next_job(); + let job = self.index_job; let repertoires = self.library.repertoires.clone(); let tx = self.tx.clone(); if let Err(error) = crate::platform::spawn("repertoire-index", move || { - let mut trees = HashMap::new(); - let mut openings = HashMap::new(); - let mut variant_counts = HashMap::new(); - for r in repertoires { - let tree = Arc::new(RepertoireTree::from_game(r.game(), u32::MAX, Vec::new())); - openings.insert(r.id.clone(), opening_labels(&tree)); - variant_counts.insert(r.id.clone(), pgn_route_count(&tree)); - trees.insert(r.id.clone(), tree); - } - let _ = tx.send(Event::Indexed(generation, trees, openings, variant_counts)); + let index = repertoires + .into_iter() + .map(|r| { + let game = r.game(); + let start = layout::common_start(&game); + ( + r.id.clone(), + RowIndex { + start: layout::position_of(&game, start), + last_move: layout::last_move(&game, start), + has_moves: !game.children(NodeId::ROOT).is_empty(), + }, + ) + }) + .collect(); + let _ = tx.send(Event::Indexed(job, index)); }) { - self.indexing = false; - self.error = Some(error.to_string()); + self.show_message(error.to_string(), true); } } + + fn sides(&self, settings: &Settings) -> Vec<(RepertoireId, LearningSide)> { + self.sorted_ids() + .into_iter() + .map(|id| { + let side = layout::side_of(settings, &id); + (id, side) + }) + .collect() + } + + /// Recount in the background when the library, the answers, a colour or the day + /// changed; the previous numbers stay meanwhile. + fn request_stats(&mut self, settings: &Settings) { + if self.library_error.is_some() || self.learning_error.is_some() { + return; + } + let today = layout::end_of_today(); + let key = StatsKey { + library_revision: self.library.revision, + learning_revision: self.learning.revision, + sides: self.sides(settings), + day: today, + }; + if self.stats_key.as_ref() == Some(&key) { + return; + } + self.stats_key = Some(key.clone()); + let library = self.library.clone(); + let learning = self.learning.learning.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-stats", move || { + let stats = key + .sides + .iter() + .map(|(id, side)| (id.clone(), row_stats(&library, &learning, id, *side, today))) + .collect(); + let _ = tx.send(Event::Stats(key, stats)); + }) { + self.show_message(error.to_string(), true); + } + } + + fn reload_learning(&mut self) { + self.learning_loading = true; + let store = self.learning_store.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-learning-load", move || { + let _ = tx.send(Event::LearningLoaded( + store.load().map_err(|error| error.to_string()), + )); + }) { + self.learning_loading = false; + self.show_message(error.to_string(), true); + } + } + + /// Writes the library; on success it is the one shown. fn persist(&mut self, mut library: Library) -> bool { - if self.library_error.is_some() - || self - .editor - .as_ref() - .is_some_and(RepertoireEditorUi::has_unsaved) - { + if self.library_error.is_some() { return false; } match self.library_store.save(&mut library) { Ok(()) => { self.library = library; - self.error = None; - self.close_editor(); - self.trees.clear(); - self.rebuild_tree(); + self.reindex(); true } - Err(e) => { - self.error = Some(e.to_string()); + Err(error) => { + self.show_message( + trf("Could not save: {e}", &[("e", &error.to_string())]), + true, + ); false } } } - fn reload_learning(&mut self) { - match self.learning_store.load() { - Ok(data) => { - self.learning = data; - self.learning_error = None; - if let Some(editor) = &mut self.editor { - editor.set_learning(&self.learning.learning); - } - } - Err(error) => self.learning_error = Some(error.to_string()), - } - } - fn invalidate_reset_jobs(&mut self) { - self.reset_generation = self.reset_generation.wrapping_add(1); - self.shared_reset = None; - self.review_reset_pending = false; - } - fn begin_shared_reset(&mut self, scope: StatsScope) { - if self.has_unsaved() || self.preparing { - return; - } - self.invalidate_reset_jobs(); - let generation = self.reset_generation; - self.shared_reset = Some(SharedReset { - impact: None, - keys: BTreeSet::new(), - confirmed: false, - busy: false, - }); - let library = self.library.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("repertoire-reset-impact", move || { - let result = reset_impact(&library, &scope) - .map_err(|error| error.to_string()) - .and_then(|impact| { - active_learning_keys(&library, &scope) - .map(|keys| (impact, keys)) - .map_err(|error| error.to_string()) - }); - let _ = tx.send(Event::ResetImpact(generation, Box::new(result))); - }) { - self.shared_reset = None; - self.error = Some(error.to_string()); - } - } - fn cancel_shared_reset(&mut self) { - self.reset_generation = self.reset_generation.wrapping_add(1); - self.shared_reset = None; - } - fn confirm_shared_reset(&mut self) { - if self.has_unsaved() || self.preparing { - return; - } - let Some(state) = &mut self.shared_reset else { - return; - }; - if !state.confirmed || state.busy || state.impact.is_none() || state.keys.is_empty() { - return; - } - state.busy = true; - let generation = self.reset_generation; - let keys = state.keys.clone(); - let store = self.learning_store.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("repertoire-shared-reset", move || { - let result = store - .reset_learning(keys) - .map_err(|error| error.to_string()) - .and_then(|_| store.load().map_err(|error| error.to_string())); - let _ = tx.send(Event::LearningReset(generation, Box::new(result))); - }) { - if let Some(state) = &mut self.shared_reset { - state.busy = false; - } - self.error = Some(error.to_string()); - } - } - fn matches_review_snapshot(&self, snapshot: &LearningSessionSnapshot) -> bool { - self.selected.as_ref().is_some_and(|id| { - snapshot.session.mode == self.queue - && snapshot.stats_scope.repertoire_ids.len() == 1 - && snapshot.stats_scope.repertoire_ids.contains(id) - && snapshot.stats_scope.side == self.side - && snapshot.stats_scope.max_depth - == self - .library - .repertoire(id) - .map(|repertoire| repertoire.max_plies) - && snapshot.stats_scope.only_active - && snapshot.stats_scope.branch_root.is_none() - && snapshot.stats_scope.learning_priority == self.priority - }) - } - fn has_review_snapshot(&self) -> bool { - self.learning - .session_snapshots - .iter() - .any(|snapshot| self.matches_review_snapshot(snapshot)) - } - fn has_unfinished_review_snapshot(&self) -> bool { - self.learning.session_snapshots.iter().any(|snapshot| { - snapshot.phase != LearningSessionPhase::Finished - && self.matches_review_snapshot(snapshot) - }) - } - fn selected_start_kind(&self, summary: &LearningAggregate) -> StartKind { - if self.queue == QueueMode::SpacedRepetition && self.has_unfinished_review_snapshot() { - StartKind::Review - } else { - mode_start_kind(self.queue, summary) - } - } - fn review_snapshot(&self) -> Option { - self.learning - .session_snapshots - .iter() - .filter(|snapshot| self.matches_review_snapshot(snapshot)) - .max_by_key(|snapshot| snapshot.revision) - .cloned() - } - fn reset_review_cursor(&mut self) { - if self.queue == QueueMode::SpacedRepetition - || self.has_unsaved() - || self.preparing - || self.review_reset_pending - { - return; - } - let Some(mut snapshot) = self.review_snapshot() else { - return; - }; - self.invalidate_reset_jobs(); - let generation = self.reset_generation; - self.review_reset_pending = true; - let store = self.learning_store.clone(); - let tx = self.tx.clone(); - if let Err(error) = crate::platform::spawn("repertoire-review-reset", move || { - let result = store - .reset_review_order(&mut snapshot) - .map_err(|error| error.to_string()) - .and_then(|_| store.load().map_err(|error| error.to_string())); - let _ = tx.send(Event::ReviewReset(generation, Box::new(result))); - }) { - self.review_reset_pending = false; - self.error = Some(error.to_string()); - } - } + fn checked_name(&self, name: &str, excluding: Option<&RepertoireId>) -> Result { let name = name.split_whitespace().collect::>().join(" "); if name.is_empty() { @@ -640,162 +549,203 @@ impl RepertoireUi { } Ok(name) } - fn start(&mut self, settings: &mut Settings) { - if self.learning_error.is_some() - || self.library_error.is_some() - || self.has_unsaved() - || self.preparing - { + + fn start(&mut self, kind: SessionKind, settings: &Settings) { + if self.preparing.is_some() || self.has_unsaved() { return; } - let Some((id, name)) = self - .selected - .as_ref() - .and_then(|id| self.library.repertoire(id)) - .map(|r| (r.id.clone(), r.name.clone())) - else { + let Some(id) = self.selected.clone() else { return; }; - let Some((scope, summary)) = self - .selected_aggregate() - .map(|scoped| (scoped.scope.clone(), scoped.summary.clone())) - else { - return; - }; - let kind = self.selected_start_kind(&summary); - if kind == StartKind::Unavailable { - return; - } - let introduce_new = - self.queue == QueueMode::SpacedRepetition && kind == StartKind::IntroduceNew; - let scope = if self.queue == QueueMode::SpacedRepetition { - scope - } else { - scope.with_learning_priority(self.priority) - }; - let queue = self.queue; - let mode = training_mode(self.side); - let context_policy = settings - .repertoire_context_policies - .get(id.as_str()) - .copied() - .unwrap_or_default(); + let name = self.selected_name(); + let side = layout::side_of(settings, &id); + let scope = StatsScope::for_repertoire(id.clone(), side, layout::end_of_today()); let library = self.library.clone(); let store = self.learning_store.clone(); + let job = next_job(); let tx = self.tx.clone(); - self.training_generation += 1; - let generation = self.training_generation; - settings - .repertoire_modes - .insert(id.to_string(), (mode, queue)); - settings - .repertoire_priorities - .insert(id.to_string(), self.priority); - self.close_editor(); - self.invalidate_reset_jobs(); - self.training_name = name; - self.scroll_to_selected = true; - self.preparing = true; - if let Err(error) = crate::platform::spawn("repertoire-training-start", move || { - let result = LearningTrainingUi::new_with_policy( - library, - store, - scope, - SrsSettings::default(), - introduce_new, - false, - queue, - context_policy, - ) - .map(Box::new) - .map_err(|e| e.to_string()); - let _ = tx.send(Event::TrainingReady(generation, result)); - }) { - self.preparing = false; - self.error = Some(error.to_string()); - } - } - fn import_path( - &mut self, - path: PathBuf, - target: Option, - ctx: Option, - ) { - if self.cancel.is_some() { - return; - } - let cancel = Arc::new(AtomicBool::new(false)); - self.cancel = Some(cancel.clone()); - let tx = self.tx.clone(); - let base = self.library.clone(); - let result = crate::platform::spawn("repertoire-import", move || { - let result = read_import(&path, target, base, &cancel); - let _ = tx.send(Event::Imported(result)); - if let Some(ctx) = ctx { - ctx.request_repaint(); + let session_kind = kind.clone(); + let slow = debug_slow(); + if let Err(error) = crate::platform::spawn("repertoire-session-start", move || { + if let Some(slow) = slow { + std::thread::sleep(slow); } - }); - if let Err(e) = result { - self.cancel = None; - self.error = Some(e.to_string()); - } - } - fn pick_import(&mut self, target: Option, ctx: &egui::Context) { - if self.cancel.is_some() { + let result = OpeningSessionUi::new(library, store, scope, session_kind).map(Box::new); + let _ = tx.send(Event::SessionReady(job, result)); + }) { + self.show_message(error.to_string(), true); return; } + self.preparing = Some(Preparing { + job, + since: Instant::now(), + id, + name, + kind, + }); + } + + fn more_new(&mut self) { + let Screen::Session(session) = &self.screen else { + return; + }; + let Some(id) = self.selected.clone() else { + return; + }; + let snapshot = session.snapshot().clone(); + let orientation = session.orientation(); + let library = self.library.clone(); + let store = self.learning_store.clone(); + let job = next_job(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-session-more", move || { + let result = + OpeningSessionUi::more_new(library, store, snapshot, orientation).map(Box::new); + let _ = tx.send(Event::SessionReady(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.preparing = Some(Preparing { + job, + since: Instant::now(), + id, + name: self.selected_name(), + kind: SessionKind::Daily, + }); + } + + fn open_lines(&mut self, settings: &Settings, cursor: Option>) { + let Some(id) = self.selected.clone() else { + return; + }; + let side = layout::side_of(settings, &id); + let library = self.library.clone(); + let learning = self.learning.learning.clone(); + let job = next_job(); + self.lines_job = Some(job); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-lines", move || { + let lines = OpeningLinesUi::new(&library, &learning, id, side, cursor).map(Box::new); + let _ = tx.send(Event::LinesReady(job, lines)); + }) { + self.lines_job = None; + self.show_message(error.to_string(), true); + } + } + + fn pick_import(&mut self, target: Option, ctx: &egui::Context) { + let job = next_job(); let cancel = Arc::new(AtomicBool::new(false)); - self.cancel = Some(cancel.clone()); + let base = self.library.clone(); let tx = self.tx.clone(); let ctx = ctx.clone(); - let base = self.library.clone(); - if let Err(e) = crate::platform::spawn("repertoire-import-dialog", move || { - let result = rfd::FileDialog::new() + let worker_cancel = cancel.clone(); + let worker_target = target.clone(); + if let Err(error) = crate::platform::spawn("repertoire-import-dialog", move || { + let picked = rfd::FileDialog::new() .add_filter("PGN", &["pgn", "PGN"]) - .pick_file() - .ok_or_else(|| tr("Cancelled").to_owned()) - .and_then(|path| read_import(&path, target, base, &cancel)); - let _ = tx.send(Event::Imported(result)); + .pick_file(); + let Some(path) = picked else { + let _ = tx.send(Event::Imported(job, Err(String::new()))); + ctx.request_repaint(); + return; + }; + let _ = tx.send(Event::Imported( + job, + read_import(&path, worker_target, base, &worker_cancel), + )); ctx.request_repaint(); }) { - self.cancel = None; - self.error = Some(e.to_string()); + self.show_message(error.to_string(), true); + return; } + self.dialog = Some(Dialog::Import(ImportDialog { + job, + target, + preview: None, + name: String::new(), + side: LearningSide::White, + error: None, + cancel, + })); } - fn confirm_import(&mut self, settings: &Settings) -> bool { - let Some(preview) = self.import.take() else { + + fn import_path(&mut self, path: PathBuf, target: Option) { + let job = next_job(); + let cancel = Arc::new(AtomicBool::new(false)); + let base = self.library.clone(); + let tx = self.tx.clone(); + let worker_cancel = cancel.clone(); + let worker_target = target.clone(); + if let Err(error) = crate::platform::spawn("repertoire-import", move || { + let _ = tx.send(Event::Imported( + job, + read_import(&path, worker_target, base, &worker_cancel), + )); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Import(ImportDialog { + job, + target, + preview: None, + name: String::new(), + side: LearningSide::White, + error: None, + cancel, + })); + } + + /// Imports what the dialog shows. Returns whether it was saved. + fn confirm_import(&mut self, settings: &mut Settings) -> bool { + let Some(Dialog::Import(dialog)) = &self.dialog else { return false; }; - let result = self.merge_import(&preview); - match result { - Ok((library, id)) if self.persist(library.clone()) => { - self.select(id, settings); - true + let Some(preview) = &dialog.preview else { + return false; + }; + if preview.base_revision != self.library.revision { + let error = tr("The library changed; import the PGN again").to_owned(); + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error); } - Ok(_) => { - self.import = Some(preview); - false - } - Err(e) => { - self.error = Some(e); - self.import = Some(preview); - false - } - } - } - fn merge_import(&self, preview: &ImportPreview) -> Result<(Library, RepertoireId), String> { - if preview.library.revision != self.library.revision { - return Err(tr("The library changed; import the PGN again").to_owned()); + return false; } let mut library = preview.library.clone(); - if preview.target.is_none() { - let name = self.checked_name(&preview.name, None)?; - library - .rename(&preview.id, name) - .map_err(|e| e.to_string())?; + let id = preview.id.clone(); + let target = dialog.target.clone(); + let side = dialog.side; + if target.is_none() { + match self.checked_name(&dialog.name, None) { + Ok(name) => { + if let Err(error) = library.rename(&id, name) { + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error.to_string()); + } + return false; + } + } + Err(error) => { + if let Some(Dialog::Import(dialog)) = &mut self.dialog { + dialog.error = Some(error); + } + return false; + } + } } - Ok((library, preview.id.clone())) + if !self.persist(library) { + return false; + } + if target.is_none() { + layout::set_side(settings, &id, side); + } + self.dialog = None; + self.select(id); + true } + fn export(&mut self, ctx: Option) { let Some(r) = self .selected @@ -807,156 +757,317 @@ impl RepertoireUi { let pgn = r.pgn.clone(); let name = format!("{}.pgn", r.name.replace(['/', '\\'], "_")); let tx = self.tx.clone(); - if let Err(e) = crate::platform::spawn("repertoire-export", move || { - let result = if let Some(path) = std::env::var_os("CP_REPERTOIRE_EXPORT_FILE") + if let Err(error) = crate::platform::spawn("repertoire-export", move || { + let path = std::env::var_os("CP_REPERTOIRE_EXPORT_FILE") .map(PathBuf::from) .or_else(|| { rfd::FileDialog::new() .set_file_name(name) .add_filter("PGN", &["pgn"]) .save_file() - }) { - chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) - .map_err(|e| e.to_string()) - } else { - Ok(()) + }); + let result = match path { + Some(path) => chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) + .map(|()| Some(path)) + .map_err(|error| error.to_string()), + None => Ok(None), }; let _ = tx.send(Event::Exported(result)); if let Some(ctx) = ctx { ctx.request_repaint(); } }) { - self.error = Some(e.to_string()); + self.show_message(error.to_string(), true); } } + + fn open_color_dialog(&mut self, settings: &Settings) { + let Some(id) = self.selected.clone() else { + return; + }; + let to = match layout::side_of(settings, &id) { + LearningSide::White => LearningSide::Black, + LearningSide::Black => LearningSide::White, + }; + let job = next_job(); + let library = self.library.clone(); + let tx = self.tx.clone(); + let scope = StatsScope::for_repertoire(id.clone(), to, layout::now()); + if let Err(error) = crate::platform::spawn("repertoire-other-side", move || { + let count = active_learning_keys(&library, &scope) + .map(|keys| keys.len()) + .map_err(|error| error.to_string()); + let _ = tx.send(Event::OtherSide(job, count)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Color { + id, + to, + job, + count: None, + }); + } + + fn open_reset_dialog(&mut self, settings: &Settings) { + let Some(id) = self.selected.clone() else { + return; + }; + let scope = + StatsScope::for_repertoire(id.clone(), layout::side_of(settings, &id), layout::now()); + let job = next_job(); + let library = self.library.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-reset-impact", move || { + let result = reset_impact(&library, &scope) + .and_then(|impact| { + active_learning_keys(&library, &scope).map(|keys| (impact, keys)) + }) + .map_err(|error| error.to_string()); + let _ = tx.send(Event::ResetImpact(job, result)); + }) { + self.show_message(error.to_string(), true); + return; + } + self.dialog = Some(Dialog::Reset { + id, + job, + impact: None, + busy: false, + }); + } + + fn confirm_reset(&mut self) { + let Some(Dialog::Reset { + job, + impact: Some((_, keys)), + busy, + .. + }) = &mut self.dialog + else { + return; + }; + if *busy { + return; + } + *busy = true; + let job = *job; + let keys = keys.clone(); + let store = self.learning_store.clone(); + let tx = self.tx.clone(); + if let Err(error) = crate::platform::spawn("repertoire-reset", move || { + let result = store + .reset_learning(keys) + .map_err(|error| error.to_string()) + .and_then(|_| store.load().map_err(|error| error.to_string())); + let _ = tx.send(Event::ResetDone(job, result)); + }) { + self.dialog = None; + self.show_message(error.to_string(), true); + } + } + + fn delete_selected(&mut self) { + let Some(Dialog::Delete { id }) = &self.dialog else { + return; + }; + let id = id.clone(); + let order = self.sorted_ids(); + let position = order.iter().position(|other| *other == id); + let mut library = self.library.clone(); + if let Err(error) = library.delete(&id) { + self.show_message(error.to_string(), true); + return; + } + if !self.persist(library) { + return; + } + self.dialog = None; + let order = self.sorted_ids(); + self.selected = position + .and_then(|position| order.get(position.min(order.len().saturating_sub(1)))) + .cloned(); + self.scroll_to_selected = true; + } + 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) => { - if self.current_aggregate_key().as_ref() == Some(&key) - && let Err(error) = &*result - { - self.error = Some(error.clone()); - } - if let Some(value) = self.aggregates.get_mut(&key) { - *value = Some(*result); + Event::Indexed(job, index) => { + if job == self.index_job { + self.index = index; } } - Event::ResetImpact(generation, result) => { - if generation != self.reset_generation { + Event::Stats(key, stats) => { + if self.stats_key.as_ref() == Some(&key) { + self.stats = stats; + } + } + Event::Imported(job, result) => { + let Some(Dialog::Import(dialog)) = &mut self.dialog else { + continue; + }; + if dialog.job != job { continue; } - match *result { - Ok((impact, keys)) => { - if let Some(state) = &mut self.shared_reset { - state.impact = Some(impact); - state.keys = keys; - } - } - Err(error) => { - self.shared_reset = None; - self.error = Some(error); - } - } - } - Event::LearningReset(generation, result) => { - if generation != self.reset_generation { - continue; - } - match *result { - Ok(data) => { - self.learning = data; - self.learning_error = None; - self.shared_reset = None; - self.aggregates.clear(); - self.training = None; - self.training_visible = false; - self.reset_generation = self.reset_generation.wrapping_add(1); - } - Err(error) => { - if let Some(state) = &mut self.shared_reset { - state.busy = false; - } - self.error = Some(error); - } - } - } - Event::ReviewReset(generation, result) => { - if generation != self.reset_generation { - continue; - } - self.review_reset_pending = false; - match *result { - Ok(data) => { - self.learning = data; - self.learning_error = None; - self.aggregates.clear(); - self.training = None; - self.training_visible = false; - self.reset_generation = self.reset_generation.wrapping_add(1); - } - Err(error) => self.error = Some(error), - } - } - Event::Indexed(generation, trees, openings, variant_counts) => { - if generation == self.index_generation { - self.trees = trees; - self.openings = openings; - self.variant_counts = variant_counts; - self.indexing = false; - self.update_selected_tree(); - } - } - Event::TrainingReady(generation, result) => { - if generation != self.training_generation || !self.preparing { - continue; - } - self.preparing = false; match result { - Ok(training) if training.target_available() => { - self.training = Some(*training); - self.training_visible = true; + Ok(preview) => { + dialog.name = preview.default_name.clone(); + dialog.side = preview.suggested; + if let Some(target) = &dialog.target { + dialog.side = layout::side_of(settings, target); + } + dialog.preview = Some(preview); + } + // The file chooser was closed. + Err(error) if error.is_empty() => self.dialog = None, + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + Event::Exported(Ok(Some(path))) => { + self.show_message(trf("Saved to {path}", &[("path", &path.display())]), false) + } + Event::Exported(Ok(None)) => {} + Event::Exported(Err(error)) => { + self.show_message(trf("Could not save: {e}", &[("e", &error)]), true) + } + Event::SessionReady(job, result) => { + if self.preparing.as_ref().is_none_or(|p| p.job != job) { + continue; + } + self.preparing = None; + match result { + Ok(mut session) if session.target_available() => { + if let Screen::Lines(lines) = + std::mem::replace(&mut self.screen, Screen::Repertoires) + { + self.lines_return = Some(lines); + } + session.set_back_to_lines(self.lines_return.is_some()); + self.screen = Screen::Session(session); if let Some(moves) = self.debug_pending_moves.take() { self.debug_moves(&moves); } } - Ok(_) => self.error = Some(tr("No targets in this mode").to_owned()), - Err(error) => self.error = Some(error), + Ok(_) => { + self.screen_back_from_session(); + self.show_message(tr("Nothing to train here right now"), false); + } + Err(error) => { + self.screen_back_from_session(); + self.show_message(error, true); + } } } - Event::Imported(result) => { - let cancelled = self - .cancel - .take() - .is_some_and(|c| c.load(Ordering::Relaxed)); - if cancelled { + Event::LinesReady(job, lines) => { + if self.lines_job != Some(job) { continue; } - match result { - Ok(preview) => self.import = Some(preview), - Err(e) => self.error = Some(e), + self.lines_job = None; + if let Some(mut lines) = lines { + if let Ok(path) = std::env::var("CP_REPERTOIRE_LINE") { + let path: Vec = + path.split_whitespace().map(str::to_owned).collect(); + lines.debug_select(&path); + } + self.screen = Screen::Lines(lines); + } + } + Event::LearningLoaded(Ok(data)) => { + self.learning_loading = false; + self.learning = data; + self.learning_error = None; + } + Event::LearningLoaded(Err(error)) => { + self.learning_loading = false; + self.learning_error = Some(error); + } + Event::OtherSide(job, result) => { + if let Some(Dialog::Color { + job: expected, + count, + .. + }) = &mut self.dialog + && *expected == job + { + match result { + Ok(value) => *count = Some(value), + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + } + Event::ResetImpact(job, result) => { + if let Some(Dialog::Reset { + job: expected, + impact, + .. + }) = &mut self.dialog + && *expected == job + { + match result { + Ok(value) => *impact = Some(value), + Err(error) => { + self.dialog = None; + self.show_message(error, true); + } + } + } + } + Event::ResetDone(job, result) => { + if !matches!(&self.dialog, Some(Dialog::Reset { job: expected, .. }) if *expected == job) + { + continue; + } + self.dialog = None; + match result { + Ok(data) => { + self.learning = data; + self.learning_error = None; + } + Err(error) => self.show_message(error, true), } } - Event::Exported(Err(e)) => self.error = Some(e), - Event::Exported(Ok(())) => {} } } - if self.import.is_some() && std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() { + if std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() + && matches!(&self.dialog, Some(Dialog::Import(d)) if d.preview.is_some()) + { self.confirm_import(settings); } - if self.cancel.is_none() - && self.import.is_none() + if let Some(message) = &self.message + && message.until.is_some_and(|until| Instant::now() >= until) + { + self.message = None; + } + if self.preparing.is_none() + && self.dialog.is_none() && let Some(what) = self.debug_start.take() { self.debug_open(&what, settings); } + self.request_stats(settings); } + + fn screen_back_from_session(&mut self) { + self.screen = match self.lines_return.take() { + Some(lines) => Screen::Lines(lines), + None if matches!(self.screen, Screen::Lines(_)) => { + std::mem::replace(&mut self.screen, Screen::Repertoires) + } + None => Screen::Repertoires, + }; + } + pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec { self.poll(settings); let mut actions = Vec::new(); @@ -964,1039 +1075,983 @@ impl RepertoireUi { let background = ui.visuals().window_fill(); ui.painter_at(available) .rect_filled(available, 0.0, background); - #[cfg(test)] - { - self.debug_layout.editor = None; + if self.preparing.is_some() || self.lines_job.is_some() { + ui.ctx().request_repaint_after(Duration::from_millis(50)); } - if self.training_visible && self.training.is_some() { - let mut training = self.training.take().expect("checked training session"); - let name = self.training_name.clone(); - let emitted = training.show(ui, settings, &name); - if self.training_visible { - self.training = Some(training); - } - for action in emitted { + if let Some(preparing) = &self.preparing + && preparing.since.elapsed() >= PREPARING_SHOWN_AFTER + { + let side = layout::side_of(settings, &preparing.id); + let index = self.index.get(&preparing.id); + let start = index.map(|row| row.start.clone()).unwrap_or_default(); + let subtitle = preparing.kind.subtitle(side); + let view = PreparingView { + name: &preparing.name, + subtitle: &subtitle, + back: if matches!(self.screen, Screen::Lines(_)) { + tr("⬅ Lines") + } else { + tr("⬅ Repertoires") + }, + position: &start, + orientation: layout::orientation(side), + last_move: index.and_then(|row| row.last_move), + lines: preparing.kind != SessionKind::Daily, + }; + for action in show_preparing(ui, settings, &mut self.board, &view) { match action { - TrainingAction::Back => { - self.reload_learning(); - self.training_visible = false; - self.scroll_to_selected = true; + SessionAction::Back => { + self.preparing = None; + self.screen_back_from_session(); } - TrainingAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), - TrainingAction::Sound(sound) => actions.push(RepertoireAction::Sound(sound)), - TrainingAction::Toast(text) => actions.push(RepertoireAction::Toast(text)), + SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + SessionAction::Sound(_) | SessionAction::MoreNew => {} } } return actions; } - if self.editor.is_some() { - #[cfg(test)] - { - self.debug_layout.editor = Some(ui.available_rect_before_wrap()); + match std::mem::replace(&mut self.screen, Screen::Repertoires) { + Screen::Session(mut session) => { + let name = self.selected_name(); + let emitted = session.show(ui, settings, &name); + self.screen = Screen::Session(session); + for action in emitted { + match action { + SessionAction::Back => { + self.reload_learning(); + self.screen_back_from_session(); + if let Screen::Lines(lines) = &mut self.screen { + lines.refresh(&self.library, &self.learning.learning); + } + self.scroll_to_selected = true; + } + SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + SessionAction::Sound(sound) => actions.push(RepertoireAction::Sound(sound)), + SessionAction::MoreNew => self.more_new(), + } + } + return actions; } - let mut editor = self.editor.take().expect("checked repertoire editor"); - let emitted = editor.show(ui, settings, &self.library_store); - for action in emitted { - actions.extend(self.handle_editor_action(action)); + Screen::Lines(mut lines) => { + let emitted = lines.show(ui, settings); + self.screen = Screen::Lines(lines); + for action in emitted { + self.lines_action(action, settings, &mut actions); + } + return actions; } - if self.editor_id.is_some() { - self.editor = Some(editor); - } - return actions; + Screen::Repertoires => {} } - if self.dashboard.is_some() { - let mut dashboard = self.dashboard.take().expect("checked learning dashboard"); - 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 { - self.dashboard = Some(dashboard); - } - return actions; - } - if !ui.ctx().egui_wants_keyboard_input() - && !crate::app::overlay_open(ui.ctx()) - && self.add.is_none() - && ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) - { - actions.push(RepertoireAction::Close); - } - egui::Panel::top("repertoire_header").show(ui, |ui| { - 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); + self.repertoires_screen(ui, settings, &mut actions); + self.show_dialog(ui.ctx(), settings, &mut actions); + self.show_add(ui, settings, &mut actions); actions } - fn errors(&mut self, ui: &mut Ui) { - let (rect, _) = - ui.allocate_exact_size(egui::vec2(ui.available_width(), 24.0), egui::Sense::hover()); - let mut status = ui.new_child( - egui::UiBuilder::new() - .max_rect(rect) - .layout(egui::Layout::left_to_right(egui::Align::Center)), - ); - let ui = &mut status; - ui.set_clip_rect(rect); - #[cfg(test)] - { - self.debug_layout.status = Some(rect); - self.debug_layout.message = None; - self.debug_layout.retry = None; - self.debug_layout.cancel = None; - } - let error = self - .library_error - .clone() - .or_else(|| self.learning_error.clone()) - .or_else(|| self.error.clone()); - let background = if self.indexing { - Some(tr("Indexing variations and ECO names…")) - } else if self.preparing { - Some(tr("Preparing the training session…")) - } else if self.cancel.is_some() { - Some(tr("Importing PGN…")) - } else { - None - }; - if background.is_some() { - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - } - let mut retry = false; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if error.is_some() { - let response = ui.button(tr("Retry")); - retry = response.clicked(); - #[cfg(test)] - { - self.debug_layout.retry = Some(response.rect); - } + + fn lines_action( + &mut self, + action: LinesAction, + settings: &mut Settings, + actions: &mut Vec, + ) { + match action { + LinesAction::Back => { + self.screen = Screen::Repertoires; + self.scroll_to_selected = true; } - if self.cancel.is_some() { - let response = ui.button(tr("Cancel")); - if response.clicked() - && let Some(cancel) = &self.cancel - { - cancel.store(true, Ordering::Relaxed); - } - #[cfg(test)] - { - self.debug_layout.cancel = Some(response.rect); - } - } - if background.is_some() { - ui.add(egui::Spinner::new().size(16.0)); - } - if let Some(text) = error.as_deref().or(background) { - let hover = text.to_owned(); - let text = if error.is_some() { - RichText::new(text).color(ui.visuals().error_fg_color) + LinesAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), + LinesAction::Train { through, label } => { + let kind = if through.is_empty() { + SessionKind::ReviewAll } else { - RichText::new(text) + SessionKind::Branch { through, label } }; - let response = ui.add(egui::Label::new(text).truncate().halign(egui::Align::Min)); - #[cfg(test)] + self.start(kind, settings); + } + LinesAction::SetDisabled { path, disabled } => { + let Screen::Lines(lines) = &self.screen else { + return; + }; + let id = lines.id().clone(); + let mut library = self.library.clone(); + let Some(repertoire) = library.repertoire_mut(&id) else { + return; + }; + if let Err(error) = repertoire.set_prefix_disabled(&path, disabled) { + self.show_message(error.to_string(), true); + return; + } + if self.persist(library) + && let Screen::Lines(lines) = &mut self.screen { - self.debug_layout.message = Some(response.rect); + lines.refresh(&self.library, &self.learning.learning); } - response.on_hover_text(hover); } - }); - if retry { - match load_library(&self.library_store) { - Ok(data) => { - self.library = data; - self.library_error = None; - self.rebuild_tree(); - } - Err(e) => self.library_error = Some(e.message), - } - self.reload_learning(); - self.error = None; } } - fn show_library(&mut self, ui: &mut Ui, settings: &Settings) { - self.errors(ui); - 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)), + + fn keyboard(&mut self, ui: &Ui, settings: &mut Settings, actions: &mut Vec) { + if ui.ctx().egui_wants_keyboard_input() + || crate::app::overlay_open(ui.ctx()) + || self.dialog.is_some() + || self.add.is_some() + { + return; + } + let mut command = None; + ui.input_mut(|input| { + if input.consume_key(Modifiers::NONE, Key::Escape) { + command = Some("close"); + } else if input.consume_key(Modifiers::NONE, Key::ArrowDown) { + command = Some("down"); + } else if input.consume_key(Modifiers::NONE, Key::ArrowUp) { + command = Some("up"); + } else if input.consume_key(Modifiers::NONE, Key::Enter) { + command = Some("main"); + } + }); + let rows = self.visible_ids(); + let current = self + .selected + .as_ref() + .and_then(|id| rows.iter().position(|row| row == id)); + match command { + Some("close") => actions.push(RepertoireAction::Close), + Some("down") => { + let next = current.map_or(0, |i| (i + 1).min(rows.len().saturating_sub(1))); + if let Some(id) = rows.get(next).cloned() { + self.select(id); + } + } + Some("up") => { + let next = current.map_or(0, |i| i.saturating_sub(1)); + if let Some(id) = rows.get(next).cloned() { + self.select(id); + } + } + Some("main") => self.main_action(ui.ctx(), settings), + _ => {} + } + } + + fn visible_ids(&self) -> Vec { + let search = self.search.to_lowercase(); + self.sorted_ids() + .into_iter() + .filter(|id| { + self.library + .repertoire(id) + .is_some_and(|r| r.name.to_lowercase().contains(&search)) + }) + .collect() + } + + fn selected_card(&self) -> CardState { + let Some(id) = &self.selected else { + return CardState::Counting; + }; + if let Some(error) = self.library_error.clone().or(self.learning_error.clone()) { + return CardState::Failed(error); + } + card_state( + self.index.get(id).map(|row| row.has_moves), + self.stats.get(id), + ) + } + + /// The card's main button. + fn main_action(&mut self, ctx: &egui::Context, settings: &mut Settings) { + match self.selected_card() { + CardState::Review { .. } | CardState::OnlyNew { .. } => { + self.start(SessionKind::Daily, settings) + } + CardState::Done { .. } => self.start(SessionKind::ReviewAll, settings), + CardState::Empty => { + let target = self.selected.clone(); + self.pick_import(target, ctx); + } + CardState::OtherColor => self.open_color_dialog(settings), + CardState::Counting => {} + CardState::Failed(_) => self.retry_load(), + } + } + + fn retry_load(&mut self) { + match load_library(&self.library_store) { + Ok(library) => { + self.library = library; + self.library_error = None; + self.reindex(); + } + Err(error) => self.library_error = Some(error), + } + match self.learning_store.load() { + Ok(data) => { + self.learning = data; + self.learning_error = None; + } + Err(error) => self.learning_error = Some(error.to_string()), + } + self.stats_key = None; + self.stats.clear(); + } + + fn menu_item(&mut self, item: MenuItem, ctx: &egui::Context, settings: &mut Settings) { + match item { + MenuItem::Train => self.main_action(ctx, settings), + MenuItem::ReviewAll => self.start(SessionKind::ReviewAll, settings), + MenuItem::Lines => self.open_lines(settings, None), + MenuItem::Rename => { + if let Some(id) = self.selected.clone() { + self.dialog = Some(Dialog::Rename { + name: self.selected_name(), + id, + error: None, + select_all: true, + }); + } + } + MenuItem::SwitchColor => self.open_color_dialog(settings), + MenuItem::AddPgn => { + let target = self.selected.clone(); + self.pick_import(target, ctx); + } + MenuItem::Export => self.export(Some(ctx.clone())), + MenuItem::Reset => self.open_reset_dialog(settings), + MenuItem::Delete => { + if let Some(id) = self.selected.clone() { + self.dialog = Some(Dialog::Delete { id }); + } + } + } + } + + fn repertoires_screen( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { + self.keyboard(ui, settings, actions); + let back = if self.return_to_game.is_some() { + tr("⬅ To game") + } else { + tr("⬅ Library") + }; + let back = if ui.available_width() < 600.0 { + "⬅" + } else { + back + }; + let count = self.library.repertoires.len(); + let subtitle = if count == 0 { + String::new() + } else { + trf("{n} repertoires", &[("n", &count)]) + }; + let mut header = (false, false); + let mut menu = None; + layout::screen( + ui, + self, + |_, ui| { + header = crate::widgets::section_header_sub( + ui, + back, + tr("Opening training (α version)"), + &subtitle, + ) + }, + |this, ui| menu = this.panel(ui, settings), + |this, ui| this.preview_board(ui, settings), + ); + if header.0 { + actions.push(RepertoireAction::Close); + } + if header.1 { + actions.push(RepertoireAction::OpenSettings); + } + if let Some(item) = menu { + self.menu_item(item, ui.ctx(), settings); + } + } + + fn preview_board(&mut self, ui: &mut Ui, settings: &Settings) { + let row = self.selected.as_ref().and_then(|id| self.index.get(id)); + let position = row.map(|row| row.start.clone()).unwrap_or_default(); + let last_move = row.and_then(|row| row.last_move); + let side = self + .selected + .as_ref() + .map_or(LearningSide::White, |id| layout::side_of(settings, id)); + layout::still_board( + ui, + &mut self.board, + settings, + &position, + layout::orientation(side), + last_move, + &BoardAnnotations::default(), + ); + } + + /// The right panel; returns a chosen menu item (or the card's buttons). + fn panel(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let mut chosen = None; + let rect = ui.available_rect_before_wrap(); + ui.spacing_mut().item_spacing.y = GAP; + if self.library.repertoires.is_empty() { + self.empty_panel(ui, rect); + return None; + } + ui.add_space(4.0); + chosen = chosen.or(self.card(ui, settings)); + if self.library.repertoires.len() > 8 { + layout::fixed_block(ui, 24.0, |ui| { + ui.add( + egui::TextEdit::singleline(&mut self.search) + .hint_text(tr("Search")) + .desired_width(f32::INFINITY), + ); + }); + } + let table_h = (ui.available_height() - MESSAGE_H - BOTTOM_H - 3.0 * GAP).max(HEADER_H); + let table = layout::fixed_block(ui, table_h, |ui| self.table(ui, settings)); + chosen = chosen.or(table); + layout::fixed_block(ui, MESSAGE_H, |ui| self.message_strip(ui)); + layout::fixed_block(ui, BOTTOM_H, |ui| { + ui.horizontal(|ui| { + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("Import PGN…")) + .truncate() + .min_size(vec2(BOTTOM_W, BOTTOM_H)), + ) + .clicked() + { + self.pick_import(None, ui.ctx()); + } + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("New repertoire")) + .truncate() + .min_size(vec2(BOTTOM_W, BOTTOM_H)), + ) + .clicked() + { + self.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + } + }); + }); + chosen + } + + fn empty_panel(&mut self, ui: &mut Ui, rect: egui::Rect) { + let height = 200.0; + let top = rect.top() + ((rect.height() - height) / 2.0).max(0.0); + let area = + egui::Rect::from_min_size(egui::pos2(rect.left(), top), vec2(rect.width(), height)); + ui.scope_builder( + egui::UiBuilder::new() + .max_rect(area) + .layout(egui::Layout::top_down(egui::Align::Center)), + |ui| { + ui.heading(tr("No repertoires yet")); + ui.add_space(6.0); + ui.add( + egui::Label::new(RichText::new(tr("A repertoire is your opening moves as a PGN with variations. Import a file, or open any game, pick a move and choose “Add to repertoire…”.")).weak()) + .wrap(), + ); + ui.add_space(12.0); + if ui + .add_enabled_ui(self.library_error.is_none(), |ui| { + crate::widgets::primary_wide(ui, tr("Import PGN…"), BOTTOM_W) + }) + .inner + .clicked() + { + self.pick_import(None, ui.ctx()); + } + if ui + .add_enabled( + self.library_error.is_none(), + egui::Button::new(tr("New repertoire")).min_size(vec2(BOTTOM_W, 30.0)), + ) + .clicked() + { + self.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + } + if let Some(error) = &self.library_error { + ui.add_space(8.0); + ui.add( + egui::Label::new( + RichText::new(trf("Could not read the repertoires: {e}", &[("e", error)])) + .color(ui.visuals().warn_fg_color), ) - .clicked() - { - self.pick_import(None, ui.ctx()); + .wrap(), + ); + } + }, + ); + } + + fn card(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let Some(id) = self.selected.clone() else { + layout::fixed_block(ui, CARD_H, |_| {}); + return None; + }; + let state = self.selected_card(); + let stats = self + .stats + .get(&id) + .and_then(|stats| stats.as_ref().ok()) + .cloned(); + let side = layout::side_of(settings, &id); + let name = self.selected_name(); + let mut chosen = None; + layout::fixed_block(ui, CARD_H, |ui| { + let inner = vec2(ui.available_width() - 20.0, CARD_H - 12.0); + layout::card(ui, false, false).show(ui, |ui| { + ui.set_min_size(inner); + ui.set_max_size(inner); + ui.spacing_mut().item_spacing.y = 7.0; + let width = ui.available_width(); + // 1. The name and the colour. + layout::fixed_block(ui, 26.0, |ui| { + ui.horizontal(|ui| { + let you = format!("{} {}", layout::king(side), layout::you_play(side)); + let you_w = text_width(ui, &you, 14.0) + 8.0; + ui.allocate_ui_with_layout( + vec2((width - you_w).max(0.0), 26.0), + egui::Layout::left_to_right(egui::Align::Center), + |ui| layout::line(ui, RichText::new(&name).heading()), + ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(you).weak()); + }); + }); + }); + // 2. Today. + let (today, note) = card_texts(&state, side); + layout::fixed_block(ui, 22.0, |ui| { + let mut text = RichText::new(today).strong().size(15.0); + if matches!(state, CardState::Failed(_)) { + text = text.color(ui.visuals().warn_fg_color); } + layout::line(ui, text); + }); + // 3. Progress. + layout::fixed_block(ui, 28.0, |ui| progress(ui, stats.as_ref())); + // 4. A quiet explanation. + layout::fixed_block(ui, 20.0, |ui| { + layout::line(ui, RichText::new(note).weak()); + }); + // 5. Buttons. + layout::fixed_block(ui, 30.0, |ui| { + ui.horizontal(|ui| { + let (label, enabled, item) = main_button(&state, side); + let third = matches!(state, CardState::OnlyNew { .. }); + let gap = ui.spacing().item_spacing.x; + let room = ui.available_width(); + let (main_w, lines_w, third_w) = + if MAIN_W + LINES_W + THIRD_W + 2.0 * gap <= room || !third { + (MAIN_W, LINES_W, THIRD_W) + } else { + let rest = ((room - MAIN_W - 2.0 * gap) / 2.0).max(60.0); + (MAIN_W.min(room / 2.0), rest, rest) + }; + let response = ui + .add_enabled_ui(enabled, |ui| { + crate::widgets::primary_wide(ui, &label, main_w) + }) + .inner; + let response = if matches!(state, CardState::Counting) { + response.on_disabled_hover_text(tr("Counting moves…")) + } else { + response + }; + if response.clicked() { + chosen = item; + } + if ui + .add_enabled( + !matches!(state, CardState::Empty | CardState::Failed(_)), + egui::Button::new(tr("Lines…")) + .truncate() + .min_size(vec2(lines_w, 30.0)), + ) + .clicked() + { + chosen = Some(MenuItem::Lines); + } + if third + && ui + .add( + egui::Button::new(tr("Review all lines")) + .truncate() + .min_size(vec2(third_w, 30.0)), + ) + .clicked() + { + chosen = Some(MenuItem::ReviewAll); + } + }); }); }); - self.name_editor(ui, settings); - if self.import.is_some() { - self.import_preview(ui, settings); - } - if self.library.repertoires.is_empty() { - ui.heading(tr("No repertoires yet")); - ui.label(tr("Create an empty one or import PGN. You can also select a move in any game and choose “Add to repertoire…”.")); - } - if self.library.repertoires.len() > 8 { - ui.add(egui::TextEdit::singleline(&mut self.search).hint_text(tr("Search"))); - } - if let Some(id) = self.delete.clone() { - ui.separator(); - ui.label(tr( - "Delete repertoire? Source PGN files and learning history will not change.", - )); - ui.horizontal(|ui| { - if ui.button(tr("Cancel")).clicked() { - self.delete = None; - } - if ui.button(tr("Delete")).clicked() { - let mut library = self.library.clone(); - if library.delete(&id).is_ok() && self.persist(library) { - self.delete = None; - self.selected = None; - self.update_selected_tree(); - if let Some(next) = self.library.repertoires.first().map(|r| r.id.clone()) { - self.select(next, settings); - } else { - self.training_visible = false; - self.training = None; - } - } - } - }); - } + }); + chosen + } - let mut rows: Vec<_> = self - .library - .repertoires - .iter() - .filter(|r| r.name.to_lowercase().contains(&self.search.to_lowercase())) - .map(|r| LibraryRow { - id: r.id.clone(), - name: r.name.clone(), - openings: self.openings.get(&r.id).cloned().unwrap_or_default(), - }) - .collect(); - rows.sort_by_key(|r| r.name.to_lowercase()); - let scroll_row = if self.scroll_to_selected { + fn table(&mut self, ui: &mut Ui, settings: &Settings) -> Option { + let rows = self.visible_ids(); + let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { rows.iter() - .position(|r| Some(&r.id) == self.selected.as_ref()) + .position(|id| Some(id) == self.selected.as_ref()) } else { None }; 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; + let mut double = false; + let mut chosen = None; + let open_menu = std::mem::take(&mut self.debug_menu); ui.style_mut().interaction.selectable_labels = false; - #[cfg(test)] - let table_top = ui.next_widget_position(); - #[cfg(test)] - let table_width = ui.available_width(); let mut table = egui_extras::TableBuilder::new(ui) - .id_salt("repertoire_table") + .id_salt("opening_repertoires") .striped(true) .sense(egui::Sense::click()) .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(egui_extras::Column::remainder().at_least(120.0).clip(true)) - .column(egui_extras::Column::exact(52.0)) - .column(egui_extras::Column::exact(if compact { - 60.0 - } else { - 70.0 - })) - .column(egui_extras::Column::exact(28.0)); + .column(egui_extras::Column::remainder().at_least(80.0).clip(true)) + .column(egui_extras::Column::exact(22.0)) + .column(egui_extras::Column::exact(58.0)) + .column(egui_extras::Column::exact(70.0)) + .column(egui_extras::Column::exact(26.0)); if let Some(index) = scroll_row { - table = table.scroll_to_row(index, Some(egui::Align::Center)); - self.scroll_to_selected = false; + table = table.scroll_to_row(index, None); } table - .header(26.0, |mut header| { - for (column, key) in ["Name", "ECO", "Variants", ""].into_iter().enumerate() { + .header(HEADER_H, |mut header| { + header.col(|ui| { + ui.add(egui::Label::new(RichText::new(tr("Name")).strong()).truncate()); + }); + header.col(|_| {}); + for key in ["Today", "Learned"] { header.col(|ui| { - if column == 2 { - ui.with_layout( - egui::Layout::right_to_left(egui::Align::Center), - |ui| { - ui.add( - egui::Label::new(RichText::new(tr(key)).strong()) - .truncate(), - ); - }, - ); - } else { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate()); - } + }); }); } + header.col(|_| {}); }) .body(|body| { - body.rows(LibraryRow::height(), rows.len(), |mut row| { - let r = &rows[row.index()]; - row.set_selected(self.selected.as_ref() == Some(&r.id)); + body.rows(ROW_H, rows.len(), |mut row| { + let id = &rows[row.index()]; + let Some(repertoire) = self.library.repertoire(id) else { + return; + }; + let side = layout::side_of(settings, id); + let stats = self.stats.get(id); + row.set_selected(self.selected.as_ref() == Some(id)); row.col(|ui| { - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.spacing_mut().item_spacing.y = OPENING_GAP; - ui.add_space(ROW_VERTICAL_PADDING); - table_text_line( - ui, - RichText::new(&r.name).strong().size(16.0), - TITLE_HEIGHT, - ) - .on_hover_text(&r.name); - ui.add_space(TITLE_GAP - OPENING_GAP); - for (index, opening) in r.visible_openings().iter().enumerate() { - let more = - index + 1 == OPENING_LINES && r.openings.len() > OPENING_LINES; - let text = if more { - format!("{} …", opening.name) - } else { - opening.name.clone() - }; - let response = table_text_line( - ui, - RichText::new(text).size(14.0), - OPENING_HEIGHT, - ); - if more { - response.on_hover_text( - r.openings - .iter() - .map(|opening| { - format!("{} {}", opening.eco, opening.name) - }) - .collect::>() - .join("\n"), - ); - } else { - response.on_hover_text(&opening.name); + layout::line(ui, repertoire.name.as_str()); + }); + row.col(|ui| { + ui.label(layout::king(side)) + .on_hover_text(layout::you_play(side)); + }); + row.col(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match stats { + Some(Ok(stats)) if stats.today() > 0 => { + ui.label(stats.today().to_string()).on_hover_text(trf( + "{n} to review, {m} new", + &[("n", &stats.due), ("m", &stats.new_today())], + )); + } + Some(_) => { + ui.label(RichText::new("—").weak()); + } + None => { + ui.label(RichText::new("…").weak()); } } }); }); row.col(|ui| { - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.spacing_mut().item_spacing.y = OPENING_GAP; - ui.add_space(ROW_VERTICAL_PADDING); - table_text_line( - ui, - RichText::new(" ").strong().size(16.0), - TITLE_HEIGHT, - ); - ui.add_space(TITLE_GAP - OPENING_GAP); - if r.openings.is_empty() { - table_text_line( - ui, - RichText::new("—").size(14.0).weak(), - OPENING_HEIGHT, - ); - } else { - for (index, opening) in r.visible_openings().iter().enumerate() { - let more = index + 1 == OPENING_LINES - && r.openings.len() > OPENING_LINES; - let text = if more { - format!("{} …", opening.eco) - } else { - opening.eco.clone() - }; - table_text_line( - ui, - RichText::new(text).size(14.0), - OPENING_HEIGHT, - ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + match stats { + Some(Ok(stats)) if stats.total > 0 => { + ui.label(format!("{}/{}", stats.learnt, stats.total)); + } + Some(_) => { + ui.label(RichText::new("—").weak()); + } + None => { + ui.label(RichText::new("…").weak()); } } }); }); + let mut opened = false; row.col(|ui| { - count_cell(ui, self.variant_counts.get(&r.id).copied()); - }); - 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(); - } - if ui.button(tr("Import PGN into this repertoire…")).clicked() { - import = Some(r.id.clone()); - ui.close(); - } - if ui.button(tr("Export PGN…")).clicked() { - export = Some(r.id.clone()); - ui.close(); - } - if ui.button(tr("Delete…")).clicked() { - self.delete = Some(r.id.clone()); - ui.close(); - } - }); - }); - if row.response().clicked() { - clicked = Some(r.id.clone()); - } - }); - }); - #[cfg(test)] - { - let table_bottom = ui.next_widget_position(); - self.debug_layout.table = Some(egui::Rect::from_min_max( - table_top, - egui::pos2(table_top.x + table_width, table_bottom.y), - )); - } - 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()); - } - if let Some(id) = export { - self.select(id, settings); - self.export(Some(ui.ctx().clone())); - } - } - fn name_editor(&mut self, ui: &mut Ui, settings: &Settings) { - let Some((id, mut name)) = self.edit_name.clone() else { - return; - }; - let mut save = false; - let mut cancel = false; - ui.horizontal_wrapped(|ui| { - let response = ui.add( - egui::TextEdit::singleline(&mut name) - .char_limit(120) - .hint_text(tr("Name")), - ); - save = ui.button(tr("Save")).clicked() - || response.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); - cancel = ui.button(tr("Cancel")).clicked(); - }); - self.edit_name = Some((id.clone(), name.clone())); - if cancel { - self.edit_name = None; - } - if save { - self.save_name(id, &name, settings); - } - } - fn save_name(&mut self, id: Option, name: &str, settings: &Settings) { - match self.checked_name(name, id.as_ref()) { - Ok(name) => { - let mut library = self.library.clone(); - let result = if let Some(id) = id { - library.rename(&id, name).map(|()| id) - } else { - library.create_empty(name) - }; - match result { - Ok(id) if self.persist(library.clone()) => { - self.edit_name = None; - self.select(id, settings); - } - Ok(_) => {} - Err(e) => self.error = Some(e.to_string()), - } - } - Err(e) => self.error = Some(e), - } - } - fn import_preview(&mut self, ui: &mut Ui, settings: &Settings) { - let Some(preview) = self.import.as_mut() else { - return; - }; - ui.separator(); - ui.strong(tr("Import PGN…")); - if preview.target.is_none() { - ui.add( - egui::TextEdit::singleline(&mut preview.name) - .char_limit(120) - .hint_text(tr("Name")), - ); - } - ui.label(format!( - "{}: {} · {}: {}", - tr("Games"), - preview.records, - tr("New moves"), - preview.report.added_nodes - )); - ui.horizontal(|ui| { - if ui.button(tr("Cancel")).clicked() { - self.import = None; - } - if ui.button(tr("Add")).clicked() { - self.confirm_import(settings); - } - }); - } - fn show_workspace( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - actions: &mut Vec, - ) { - let width = ui.available_width(); - let height = ui.available_height(); - let stacked = width < 900.0 && height > width; - if stacked { - let available = ui.available_rect_before_wrap(); - 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(), available.bottom() - panel_height), - ); - let side_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| { - egui::CentralPanel::default().show(ui, |ui| self.preview_board(ui, settings)); - }); - ui.scope_builder(egui::UiBuilder::new().max_rect(side_rect), |ui| { - ui.set_clip_rect(side_rect); - egui::Frame::side_top_panel(ui.style()) - .show(ui, |ui| self.workspace_panel(ui, settings, actions)); - }); - } else { - let width = ui.available_width(); - 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.workspace_panel(ui, settings, actions)); - egui::CentralPanel::default().show(ui, |ui| self.preview_board(ui, settings)); - } - } - fn workspace_panel( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - actions: &mut Vec, - ) { - ui.set_width(ui.available_width()); - let selected = self - .selected - .as_ref() - .and_then(|id| self.library.repertoire(id).cloned()) - .map(|r| (r.id.clone(), r)); - 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); + let button = ui.add(egui::Button::new("⋯").frame(false)); + let mut popup = egui::Popup::menu(&button); + if open_menu && self.selected.as_ref() == Some(id) { + popup = popup.open_memory(Some(egui::SetOpenCommand::Bool(true))); } - if response.clicked() { - self.start(settings); - if self.preparing { - actions.push(RepertoireAction::SettingsChanged); - } + if let Some(item) = + popup + .show(|ui| menu_items(ui, side, stats)) + .and_then(|inner| { + opened = true; + inner.inner + }) + { + chosen = Some(item); } }); - 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)] + let response = row.response(); + if let Some(item) = egui::Popup::context_menu(&response) + .show(|ui| menu_items(ui, side, stats)) + .and_then(|inner| { + opened = true; + inner.inner + }) { - self.debug_layout.action_buttons[1] = Some(parameters.rect); + chosen = Some(item); } - 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 opened && self.selected.as_ref() != Some(id) { + clicked = Some(id.clone()); } if response.clicked() { - self.open_dashboard(); + clicked = Some(id.clone()); + } + if response.double_clicked() { + clicked = Some(id.clone()); + double = true; } }); - 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); - } }); + if let Some(id) = clicked { + self.selected = Some(id); } - ui.separator(); - self.show_library(ui, settings); + if double { + chosen = Some(MenuItem::Train); + } + chosen } - fn parameters_window( + + fn message_strip(&mut self, ui: &mut Ui) { + let Some(message) = &self.message else { + return; + }; + let mut close = false; + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + close = crate::widgets::small_close_button(ui).clicked(); + let mut text = RichText::new(&message.text); + text = if message.error { + text.color(ui.visuals().warn_fg_color) + } else { + text.weak() + }; + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + layout::line(ui, text); + }); + }); + }); + if close { + self.message = None; + } + } + + fn show_dialog( &mut self, ctx: &egui::Context, settings: &mut Settings, actions: &mut Vec, ) { - if !self.parameters_open { - return; - } - let Some(id) = self.selected.clone() else { - self.parameters_open = false; + let Some(dialog) = self.dialog.take() else { return; }; - let name = self + let names: HashMap = 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 { - Some(AggregateKey { - id: self.selected.clone()?, - side: self.side, - library_revision: self.library.revision, - learning_revision: self.learning.revision, - minute: now() / 60, - }) - } - fn selected_aggregate(&mut self) -> Option<&ScopedLearningAggregate> { - let key = self.current_aggregate_key()?; - self.request_aggregate(key.clone()); - self.aggregates.get(&key)?.as_ref()?.as_ref().ok() - } - fn request_aggregate(&mut self, key: AggregateKey) { - if self.aggregates.contains_key(&key) { - return; - } - if self.aggregates.iter().any(|(pending, value)| { - let mut comparable = pending.clone(); - comparable.minute = key.minute; - value.is_none() && comparable == key - }) { - return; - } - let max_depth = self - .library - .repertoire(&key.id) - .map(|repertoire| repertoire.max_plies); - let scope = - StatsScope::for_repertoire(key.id.clone(), key.side, now()).with_max_depth(max_depth); - let library = self.library.clone(); - let learning = self.learning.learning.clone(); - let tx = self.tx.clone(); - let job_key = key.clone(); - self.aggregates.retain(|old, value| { - old.library_revision == key.library_revision - && old.learning_revision == key.learning_revision - && (value.is_none() || old.minute >= key.minute - 1) - }); - self.aggregates.insert(key.clone(), None); - if let Err(error) = crate::platform::spawn("repertoire-aggregate", move || { - let result = aggregate_scope(&library, &learning, &scope, &SrsSettings::default()) - .map_err(|error| error.to_string()); - let _ = tx.send(Event::Aggregated(job_key, Box::new(result))); - }) { - self.aggregates.remove(&key); - self.error = Some(error.to_string()); - } - } - fn preview_board(&mut self, ui: &mut Ui, settings: &Settings) { - let pos = self - .tree - .as_ref() - .and_then(|tree| tree.game().position(NodeId::ROOT)) - .cloned() - .unwrap_or_default(); - let side = ui - .available_width() - .min(ui.available_height()) - .max(1.0) - .floor(); - let available = ui.available_size(); - let offset = egui::vec2( - ((available.x - side) / 2.0).max(0.0).floor(), - ((available.y - side) / 2.0).max(0.0).floor(), - ); - let rect = egui::Rect::from_min_size(ui.cursor().min + offset, egui::vec2(side, side)); - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - BoardView { - pos: &pos, - orientation: self.side.color(), - last_move: None, - arrows: &[], - circles: &[], - badge: None, - interactive: false, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: false, - alert: None, - } - .show(ui, &mut self.board); - }); - } - fn statistics_panel(&mut self, ui: &mut Ui) { - let summary = self - .selected_aggregate() - .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 - .as_ref() - .map_or_else(|| "…".to_owned(), |summary| metric(summary).to_string()) - }; - 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)); - } - } - fn shared_reset_panel(&mut self, ui: &mut Ui) { - let Some(state) = &self.shared_reset else { - return; - }; - let impact = state.impact.clone(); - let busy = state.busy; - ui.separator(); - let Some(impact) = impact else { - ui.spinner(); - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - return; - }; - ui.label(format!( - "{}: {} · {}: {}", - tr("Learning items"), - impact.reset_count, - tr("Shared"), - impact.shared_count - )); - let names = impact - .affected_repertoires + .repertoires .iter() - .map(|repertoire| repertoire.name.as_str()) - .collect::>() - .join(", "); - ui.add( - egui::Label::new(format!( - "{}: {}", - tr("Affected repertoires"), - if names.is_empty() { "—" } else { &names } - )) - .wrap(), - ); - ui.label( - RichText::new(tr( - "Progress in other repertoires will also become Unseen. PGN files will not change.", - )) - .weak(), - ); - let mut confirmed = state.confirmed; - ui.add_enabled_ui(!busy, |ui| { - ui.checkbox( - &mut confirmed, - tr("I understand that shared progress will be reset"), - ); - }); - if let Some(state) = &mut self.shared_reset { - state.confirmed = confirmed; - } - let mut cancel = false; - let mut confirm = false; - ui.horizontal(|ui| { - cancel = ui - .add_enabled(!busy, egui::Button::new(tr("Cancel"))) - .clicked(); - confirm = ui - .add_enabled( - confirmed && !busy && impact.reset_count > 0, - egui::Button::new(tr("Reset shared learning data")), - ) - .clicked(); - if busy { - ui.spinner(); - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); + .map(|r| (r.id.clone(), r.name.clone())) + .collect(); + let name_of = |id: &RepertoireId| names.get(id).cloned().unwrap_or_default(); + let mut keep = true; + let mut result = None; + let enter = ctx.input(|input| input.key_pressed(Key::Enter)); + let mut dialog = dialog; + let modal = egui::Modal::new(egui::Id::new("opening_dialog")).show(ctx, |ui| { + ui.set_width(DIALOG_W); + match &mut dialog { + Dialog::Import(import) => { + result = import_dialog(ui, import, name_of, enter); + } + Dialog::New { name, side, error } => { + ui.heading(tr("New repertoire")); + ui.add_space(8.0); + name_field(ui, name, error, false); + side_choice(ui, side); + ui.add_space(4.0); + ui.add( + egui::Label::new(RichText::new(tr("Moves are added from a PGN file or with “Add to repertoire…” in any game.")).weak()) + .wrap(), + ); + result = dialog_buttons(ui, tr("Create"), true, None, enter); + } + Dialog::Rename { + name, + error, + select_all, + .. + } => { + ui.heading(tr("Rename repertoire")); + ui.add_space(8.0); + name_field(ui, name, error, std::mem::take(select_all)); + result = dialog_buttons(ui, tr("Save"), true, None, enter); + } + Dialog::Color { id, to, count, .. } => { + let name = name_of(id); + ui.heading(match to { + LearningSide::Black => trf("Play “{name}” as Black?", &[("name", &name)]), + LearningSide::White => trf("Play “{name}” as White?", &[("name", &name)]), + }); + ui.add_space(8.0); + let count = count.map_or_else(|| "…".to_owned(), |n| n.to_string()); + ui.add( + egui::Label::new(match to { + LearningSide::Black => trf( + "You will be asked Black's moves: {y}. Progress for White is kept and comes back if you switch again.", + &[("y", &count)], + ), + LearningSide::White => trf( + "You will be asked White's moves: {y}. Progress for Black is kept and comes back if you switch again.", + &[("y", &count)], + ), + }) + .wrap(), + ); + result = dialog_buttons(ui, tr("Switch"), true, None, enter); + } + Dialog::Reset { id, impact, busy, .. } => { + let name = name_of(id); + ui.heading(trf("Reset progress of “{name}”?", &[("name", &name)])); + ui.add_space(8.0); + match impact { + None => { + ui.label(RichText::new(tr("Counting moves…")).weak()); + } + Some((impact, keys)) => { + ui.add( + egui::Label::new(trf( + "All {y} moves of this repertoire become new again: answers and review dates are erased.", + &[("y", &keys.len())], + )) + .wrap(), + ); + ui.add( + egui::Label::new(tr("The moves themselves and PGN files do not change.")) + .wrap(), + ); + let others: Vec<_> = impact + .affected_repertoires + .iter() + .filter(|other| other.id != *id) + .collect(); + if impact.shared_count > 0 && !others.is_empty() { + let names = others + .iter() + .map(|other| other.name.as_str()) + .collect::>() + .join(", "); + ui.add( + egui::Label::new( + RichText::new(trf( + "{s} of these moves are also in: {names}. They become new there too.", + &[("s", &impact.shared_count), ("names", &names)], + )) + .color(ui.visuals().warn_fg_color), + ) + .wrap(), + ); + } + } + } + let ready = impact.as_ref().is_some_and(|(_, keys)| !keys.is_empty()) && !*busy; + result = dialog_buttons(ui, tr("Reset"), ready, Some(()), enter); + } + Dialog::Delete { id } => { + let name = name_of(id); + ui.heading(trf("Delete “{name}”?", &[("name", &name)])); + ui.add_space(8.0); + ui.add( + egui::Label::new(tr( + "The repertoire leaves this list. PGN files on disk do not change.", + )) + .wrap(), + ); + ui.add( + egui::Label::new(tr( + "Your answers are kept: import the same PGN again and the progress returns.", + )) + .wrap(), + ); + result = dialog_buttons(ui, tr("Delete"), true, Some(()), enter); + } } }); - if cancel { - self.cancel_shared_reset(); + if modal.should_close() && result.is_none() { + result = Some(false); } - if confirm { - self.confirm_shared_reset(); + match result { + Some(false) => { + if let Dialog::Import(import) = &dialog { + import.cancel.store(true, Ordering::Relaxed); + } + keep = false; + } + Some(true) => { + self.dialog = Some(dialog); + self.confirm_dialog(settings, actions); + return; + } + None => {} + } + if keep { + self.dialog = Some(dialog); } } - fn show_add(&mut self, ui: &mut Ui, actions: &mut Vec) { + + fn confirm_dialog(&mut self, settings: &mut Settings, actions: &mut Vec) { + match self.dialog.take() { + Some(Dialog::Import(import)) => { + self.dialog = Some(Dialog::Import(import)); + self.confirm_import(settings); + } + Some(Dialog::New { name, side, .. }) => match self.checked_name(&name, None) { + Ok(name) => { + let mut library = self.library.clone(); + match library.create_empty(name.clone()) { + Ok(id) => { + if self.persist(library) { + layout::set_side(settings, &id, side); + actions.push(RepertoireAction::SettingsChanged); + self.select(id); + } else { + self.dialog = Some(Dialog::New { + name, + side, + error: None, + }); + } + } + Err(error) => { + self.dialog = Some(Dialog::New { + name, + side, + error: Some(error.to_string()), + }) + } + } + } + Err(error) => { + self.dialog = Some(Dialog::New { + name, + side, + error: Some(error), + }) + } + }, + Some(Dialog::Rename { id, name, .. }) => match self.checked_name(&name, Some(&id)) { + Ok(checked) => { + let mut library = self.library.clone(); + match library.rename(&id, checked) { + Ok(()) => { + if !self.persist(library) { + self.dialog = Some(Dialog::Rename { + id, + name, + error: None, + select_all: false, + }); + } + } + Err(error) => { + self.dialog = Some(Dialog::Rename { + id, + name, + error: Some(error.to_string()), + select_all: false, + }) + } + } + } + Err(error) => { + self.dialog = Some(Dialog::Rename { + id, + name, + error: Some(error), + select_all: false, + }) + } + }, + Some(Dialog::Color { id, to, .. }) => { + layout::set_side(settings, &id, to); + actions.push(RepertoireAction::SettingsChanged); + } + Some(dialog @ Dialog::Reset { .. }) => { + self.dialog = Some(dialog); + self.confirm_reset(); + } + Some(dialog @ Dialog::Delete { .. }) => { + self.dialog = Some(dialog); + self.delete_selected(); + } + None => {} + } + } + + fn show_add( + &mut self, + ui: &mut Ui, + settings: &mut Settings, + actions: &mut Vec, + ) { let Some(mut add) = self.add.take() else { return; }; let mut cancel = false; let mut commit = false; + let start = fen4(add.source.start().position()); + let candidates: Vec<(RepertoireId, String)> = self + .library + .repertoires + .iter() + .filter(|r| { + self.index.contains_key(&r.id) && fen4(r.game().start().position()) == start + }) + .map(|r| (r.id.clone(), r.name.clone())) + .collect(); egui::Modal::new(egui::Id::new("add_to_repertoire")).show(ui.ctx(), |ui| { ui.set_max_width(450.0); ui.heading(tr("Add to repertoire")); ui.label(prefix_label(&add.source, add.at)); - let start = fen4(add.source.start().position()); - for r in &self.library.repertoires { - if self - .trees - .get(&r.id) - .is_some_and(|tree| fen4(tree.game().start().position()) == start) - { - ui.radio_value(&mut add.selected, Some(r.id.clone()), &r.name); - } + for (id, name) in &candidates { + ui.radio_value(&mut add.selected, Some(id.clone()), name); } ui.radio_value(&mut add.selected, None, tr("New repertoire")); if add.selected.is_none() { @@ -2005,17 +2060,17 @@ impl RepertoireUi { .char_limit(120) .hint_text(tr("Name")), ); + side_choice(ui, &mut add.side); } ui.horizontal(|ui| { cancel = ui.button(tr("Cancel")).clicked(); - commit = ui - .add_enabled(!self.indexing, egui::Button::new(tr("Add"))) - .clicked(); + commit = ui.button(tr("Add")).clicked(); }); }); if commit { let result = (|| { let mut library = self.library.clone(); + let new = add.selected.is_none(); let id = if let Some(id) = &add.selected { id.clone() } else { @@ -2031,55 +2086,63 @@ impl RepertoireUi { .repertoire(&id) .map(|r| r.name.clone()) .unwrap_or_default(); - Ok::<_, String>((library, id, name, report)) + Ok::<_, String>((library, id, name, report, new)) })(); match result { - Ok((library, id, name, report)) if self.persist(library.clone()) => { + Ok((library, id, name, report, new)) if self.persist(library.clone()) => { + if new { + layout::set_side(settings, &id, add.side); + actions.push(RepertoireAction::SettingsChanged); + } actions.push(RepertoireAction::Added { id, name, report }); return; } Ok(_) => {} - Err(e) => self.error = Some(e), + Err(error) => self.show_message(error, true), } } if !cancel { self.add = Some(add); } } + pub fn debug_import(&mut self, path: PathBuf) { - self.import_path(path, None, None); + let target = + std::env::var_os("CP_REPERTOIRE_IMPORT_INTO").and_then(|_| self.selected.clone()); + self.import_path(path, target); } - pub fn debug_confirm_import(&mut self, settings: &Settings) -> bool { - self.confirm_import(settings) + + /// `CP_REPERTOIRE_CONFIRM_IMPORT`: confirmed in `poll`, where the chosen colour can + /// be written to the settings. + pub fn debug_confirm_import(&mut self, _settings: &Settings) -> bool { + false } + pub fn debug_export(&mut self) { self.export(None); } + pub fn debug_rename(&mut self, name: String, _settings: &Settings) -> bool { let Some(id) = self.selected.clone() else { return false; }; let mut library = self.library.clone(); - if let Err(e) = library.rename(&id, name) { - self.error = Some(e.to_string()); + if let Err(error) = library.rename(&id, name) { + self.show_message(error.to_string(), true); return false; } self.persist(library) } + pub fn debug_delete(&mut self, _settings: &Settings) -> bool { let Some(id) = self.selected.clone() else { return false; }; - let mut library = self.library.clone(); - if library.delete(&id).is_err() { - return false; - } - if !self.persist(library) { - return false; - } - self.selected = None; - true + self.dialog = Some(Dialog::Delete { id }); + self.delete_selected(); + self.dialog.is_none() } + pub fn debug_add_from_game(&mut self, source: Game, at: NodeId, title: String, target: String) { self.open_add_from_game(source, at, title); if let Some(add) = &mut self.add { @@ -2087,55 +2150,535 @@ impl RepertoireUi { add.selected = None; } } + + /// QA hooks (docs/qa/opening-trainer-v2-devhooks.md): `CP_REPERTOIRE=`, after + /// `CP_REPERTOIRE_SELECT=`. pub fn debug_open(&mut self, what: &str, settings: &mut Settings) { - if let Some(id) = self.selected.clone() { - self.select(id, settings); - } - match what { - "library" | "detail" => {} - "dashboard" => self.open_dashboard(), - "editor" => self.open_editor(), - "white" | "black" => { - if self.selected.is_none() || self.cancel.is_some() { - self.debug_start = Some(what.to_owned()); - return; - } - self.side = if what == "black" { - LearningSide::Black - } else { - LearningSide::White - }; - if self.selected_aggregate().is_none() { - self.debug_start = Some(what.to_owned()); - return; - } - self.start(settings); + if let Ok(name) = std::env::var("CP_REPERTOIRE_SELECT") { + let name = name.to_lowercase(); + if let Some(id) = self + .library + .repertoires + .iter() + .find(|r| r.name.to_lowercase().contains(&name)) + .map(|r| r.id.clone()) + { + self.select(id); } + } + let ready = self + .selected + .as_ref() + .is_some_and(|id| self.stats.contains_key(id) && self.index.contains_key(id)); + let needs_stats = !matches!(what, "library" | "detail" | "new" | "message"); + if needs_stats && !ready && !self.library.repertoires.is_empty() { + self.debug_start = Some(what.to_owned()); + return; + } + let ctx = egui::Context::default(); + match what { + "white" | "black" => { + if let Some(id) = self.selected.clone() { + let side = if what == "black" { + LearningSide::Black + } else { + LearningSide::White + }; + if layout::side_of(settings, &id) != side { + layout::set_side(settings, &id, side); + self.debug_start = Some("train".to_owned()); + return; + } + self.start(SessionKind::Daily, settings); + } + } + "train" => self.start(SessionKind::Daily, settings), + "main" => self.main_action(&ctx, settings), + "review" => self.start(SessionKind::ReviewAll, settings), + "lines" => { + let path = std::env::var("CP_REPERTOIRE_LINE") + .ok() + .map(|path| path.split_whitespace().map(str::to_owned).collect()); + self.open_lines(settings, path); + } + "branch" => { + let through: Vec = std::env::var("CP_REPERTOIRE_LINE") + .unwrap_or_default() + .split_whitespace() + .map(str::to_owned) + .collect(); + let label = through.join(" "); + self.start(SessionKind::Branch { through, label }, settings); + } + "menu" => self.debug_menu = true, + "new" => { + self.dialog = Some(Dialog::New { + name: std::env::var("CP_REPERTOIRE_NAME").unwrap_or_default(), + side: LearningSide::White, + error: None, + }); + if std::env::var_os("CP_REPERTOIRE_NAME").is_some() { + self.confirm_dialog(settings, &mut Vec::new()); + } + } + "rename" => self.menu_item(MenuItem::Rename, &ctx, settings), + "color" => self.open_color_dialog(settings), + "reset" => self.open_reset_dialog(settings), + "delete" => self.menu_item(MenuItem::Delete, &ctx, settings), + "message" => self.show_message( + trf( + "Could not save: {e}", + &[("e", &"Permission denied (os error 13)")], + ), + true, + ), _ => {} } } + pub fn debug_moves(&mut self, moves: &str) { - if let Some(t) = &mut self.training { - t.debug_moves(moves); + if let Screen::Session(session) = &mut self.screen { + session.debug_moves(moves); } else { self.debug_pending_moves = Some(moves.to_owned()); } } + pub fn debug_hint(&mut self) { - if let Some(t) = &mut self.training { - t.debug_hint(); + if let Screen::Session(session) = &mut self.screen { + session.debug_hint(); } } } impl Drop for RepertoireUi { fn drop(&mut self) { - if let Some(cancel) = &self.cancel { - cancel.store(true, Ordering::Relaxed); + if let Some(Dialog::Import(import)) = &self.dialog { + import.cancel.store(true, Ordering::Relaxed); } } } +fn next_job() -> u64 { + NEXT_JOB.fetch_add(1, Ordering::Relaxed) +} + +/// `CP_REPERTOIRE_SLOW=`: a session takes this long to prepare (to see «Preparing…»). +fn debug_slow() -> Option { + std::env::var("CP_REPERTOIRE_SLOW") + .ok()? + .parse() + .ok() + .map(Duration::from_millis) +} + +fn row_stats( + library: &Library, + learning: &LearningData, + id: &RepertoireId, + side: LearningSide, + today: i64, +) -> Result { + let scope = StatsScope::for_repertoire(id.clone(), side, today); + let scoped = aggregate_scope(library, learning, &scope, &SrsSettings::default()) + .map_err(|error| error.to_string())?; + let summary = &scoped.summary; + let next = summary.next_due_at.map(|at| { + let day_end = end_of_day(at); + let count = scoped + .items + .iter() + .filter(|item| { + item.introduced + && item + .next_review_at + .is_some_and(|next| next > today && next <= day_end) + }) + .count(); + (at, count) + }); + Ok(RowStats { + total: summary.total, + due: summary.due, + unseen: summary.unseen, + learning: summary.learning, + learnt: summary.learnt, + next, + }) +} + +fn end_of_day(at: i64) -> i64 { + use chrono::{Local, TimeZone}; + Local + .timestamp_opt(at, 0) + .single() + .and_then(|time| time.date_naive().succ_opt()) + .and_then(|day| day.and_hms_opt(0, 0, 0)) + .and_then(|midnight| Local.from_local_datetime(&midnight).earliest()) + .map_or(at, |midnight| midnight.timestamp() - 1) +} + +/// Lines 2 and 4 of the card. +fn card_texts(state: &CardState, side: LearningSide) -> (String, String) { + match state { + CardState::Review { due, new } => { + let today = if *new > 0 { + trf("Today: {n} to review · {m} new", &[("n", due), ("m", new)]) + } else { + trf("Today: {n} to review", &[("n", due)]) + }; + let seconds = (due + new) * SECONDS_PER_MOVE; + let note = if seconds >= 60 { + trf("About {t} min", &[("t", &seconds.div_ceil(60))]) + } else { + String::new() + }; + (today, note) + } + CardState::OnlyNew { new } => ( + trf("Today: {m} new moves", &[("m", new)]), + tr("Nothing to review today").to_owned(), + ), + CardState::Done { next } => ( + tr("Done for today").to_owned(), + next.map(|(at, count)| { + trf( + "Next review: {when} · {n} moves", + &[("when", &layout::when(at, layout::now())), ("n", &count)], + ) + }) + .unwrap_or_default(), + ), + CardState::Empty => ( + tr("No moves yet").to_owned(), + tr("Add a PGN, or use “Add to repertoire…” in any game").to_owned(), + ), + CardState::OtherColor => ( + match side { + LearningSide::White => tr("No moves for White here"), + LearningSide::Black => tr("No moves for Black here"), + } + .to_owned(), + tr("This PGN may be a repertoire for the other colour").to_owned(), + ), + CardState::Counting => (tr("Counting moves…").to_owned(), String::new()), + CardState::Failed(error) => (tr("Cannot read this repertoire").to_owned(), error.clone()), + } +} + +/// The card's main button: label, enabled, what it does. +fn main_button(state: &CardState, side: LearningSide) -> (String, bool, Option) { + match state { + CardState::Review { .. } => (tr("Train").to_owned(), true, Some(MenuItem::Train)), + CardState::OnlyNew { new } => ( + trf("Learn {m} new", &[("m", new)]), + true, + Some(MenuItem::Train), + ), + CardState::Done { .. } => ( + tr("Review all lines").to_owned(), + true, + Some(MenuItem::ReviewAll), + ), + CardState::Empty => (tr("Add PGN…").to_owned(), true, Some(MenuItem::AddPgn)), + CardState::OtherColor => ( + match side { + LearningSide::White => tr("Play as Black"), + LearningSide::Black => tr("Play as White"), + } + .to_owned(), + true, + Some(MenuItem::SwitchColor), + ), + CardState::Counting => (tr("Train").to_owned(), false, None), + CardState::Failed(_) => (tr("Try again").to_owned(), true, Some(MenuItem::Train)), + } +} + +/// Row 3 of the card: learnt, in progress, the rest. +fn progress(ui: &mut Ui, stats: Option<&RowStats>) { + let width = ui.available_width(); + let (bar, _) = ui.allocate_exact_size(vec2(width, 8.0), egui::Sense::hover()); + let painter = ui.painter(); + painter.rect_filled(bar, 2.0, ui.visuals().extreme_bg_color); + if let Some(stats) = stats.filter(|stats| stats.total > 0) { + let total = stats.total as f32; + let learnt = bar.width() * stats.learnt as f32 / total; + let learning = bar.width() * stats.learning as f32 / total; + let fill = ui.visuals().selection.bg_fill; + painter.rect_filled( + egui::Rect::from_min_size(bar.min, vec2(learnt, bar.height())), + 2.0, + fill, + ); + painter.rect_filled( + egui::Rect::from_min_size(bar.min + vec2(learnt, 0.0), vec2(learning, bar.height())), + 0.0, + fill.gamma_multiply(0.45), + ); + } + ui.add_space(-2.0); + ui.horizontal(|ui| { + ui.set_height(20.0); + let (learnt, total, learning) = stats.map_or((0, 0, 0), |stats| { + (stats.learnt, stats.total, stats.learning) + }); + if stats.is_some() { + layout::line( + ui, + trf("Learned {x} of {y} moves", &[("x", &learnt), ("y", &total)]), + ); + } + if learning > 0 { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(trf("{k} in progress", &[("k", &learning)])).weak()); + }); + } + }); +} + +fn menu_items( + ui: &mut Ui, + side: LearningSide, + stats: Option<&Result>, +) -> Option { + let has_moves = matches!(stats, Some(Ok(stats)) if stats.total > 0); + let mut chosen = None; + let mut item = |ui: &mut Ui, enabled: bool, label: &str, value: MenuItem| { + if ui.add_enabled(enabled, egui::Button::new(label)).clicked() { + chosen = Some(value); + ui.close(); + } + }; + item(ui, has_moves, tr("Train"), MenuItem::Train); + item(ui, has_moves, tr("Review all lines"), MenuItem::ReviewAll); + item(ui, true, tr("Lines…"), MenuItem::Lines); + ui.separator(); + item(ui, true, tr("Rename…"), MenuItem::Rename); + item( + ui, + true, + match side { + LearningSide::White => tr("Play as Black"), + LearningSide::Black => tr("Play as White"), + }, + MenuItem::SwitchColor, + ); + item( + ui, + true, + tr("Add PGN to this repertoire…"), + MenuItem::AddPgn, + ); + item(ui, true, tr("Export PGN…"), MenuItem::Export); + ui.separator(); + item(ui, has_moves, tr("Reset progress…"), MenuItem::Reset); + item(ui, true, tr("Delete…"), MenuItem::Delete); + chosen +} + +/// The dialog's buttons on the right: «Cancel», then the main one. `danger`: both are +/// plain and Enter means «Cancel». Returns `Some(true)` to confirm, `Some(false)` to +/// cancel. +fn dialog_buttons( + ui: &mut Ui, + label: &str, + enabled: bool, + danger: Option<()>, + enter: bool, +) -> Option { + let mut result = None; + ui.add_space(12.0); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let main = if danger.is_some() { + ui.add_enabled(enabled, egui::Button::new(label).min_size(vec2(0.0, 30.0))) + } else { + ui.add_enabled_ui(enabled, |ui| crate::widgets::primary(ui, label)) + .inner + }; + if main.clicked() { + result = Some(true); + } + let cancel = ui.add(egui::Button::new(tr("Cancel")).min_size(vec2(0.0, 30.0))); + if danger.is_some() && !ui.ctx().memory(|m| m.focused().is_some()) { + cancel.request_focus(); + } + if cancel.clicked() { + result = Some(false); + } + }); + if result.is_none() && enter { + if danger.is_some() { + result = Some(false); + } else if enabled { + result = Some(true); + } + } + result +} + +fn name_field(ui: &mut Ui, name: &mut String, error: &mut Option, select_all: bool) { + ui.label(RichText::new(tr("Name")).strong().size(15.0)); + let output = egui::TextEdit::singleline(name) + .char_limit(120) + .desired_width(f32::INFINITY) + .show(ui); + if select_all { + let mut state = output.state.clone(); + state + .cursor + .set_char_range(Some(egui::text::CCursorRange::two( + egui::text::CCursor::new(0), + egui::text::CCursor::new(name.chars().count()), + ))); + state.store(ui.ctx(), output.response.id); + output.response.request_focus(); + } + if output.response.changed() { + *error = None; + } + // The place of the error is kept: the dialog does not grow when it appears. + ui.allocate_ui(vec2(ui.available_width(), 18.0), |ui| { + if let Some(error) = error.as_deref() { + ui.label(RichText::new(error).color(ui.visuals().warn_fg_color)); + } + }); +} + +fn side_choice(ui: &mut Ui, side: &mut LearningSide) { + ui.add_space(4.0); + ui.label(RichText::new(tr("You play")).strong().size(15.0)); + ui.add_space(2.0); + ui.horizontal(|ui| { + for (value, label) in [ + (LearningSide::White, tr("♔ White")), + (LearningSide::Black, tr("♚ Black")), + ] { + if ui + .add_sized( + [222.0, 34.0], + egui::Button::selectable(*side == value, RichText::new(label).size(14.0)) + .frame_when_inactive(true), + ) + .clicked() + { + *side = value; + } + } + }); +} + +fn import_dialog( + ui: &mut Ui, + dialog: &mut ImportDialog, + name_of: impl Fn(&RepertoireId) -> String, + enter: bool, +) -> Option { + let adding = dialog.target.is_some(); + ui.heading(match &dialog.target { + Some(id) => trf("Add PGN to “{name}”", &[("name", &name_of(id))]), + None => tr("Import PGN").to_owned(), + }); + ui.add_space(8.0); + if !adding { + name_field(ui, &mut dialog.name, &mut dialog.error, false); + side_choice(ui, &mut dialog.side); + ui.label(RichText::new(tr("Chosen from the PGN — check it")).weak()); + ui.add_space(6.0); + } + let mut enabled = false; + let mut hover = None; + match &dialog.preview { + None => { + ui.label(RichText::new(tr("Reading the file…")).weak()); + ui.ctx().request_repaint_after(Duration::from_millis(50)); + } + Some(preview) => { + if adding { + let lines = preview.lines.saturating_sub(preview.lines_before); + if preview.report.added_nodes == 0 { + ui.label(RichText::new(tr("Nothing new in this file")).weak()); + } else { + ui.label( + RichText::new(trf( + "{m} new moves · {v} new lines", + &[("m", &preview.report.added_nodes), ("v", &lines)], + )) + .weak(), + ); + enabled = true; + } + } else { + let own = preview.own(dialog.side); + ui.label( + RichText::new(trf( + "{g} games · {v} lines · {y} your moves", + &[("g", &preview.games), ("v", &preview.lines), ("y", &own)], + )) + .weak(), + ); + enabled = own > 0 && !dialog.name.trim().is_empty(); + if own == 0 { + hover = Some(tr("No moves for this colour")); + } + } + for warning in preview.warnings.iter().take(WARNING_ROWS) { + layout::line(ui, RichText::new(warning).color(ui.visuals().warn_fg_color)); + } + if preview.warnings.len() > WARNING_ROWS { + ui.label( + RichText::new(trf( + "and {k} more", + &[("k", &(preview.warnings.len() - WARNING_ROWS))], + )) + .color(ui.visuals().warn_fg_color), + ); + } + if adding && let Some(error) = &dialog.error { + ui.label(RichText::new(error).color(ui.visuals().warn_fg_color)); + } + } + } + let label = if adding { tr("Add") } else { tr("Import") }; + let result = dialog_buttons(ui, label, enabled, None, enter); + if let Some(hover) = hover { + ui.label(RichText::new(hover).weak()); + } + result +} + +fn text_width(ui: &Ui, text: &str, size: f32) -> f32 { + ui.painter() + .layout_no_wrap( + text.to_owned(), + egui::FontId::proportional(size), + egui::Color32::WHITE, + ) + .size() + .x +} + +/// The colour whose moves a PGN repertoire gives: the side with fewer positions where +/// the PGN has several moves (one answer to many replies). White on a tie. +fn suggested_side(game: &Game) -> LearningSide { + let mut branching = [0usize; 2]; + let mut stack = vec![NodeId::ROOT]; + while let Some(node) = stack.pop() { + let children = game.children(node); + if children.len() > 1 + && let Some(position) = game.position(node) + { + branching[usize::from(position.turn() == Color::Black)] += 1; + } + stack.extend(children.iter().copied()); + } + if branching[1] < branching[0] { + LearningSide::Black + } else { + LearningSide::White + } +} + fn read_import( path: &Path, target: Option, @@ -2148,185 +2691,115 @@ fn read_import( if db.is_empty() { return Err(tr("No games").to_owned()); } + let base_revision = library.revision; let stem = path .file_stem() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_else(|| tr("New repertoire").to_owned()); - let mut name = stem.clone(); - let mut suffix = 2; - while library - .repertoires - .iter() - .any(|r| r.name.to_lowercase() == name.to_lowercase()) - { - name = format!("{stem} ({suffix})"); - suffix += 1; - } + let mut warnings = Vec::new(); let mut id = target.clone(); let mut report = MergeReport::default(); + let mut event = None; + let lines_before = target + .as_ref() + .and_then(|id| library.repertoire(id)) + .map_or(0, |r| layout::lines(&r.game(), |_| false).len()); for index in 0..db.len() { if cancel.load(Ordering::Relaxed) { - return Err(tr("Cancelled").to_owned()); + return Err(String::new()); } - let parsed = db - .load_game(index) - .ok_or_else(|| tr("No games").to_owned())?; + let Some(parsed) = db.load_game(index) else { + warnings.push(trf("Game {n}: could not be read", &[("n", &(index + 1))])); + continue; + }; if let Some(d) = parsed .diagnostics .iter() .find(|d| d.severity == Severity::Error) { - return Err(format!("PGN #{}: {}", index + 1, d.message)); + warnings.push(trf( + "Game {n}: {message}", + &[("n", &(index + 1)), ("message", &d.message)], + )); + } + if event.is_none() { + event = parsed + .game + .tag("Event") + .map(|value| value.trim().to_owned()) + .filter(|value| !value.is_empty() && value != "?"); + } + if parsed.game.children(NodeId::ROOT).is_empty() { + warnings.push(trf("Game {n} has no moves", &[("n", &(index + 1))])); + continue; } let current = match &id { Some(id) => id.clone(), None => { let new_id = library - .create(name.clone(), &Game::from_start(parsed.game.start().clone())) + .create(stem.clone(), &Game::from_start(parsed.game.start().clone())) .map_err(|e| e.to_string())?; id = Some(new_id.clone()); new_id } }; - let added = library - .add_game(¤t, &parsed.game) - .map_err(|e| format!("PGN #{}: {e}", index + 1))?; - report.added_nodes += added.added_nodes; - report.merged_nodes += added.merged_nodes; - report.annotation_changes += added.annotation_changes; + match library.add_game(¤t, &parsed.game) { + Ok(added) => { + report.added_nodes += added.added_nodes; + report.merged_nodes += added.merged_nodes; + report.annotation_changes += added.annotation_changes; + } + Err(error) => warnings.push(trf( + "Game {n}: {message}", + &[("n", &(index + 1)), ("message", &error.to_string())], + )), + } + } + let id = id.ok_or_else(|| tr("No games with moves in this file").to_owned())?; + let game = library + .repertoire(&id) + .map(|r| r.game()) + .ok_or_else(|| tr("No games").to_owned())?; + let own = [LearningSide::White, LearningSide::Black].map(|side| { + active_learning_keys(&library, &StatsScope::for_repertoire(id.clone(), side, 0)) + .map_or(0, |keys| keys.len()) + }); + let mut name = event.unwrap_or(stem); + let base = name.clone(); + let mut suffix = 2; + while library + .repertoires + .iter() + .any(|r| r.id != id && r.name.to_lowercase() == name.to_lowercase()) + { + name = format!("{base} ({suffix})"); + suffix += 1; } - let id = id.ok_or_else(|| tr("No games").to_owned())?; Ok(ImportPreview { + lines: layout::lines(&game, |_| false).len(), + lines_before, + suggested: suggested_side(&game), library, id, - records: db.len(), + base_revision, + games: db.len(), + own, + default_name: name, + warnings, report, - name, - target, }) } -fn pgn_route_count(tree: &RepertoireTree) -> usize { - let mut count = 0usize; - let _ = tree.visit_source_paths(&TrainingScope::whole(), |_| { - count = count.saturating_add(1); - std::ops::ControlFlow::Continue(()) - }); - count -} -fn start_kind(summary: &LearningAggregate) -> StartKind { - if summary.total == 0 { - StartKind::Unavailable - } else if summary.due > 0 { - StartKind::Review - } else if summary.unseen > 0 { - StartKind::IntroduceNew - } else { - StartKind::Unavailable - } -} -fn mode_start_kind(queue: QueueMode, summary: &LearningAggregate) -> StartKind { - match queue { - QueueMode::SpacedRepetition => start_kind(summary), - QueueMode::ReviewInOrder | QueueMode::LeastRecent if summary.total > 0 => StartKind::Review, - QueueMode::Practice | QueueMode::ReviewInOrder | QueueMode::LeastRecent => { - StartKind::Unavailable - } - } -} -fn queue_mode_label(queue: QueueMode) -> &'static str { - tr(match queue { - QueueMode::Practice | QueueMode::SpacedRepetition => "On schedule", - QueueMode::ReviewInOrder => "Review in order", - QueueMode::LeastRecent => "Least recent and unseen first", - }) -} -fn learning_priority_label(priority: LearningPriority) -> &'static str { - tr(match priority { - LearningPriority::DepthFirst => "Depth first", - LearningPriority::BreadthOverDepth => "Breadth over depth", - LearningPriority::MainLinesFirst => "Main lines first", - LearningPriority::CommonPositionsFirst => "Common positions first", - }) -} -fn training_mode(side: LearningSide) -> TrainingMode { - match side { - LearningSide::White => TrainingMode::White, - LearningSide::Black => TrainingMode::Black, - } -} -fn learning_side_label(side: LearningSide) -> &'static str { - tr(match side { - LearningSide::White => "White", - LearningSide::Black => "Black", - }) -} -fn opening_labels(tree: &RepertoireTree) -> Vec { - let mut labels = BTreeSet::new(); - let start = tree.game().start().position(); - let _ = tree.visit_source_paths(&TrainingScope::whole(), |moves| { - let mut position = start.clone(); - let mut keys = Vec::with_capacity(moves.len() + 1); - keys.push(chess_openings::key(&position)); - for uci in moves { - let Some(mv) = uci - .parse::() - .ok() - .and_then(|uci| uci.to_move(&position).ok()) - else { - return std::ops::ControlFlow::Continue(()); - }; - position.play_unchecked(mv); - keys.push(chess_openings::key(&position)); - } - if let Some((_, id)) = chess_openings::deepest(&keys) { - let opening = chess_openings::get(id); - labels.insert(OpeningLabel { - eco: opening.eco.clone(), - name: opening.name.clone(), - }); - } - std::ops::ControlFlow::Continue(()) - }); - labels.into_iter().collect() -} -fn table_text_line(ui: &mut Ui, text: RichText, height: f32) -> egui::Response { - ui.allocate_ui_with_layout( - egui::vec2(ui.available_width(), height), - egui::Layout::left_to_right(egui::Align::Center), - |ui| { - ui.add( - egui::Label::new(text) - .selectable(false) - .truncate() - .halign(egui::Align::Min), - ) - }, - ) - .inner +fn load_library(store: &LibraryStore) -> Result { + let mut library = store.load().map_err(|error| error.to_string())?; + // The depth limit of 2.2 is not a user's choice: trained lines go to their ends. + // The PGN does not change. + for repertoire in &mut library.repertoires { + repertoire.set_max_plies(u32::MAX); + } + Ok(library) } -fn count_cell(ui: &mut Ui, count: Option) { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(count) = count { - ui.label(count.to_string()); - } else { - ui.spinner(); - ui.ctx() - .request_repaint_after(std::time::Duration::from_millis(100)); - } - }); -} -fn now() -> i64 { - web_time::SystemTime::now() - .duration_since(web_time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs() as i64) -} -fn load_library(store: &LibraryStore) -> Result { - store.load().map_err(|error| LibraryLoadError { - message: error.to_string(), - }) -} fn prefix_label(game: &Game, at: NodeId) -> String { game.path(at) .into_iter() @@ -2336,6 +2809,7 @@ fn prefix_label(game: &Game, at: NodeId) -> String { .collect::>() .join(" ") } + fn stores() -> (LibraryStore, LearningStore) { let legacy = std::env::var_os("CP_TRAINING_FILE") .map(PathBuf::from) diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index 3c1a32a..3e0542a 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -1,1727 +1,525 @@ -use super::*; use std::sync::atomic::AtomicU64; -use std::time::Duration; -static NEXT_TEST: AtomicU64 = AtomicU64::new(0); +use super::*; +use trainer::repertoire::{QueueMode, TrainingMode, active_learning_memberships}; -struct Fixture { - ui: RepertoireUi, - settings: Settings, - dir: PathBuf, - id: RepertoireId, -} +static NEXT_DIR: AtomicU64 = AtomicU64::new(1); +const DAY: i64 = 24 * 60 * 60; -impl Fixture { - fn new() -> Self { - let dir = std::env::temp_dir().join(format!( - "cp-repertoire-ui-{}-{}", +struct TestDir(PathBuf); + +impl TestDir { + fn new(name: &str) -> Self { + let path = std::env::temp_dir().join(format!( + "cp-repertoire-ui-{}-{}-{name}", std::process::id(), - NEXT_TEST.fetch_add(1, Ordering::Relaxed) + NEXT_DIR.fetch_add(1, Ordering::Relaxed) )); - let library_store = LibraryStore::new(dir.join("library.json")); - let mut library = Library::default(); - let id = library - .create("Async opening", &chess_core::parse_str("1. e4 e5 *").game) - .unwrap(); - library_store.save(&mut library).unwrap(); - let mut ui = - RepertoireUi::with_stores(library_store, LearningStore::new(dir.join("learning.json"))); - let event = ui.rx.recv_timeout(Duration::from_secs(5)).unwrap(); - ui.tx.send(event).unwrap(); - let mut settings = Settings::default(); - ui.poll(&mut settings); - assert!(!ui.indexing); - ui.select(id.clone(), &settings); - Self { - ui, - settings, - dir, - id, - } + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).unwrap(); + Self(path) } - fn completed_job(&self) -> Event { - self.ui.rx.recv_timeout(Duration::from_secs(5)).unwrap() + fn stores(&self) -> (LibraryStore, LearningStore) { + ( + LibraryStore::new(self.0.join("repertoires.json")), + LearningStore::new(self.0.join("repertoire-training.json")), + ) } - fn deliver(&mut self, event: Event) { - self.ui.tx.send(event).unwrap(); - self.ui.poll(&mut self.settings); - } - - fn aggregate(&mut self) -> ScopedLearningAggregate { - for _ in 0..4 { - if self.ui.selected_aggregate().is_some() { - break; - } - let event = self.completed_job(); - self.deliver(event); - } - self.ui.selected_aggregate().cloned().expect("aggregate") - } - - fn start(&mut self) { - self.ui.side = LearningSide::White; - self.aggregate(); - self.ui.start(&mut self.settings); - assert!(self.ui.preparing); + fn ui(&self) -> RepertoireUi { + let (library, learning) = self.stores(); + RepertoireUi::with_stores(library, learning) } } -impl Drop for Fixture { +impl Drop for TestDir { fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.dir); + let _ = std::fs::remove_dir_all(&self.0); } } -fn render_library(f: &mut Fixture, ctx: &egui::Context, width: f32, time: f64) { +fn save_library(dir: &TestDir, repertoires: &[(&str, &str)]) -> Vec { + let mut library = Library::default(); + let ids = repertoires + .iter() + .map(|(name, pgn)| { + library + .create(*name, &chess_core::parse_str(pgn).game) + .unwrap() + }) + .collect(); + dir.stores().0.save(&mut library).unwrap(); + ids +} + +/// Frames until the background index and counts are in. +fn settle(ui: &mut RepertoireUi, ctx: &egui::Context, settings: &mut Settings, size: egui::Vec2) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + frame(ui, ctx, settings, size, Vec::new()); + let ready = ui.preparing.is_none() + && ui.lines_job.is_none() + && !ui.learning_loading + && ui + .library + .repertoires + .iter() + .all(|r| ui.index.contains_key(&r.id) && ui.stats.contains_key(&r.id)) + && ui.stats_key.as_ref().is_some_and(|key| { + key.library_revision == ui.library.revision + && key.learning_revision == ui.learning.revision + }); + if ready || Instant::now() > deadline { + frame(ui, ctx, settings, size, Vec::new()); + return; + } + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn frame( + ui: &mut RepertoireUi, + ctx: &egui::Context, + settings: &mut Settings, + size: egui::Vec2, + events: Vec, +) -> Vec { + let mut actions = Vec::new(); ctx.run_ui( egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, 900.0), - )), - time: Some(time), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - f.ui.show_library(ui, &f.settings); - }); - }, - ) - .drop_without_applying_deltas(); -} - -fn render_repertoire( - f: &mut Fixture, - ctx: &egui::Context, - width: f32, - time: f64, - events: Vec, -) -> Vec { - render_repertoire_frame(f, ctx, width, 700.0, time, events).1 -} - -fn render_repertoire_frame( - f: &mut Fixture, - ctx: &egui::Context, - width: f32, - height: f32, - time: f64, - events: Vec, -) -> (Vec, Vec) { - let mut actions = Vec::new(); - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(width, height), - )), - time: Some(time), + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), events, ..Default::default() }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - actions = f.ui.show(ui, &mut f.settings); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - (actions, shapes) + |root| actions = ui.show(root, settings), + ) + .drop_without_applying_deltas(); + actions } -fn click_events(position: egui::Pos2) -> Vec { - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] +fn panel_rect(ctx: &egui::Context) -> egui::Rect { + egui::containers::panel::PanelState::load(ctx, egui::Id::new("opening_side")) + .map(|state| state.outer_rect) + .unwrap_or(egui::Rect::NOTHING) +} + +fn key(key: Key) -> egui::Event { + egui::Event::Key { + key, + physical_key: None, + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + } } #[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(), +fn the_card_says_what_to_do_in_every_state() { + let stats = |due, unseen, total| RowStats { + total, + due, + unseen, + learning: 0, + learnt: total - unseen, + next: None, + }; + assert_eq!(card_state(Some(true), None), CardState::Counting); + assert_eq!( + card_state(Some(true), Some(&Err("broken".into()))), + CardState::Failed("broken".into()) + ); + assert_eq!( + card_state(Some(false), Some(&Ok(stats(0, 0, 0)))), + CardState::Empty + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 0, 0)))), + CardState::OtherColor + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(3, 40, 50)))), + CardState::Review { due: 3, new: 10 } + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 4, 50)))), + CardState::OnlyNew { new: 4 } + ); + assert_eq!( + card_state(Some(true), Some(&Ok(stats(0, 0, 50)))), + CardState::Done { next: None } + ); + // Every state has a main button that does something, but «Counting». + for (state, side) in [ + (CardState::Review { due: 3, new: 10 }, LearningSide::White), + (CardState::OnlyNew { new: 4 }, LearningSide::White), + ( + CardState::Done { + next: Some((1_800_000_000, 2)), + }, + LearningSide::White, + ), + (CardState::Empty, LearningSide::White), + (CardState::OtherColor, LearningSide::White), + (CardState::Failed("x".into()), LearningSide::Black), + ] { + let (label, enabled, item) = main_button(&state, side); + assert!(enabled && item.is_some() && !label.is_empty(), "{state:?}"); + let (today, _) = card_texts(&state, side); + assert!(!today.is_empty(), "{state:?}"); + } + assert!(!main_button(&CardState::Counting, LearningSide::White).1); + assert_eq!( + main_button(&CardState::OtherColor, LearningSide::White).0, + tr("Play as Black") + ); + assert_eq!( + card_texts(&CardState::Review { due: 3, new: 10 }, LearningSide::White), + ( + trf("Today: {n} to review · {m} new", &[("n", &3), ("m", &10)]), + trf("About {t} min", &[("t", &5)]) + ) + ); + // Under a minute the time is not shown; a part with zero is left out. + assert_eq!( + card_texts(&CardState::Review { due: 2, new: 0 }, LearningSide::White), + (trf("Today: {n} to review", &[("n", &2)]), String::new()) + ); +} + +#[test] +fn today_counts_until_the_end_of_the_day_and_at_most_ten_new() { + let mut library = Library::default(); + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 \ + 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 *"; + let id = library + .create("Ruy", &chess_core::parse_str(pgn).game) + .unwrap(); + let today = layout::end_of_today(); + let scope = StatsScope::for_repertoire(id.clone(), LearningSide::White, today); + let keys: Vec<_> = active_learning_memberships(&library, &scope) + .unwrap() + .into_iter() + .map(|membership| membership.key) + .collect(); + assert_eq!(keys.len(), 12); + let mut learning = LearningData::default(); + let now = layout::now(); + for (index, key) in keys.iter().take(3).enumerate() { + let item = learning.ensure_item(key.clone()); + item.introduced = true; + item.correct_streak = 3; + // Due later today, due long ago, due in two days. + item.next_review_at = Some(match index { + 0 => today - 1, + 1 => now - 10 * DAY, + _ => now + 2 * DAY, + }); + } + let stats = row_stats(&library, &learning, &id, LearningSide::White, today).unwrap(); + assert_eq!( + (stats.total, stats.due, stats.unseen, stats.learnt), + (12, 2, 9, 3) + ); + assert_eq!(stats.new_today(), 9); + assert_eq!(stats.today(), 11); + assert_eq!( + card_state(Some(true), Some(&Ok(stats.clone()))), + CardState::Review { due: 2, new: 9 } + ); + let black = row_stats(&library, &learning, &id, LearningSide::Black, today).unwrap(); + assert_eq!(black.total, 11); + assert_eq!(black.new_today(), NEW_PER_SESSION); +} + +#[test] +fn loading_lifts_the_old_depth_limit_without_touching_the_pgn() { + let dir = TestDir::new("depth"); + let ids = save_library(&dir, &[("Limited", "1. e4 e5 2. Nf3 *")]); + let (store, _) = dir.stores(); + let stored = store.load().unwrap(); + assert_eq!( + stored.repertoires[0].max_plies, + trainer::repertoire::DEFAULT_MAX_PLIES + ); + let ui = dir.ui(); + let repertoire = ui.library.repertoire(&ids[0]).unwrap(); + assert_eq!(repertoire.max_plies, u32::MAX); + assert_eq!(repertoire.pgn, stored.repertoires[0].pgn); + // Nothing is written until the user changes something. + assert_eq!( + store.load().unwrap().repertoires[0].max_plies, + stored.repertoires[0].max_plies + ); +} + +#[test] +fn an_import_reads_name_colour_counts_and_warnings() { + let dir = TestDir::new("import"); + let path = dir.0.join("caro.pgn"); + std::fs::write( + &path, + "[Event \"Caro-Kann for Black\"]\n\n1. e4 c6 2. d4 (2. Nc3 d5) (2. c4 d5) d5 *\n\n\ + [Event \"Empty\"]\n\n*\n", + ) + .unwrap(); + let preview = read_import(&path, None, Library::default(), &AtomicBool::new(false)).unwrap(); + assert_eq!(preview.default_name, "Caro-Kann for Black"); + assert_eq!(preview.suggested, LearningSide::Black); + assert_eq!(preview.games, 2); + assert_eq!(preview.lines, 3); + assert_eq!(preview.own(LearningSide::Black), 4); + assert_eq!(preview.own(LearningSide::White), 4); + assert_eq!( + preview.warnings, + [trf("Game {n} has no moves", &[("n", &2)])] + ); + // The source file is only read. + assert!( + std::fs::read_to_string(&path) + .unwrap() + .starts_with("[Event \"Caro-Kann") + ); + + let mut ui = dir.ui(); + let mut settings = Settings::default(); + ui.dialog = Some(Dialog::Import(ImportDialog { + job: 1, + target: None, + name: preview.default_name.clone(), + side: preview.suggested, + preview: Some(preview), + error: None, + cancel: Arc::new(AtomicBool::new(false)), + })); + assert!(ui.confirm_import(&mut settings)); + let id = ui.selected.clone().unwrap(); + assert_eq!( + ui.library.repertoire(&id).unwrap().name, + "Caro-Kann for Black" + ); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + assert_eq!( + settings.repertoire_modes.get(id.as_str()), + Some(&(TrainingMode::Black, QueueMode::SpacedRepetition)) + ); + assert_eq!(dir.stores().0.load().unwrap().repertoires.len(), 1); +} + +#[test] +fn a_white_repertoire_is_suggested_for_white() { + let game = chess_core::parse_str("1. e4 e5 (1... c5 2. Nf3) (1... e6 2. d4) 2. Nf3 *").game; + assert_eq!(suggested_side(&game), LearningSide::White); + let even = chess_core::parse_str("1. e4 e5 *").game; + assert_eq!(suggested_side(&even), LearningSide::White); +} + +#[test] +fn old_colours_open_as_before_and_both_opens_as_white() { + let mut settings = Settings::default(); + let id = Library::default().create_empty("Any").unwrap(); + assert_eq!(layout::side_of(&settings, &id), LearningSide::White); + settings.repertoire_modes.insert( + 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() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(shape) if shape.galley.text() == text => { - Some(shape.pos + egui::vec2(8.0, 6.0)) - } - _ => None, - }) - .unwrap_or_else(|| panic!("missing text {text:?}")) -} - -fn assert_rect_inside(outer: egui::Rect, inner: egui::Rect) { - assert!(inner.min.x >= outer.min.x, "{inner:?} outside {outer:?}"); - assert!(inner.min.y >= outer.min.y, "{inner:?} outside {outer:?}"); - assert!(inner.max.x <= outer.max.x, "{inner:?} outside {outer:?}"); - assert!(inner.max.y <= outer.max.y, "{inner:?} outside {outer:?}"); - assert!(inner.width() > 0.0, "empty rect: {inner:?}"); - assert!(inner.height() > 0.0, "empty rect: {inner:?}"); -} - -#[test] -fn dashboard_close_reloads_learning_and_preserves_repertoire_selection() { - let mut f = Fixture::new(); - 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, "Statistics"); - - let (actions, _) = - render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 1.0, click_events(details)); - - assert!(actions.is_empty()); - assert_eq!( - f.ui.dashboard - .as_ref() - .and_then(LearningDashboardUi::selected_repertoire), - Some(&f.id) - ); - assert_eq!( - f.ui.dashboard - .as_ref() - .map(LearningDashboardUi::selected_side), - Some(LearningSide::Black) - ); - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::Black, now()); - let key = active_learning_keys(&f.ui.library, &scope) - .unwrap() - .into_iter() - .next() - .unwrap(); - let mut data = f.ui.learning_store.load().unwrap(); - assert_eq!(data.snapshots.len(), 1); - data.revision = 23; - data.learning.ensure_item(key.clone()).introduced = true; - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .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, "← Back to repertoire"); - f.ui.scroll_to_selected = false; - - let (actions, _) = - render_repertoire_frame(&mut f, &ctx, 1400.0, 900.0, 3.0, click_events(close)); - - assert!(actions.is_empty()); - assert!(f.ui.dashboard.is_none()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - assert_eq!(f.ui.learning.revision, 23); - assert!(f.ui.learning.learning.item(&key).unwrap().introduced); - assert!(!f.ui.scroll_to_selected); - - data.revision = 24; - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - let before_reopen = std::fs::read(f.ui.learning_store.path()).unwrap(); - f.ui.open_dashboard(); - assert!(f.ui.dashboard.is_some()); - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - assert_eq!( - std::fs::read(f.ui.learning_store.path()).unwrap(), - before_reopen - ); - f.ui.scroll_to_selected = false; - let (actions, _) = render_repertoire_frame( - &mut f, - &ctx, - 1400.0, - 900.0, - 4.0, - vec![egui::Event::Key { - key: Key::Escape, - physical_key: None, - pressed: true, - repeat: false, - modifiers: Modifiers::NONE, - }], - ); - - assert!(actions.is_empty()); - assert!(f.ui.dashboard.is_none()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - assert_eq!(f.ui.learning.revision, 24); - assert!(!f.ui.scroll_to_selected); -} - -#[test] -fn compact_statistics_shows_actionable_counts() { - let mut f = Fixture::new(); - f.aggregate(); - let ctx = egui::Context::default(); - let output = 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| f.ui.statistics_panel(ui), - ); - let has_text = |expected: &str| { - output.shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Text(shape) if shape.galley.text().replace('\n', " ") == expected) - }) - }; - assert!(has_text("Learnt 0 of 1 moves")); - assert!(has_text("Unseen: 1 · Due now: 0")); - output.drop_without_applying_deltas(); -} - -#[test] -fn dashboard_does_not_open_over_editor_or_preparing_training() { - let mut f = Fixture::new(); - f.ui.open_editor(); - - f.ui.open_dashboard(); - assert!(f.ui.dashboard.is_none()); - - f.ui.close_editor(); - f.ui.preparing = true; - f.ui.open_dashboard(); - assert!(f.ui.dashboard.is_none()); -} - -#[test] -fn dashboard_uses_the_full_workspace_at_both_window_sizes() { - for (width, height) in [(1400.0, 900.0), (640.0, 480.0)] { - let mut f = Fixture::new(); - f.ui.open_dashboard(); - let ctx = egui::Context::default(); - let mut bounds = None; - let mut actions = Vec::new(); - 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| { - egui::CentralPanel::default().show(ui, |ui| { - let available = ui.available_rect_before_wrap(); - actions = f.ui.show(ui, &mut f.settings); - bounds = Some((available, ui.min_rect())); - }); - }, - ); - let dashboard_visible = output.shapes.iter().any(|clipped| { - 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 (α version)") - }); - output.drop_without_applying_deltas(); - - assert!(actions.is_empty()); - assert!(dashboard_visible); - assert!(!repertoire_header_visible); - let (available, content) = bounds.unwrap(); - assert_rect_inside(available, content); - assert!(f.ui.dashboard.is_some()); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - } -} - -#[test] -fn early_paths_paint_opaque_window_background_without_allocating() { - 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)] { - for editor in [false, true] { - let mut f = Fixture::new(); - if editor { - f.ui.open_editor(); - } else { - f.ui.open_dashboard(); - } - let ctx = egui::Context::default(); - ctx.set_visuals(visuals.clone()); - let mut available = None; - let mut content = None; - 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| { - egui::CentralPanel::default().show(ui, |ui| { - available = Some(ui.available_rect_before_wrap()); - let actions = f.ui.show(ui, &mut f.settings); - assert!(actions.is_empty()); - content = Some(ui.min_rect()); - }); - }, - ); - let shapes = output.shapes.clone(); - output.drop_without_applying_deltas(); - let available = available.unwrap(); - assert_rect_inside(available, content.unwrap()); - assert!(shapes.iter().any(|clipped| { - matches!(&clipped.shape, egui::Shape::Rect(shape) if shape.rect == available && shape.fill == visuals.window_fill() && shape.fill.a() == 255) - })); - if editor { - assert!(f.ui.debug_layout.editor.is_some()); - } else { - f.ui.dashboard.as_mut().unwrap().wait_until_idle_for_test(); - } - } - } - } -} - -#[test] -fn creating_an_empty_repertoire_selects_it_in_the_workspace() { - let mut f = Fixture::new(); - f.ui.open_library(); - f.ui.edit_name = Some((None, "Empty opening".to_owned())); - - f.ui.save_name(None, "Empty opening", &f.settings); - - let created = - f.ui.library - .repertoires - .iter() - .find(|r| r.name == "Empty opening") - .expect("the repertoire is saved"); - assert!(!f.ui.training_visible); - assert_eq!(f.ui.selected.as_ref(), Some(&created.id)); - assert!(f.ui.edit_name.is_none()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn editor_opens_in_the_full_workspace() { - let mut f = Fixture::new(); - f.ui.open_editor(); - let ctx = egui::Context::default(); - - render_repertoire(&mut f, &ctx, 1000.0, 0.0, Vec::new()); - - let editor_rect = f.ui.debug_layout.editor.unwrap(); - assert!(editor_rect.width() > 900.0, "{editor_rect:?}"); - assert!(f.ui.editor.is_some()); - assert_eq!(f.ui.editor_id.as_ref(), Some(&f.id)); -} - -#[test] -fn applied_editor_library_is_adopted_without_a_second_save() { - let mut f = Fixture::new(); - f.ui.open_editor(); - let mut applied = f.ui.library.clone(); - applied.repertoire_mut(&f.id).unwrap().set_max_plies(7); - f.ui.library_store.save(&mut applied).unwrap(); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - let expected = applied.clone(); - let generation = f.ui.index_generation; - - let _ = f.ui.handle_editor_action(RepertoireEditorAction::Applied { - repertoire_id: f.id.clone(), - library: applied, - }); - - assert_eq!( - serde_json::to_value(&f.ui.library).unwrap(), - serde_json::to_value(&expected).unwrap() - ); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); - assert!(f.ui.index_generation > generation); - assert!(f.ui.editor.is_none()); - assert!(f.ui.editor_id.is_none()); -} - -#[test] -fn cancelling_editor_does_not_change_library_bytes() { - let mut f = Fixture::new(); - f.ui.open_editor(); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - let library = f.ui.library.clone(); - - let _ = f.ui.handle_editor_action(RepertoireEditorAction::Cancel); - - assert!(f.ui.editor.is_none()); - assert_eq!( - serde_json::to_value(&f.ui.library).unwrap(), - serde_json::to_value(&library).unwrap() - ); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); -} - -#[test] -fn editor_draft_blocks_selection_start_and_unresolved_exit() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - let second = library - .create("Other opening", &chess_core::parse_str("1. d4 d5 *").game) - .unwrap(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - f.ui.select(f.id.clone(), &f.settings); - f.ui.open_editor(); - let ctx = egui::Context::default(); - let shapes = render_repertoire(&mut f, &ctx, 1000.0, 0.0, Vec::new()); - let start = shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text() == "20" => { - Some(text.pos + egui::vec2(8.0, 6.0)) - } - _ => None, - }) - .expect("depth DragValue text"); - render_repertoire( - &mut f, - &ctx, - 1000.0, - 1.0, - vec![ - egui::Event::PointerMoved(start), - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: start, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ], - ); - render_repertoire( - &mut f, - &ctx, - 1000.0, - 2.0, - vec![ - egui::Event::Text("7".to_owned()), - egui::Event::Key { - key: egui::Key::Enter, - physical_key: None, - pressed: true, - repeat: false, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::Key { - key: egui::Key::Enter, - physical_key: None, - pressed: false, - repeat: false, - modifiers: egui::Modifiers::NONE, - }, - ], - ); - assert!(f.ui.has_unsaved(), "edit did not change the editor depth"); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - - f.ui.select(second, &f.settings); - assert_eq!(f.ui.selected.as_ref(), Some(&f.id)); - assert!(f.ui.editor.is_some()); - f.ui.start(&mut f.settings); - assert!(!f.ui.preparing); - assert!(f.ui.editor.is_some()); - f.ui.resolve_unsaved(); - assert!(f.ui.editor.is_some()); - assert!(!f.ui.training_visible); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); -} - -#[test] -fn stale_applied_is_ignored_after_changing_repertoire() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - let second = library - .create("Other opening", &chess_core::parse_str("1. d4 d5 *").game) - .unwrap(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - f.ui.select(f.id.clone(), &f.settings); - f.ui.open_editor(); - let current = f.ui.library.clone(); - let before = std::fs::read(f.ui.library_store.path()).unwrap(); - let mut stale = current.clone(); - stale.revision = current.revision.saturating_add(1); - stale.repertoire_mut(&f.id).unwrap().set_max_plies(3); - f.ui.select(second.clone(), &f.settings); - - let _ = f.ui.handle_editor_action(RepertoireEditorAction::Applied { - repertoire_id: f.id.clone(), - library: stale, - }); - - assert_eq!(f.ui.selected.as_ref(), Some(&second)); - assert_eq!( - serde_json::to_value(&f.ui.library).unwrap(), - serde_json::to_value(¤t).unwrap() - ); - assert_eq!(std::fs::read(f.ui.library_store.path()).unwrap(), before); - assert!(f.ui.editor.is_none()); -} - -#[test] -fn clicking_a_row_selects_it_without_leaving_the_workspace() { - let mut f = Fixture::new(); - f.ui.open_library(); - f.ui.selected = None; - let ctx = egui::Context::default(); - let mut frame = |time: f64, events: Vec| { - ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(1000.0, 700.0), - )), - time: Some(time), - events, - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - f.ui.show_library(ui, &f.settings); - }); - }, - ) - .drop_without_applying_deltas(); - (f.ui.selected.clone(), f.ui.training_visible) - }; - let click = || { - let position = egui::pos2(200.0, 120.0); - vec![ - egui::Event::PointerMoved(position), - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: true, - modifiers: egui::Modifiers::NONE, - }, - egui::Event::PointerButton { - pos: position, - button: egui::PointerButton::Primary, - pressed: false, - modifiers: egui::Modifiers::NONE, - }, - ] - }; - - frame(0.0, Vec::new()); - let (selected, training) = frame(1.0, click()); - assert_eq!(selected.as_ref(), Some(&f.id)); - assert!(!training); - assert!(f.ui.tree.is_some()); -} - -#[test] -fn long_save_error_and_import_cancel_stay_inside_the_fixed_status_row() { - for width in [640.0_f32, 1400.0] { - let mut f = Fixture::new(); - f.ui.side = LearningSide::White; - let ctx = egui::Context::default(); - render_library(&mut f, &ctx, width, 0.0); - let baseline = f.ui.debug_layout; - let baseline_status = baseline.status.unwrap(); - let baseline_table = baseline.table.unwrap(); - assert_eq!(baseline_status.height(), 24.0); - assert!(baseline_table.height() > 0.0); - - let path = f - .dir - .join("a-very-long-save-error-parent-directory-for-layout-regression") - .join("another-long-directory-component-that-makes-the-error-wrap") - .join("learning.json"); - let file_name = path.file_name().unwrap().to_string_lossy().into_owned(); - let lock = path.with_file_name(format!("{file_name}.lock")); - std::fs::create_dir_all(&lock).unwrap(); - let attempt = trainer::repertoire::TrainingAttempt { - user_id: trainer::repertoire::LOCAL_PROFILE_ID.to_owned(), - position_fen4: fen4(&chess_core::shakmaty::Chess::default()), - client_attempt_id: "status-layout-error".to_owned(), - session_id: "status-layout-session".to_owned(), - event_type: trainer::repertoire::TrainingEventType::CorrectIndependent, - expected_uci: "e2e4".to_owned(), - actual_uci: Some("e2e4".to_owned()), - response_time_ms: Some(1), - happened_at: now(), - }; - let error = LearningStore::new(&path) - .apply_attempt(attempt, &SrsSettings::default()) - .unwrap_err() - .to_string(); - assert!(error.len() > 160, "short fixture error: {error}"); - assert!(error.contains("learning.json.lock"), "{error}"); - f.ui.error = Some(error); - f.ui.cancel = Some(Arc::new(AtomicBool::new(false))); - - render_library(&mut f, &ctx, width, 1.0); - - let with_error = f.ui.debug_layout; - let status = with_error.status.unwrap(); - let message = with_error.message.unwrap(); - let retry = with_error.retry.unwrap(); - let cancel = with_error.cancel.unwrap(); - assert_eq!(status, baseline_status); - assert_eq!(with_error.table, baseline.table); - assert_rect_inside(status, message); - assert_rect_inside(status, retry); - assert_rect_inside(status, cancel); - assert!(message.max.x <= cancel.min.x, "{message:?} {cancel:?}"); - assert!(cancel.max.x <= retry.min.x, "{cancel:?} {retry:?}"); - assert!(status.bottom() <= with_error.table.unwrap().top()); - assert_eq!(f.ui.side, LearningSide::White); - assert!(f.ui.error.is_some()); - } -} - -#[test] -fn opening_index_has_the_deepest_eco_and_variation_name() { - let game = chess_core::parse_str("1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O *").game; - let mut library = Library::default(); - let id = library.create("Rossolimo", &game).unwrap(); - let tree = RepertoireTree::new(library.repertoire(&id).unwrap()); - - let labels = opening_labels(&tree); - - assert_eq!(labels.len(), 1); - assert_eq!(labels[0].eco, "B31"); - assert!( - labels[0] - .name - .starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), - "{}", - labels[0].name - ); -} - -#[test] -fn rows_have_one_height_and_show_at_most_five_opening_names() { - let f = Fixture::new(); - let row = |count: usize| LibraryRow { - id: f.id.clone(), - name: "Opening".to_owned(), - openings: (0..count) - .map(|index| OpeningLabel { - eco: format!("B{index:02}"), - name: format!("Opening {index}"), - }) - .collect(), - }; - - assert_eq!(LibraryRow::height(), 156.0); - assert_eq!(row(0).visible_openings().len(), 0); - assert_eq!(row(3).visible_openings().len(), 3); - assert_eq!(row(8).visible_openings().len(), OPENING_LINES); -} - -#[test] -fn load_preserves_scope_and_main_answer_overrides() { - let f = Fixture::new(); - let store = LibraryStore::new(f.dir.join("scoped-library.json")); - let mut library = Library::default(); - let id = library - .create("Scoped opening", &chess_core::parse_str("1. e4 e5 *").game) - .unwrap(); - let repertoire = library.repertoire_mut(&id).unwrap(); - repertoire.max_plies = 1; - repertoire - .set_prefix_disabled(&["e2e4".to_owned()], true) - .unwrap(); - let start = fen4(repertoire.game().start().position()); - repertoire - .set_main_answer_override(&start, "e2e4", LearningSide::White) - .unwrap(); - let pgn = repertoire.pgn.clone(); - let overrides = repertoire.main_answer_overrides.clone(); - store.save(&mut library).unwrap(); - - let ui = RepertoireUi::with_stores( - store.clone(), - LearningStore::new(f.dir.join("scoped-learning.json")), - ); - - assert!(ui.library_error.is_none(), "{:?}", ui.library_error); - let saved = store.load().unwrap(); - for library in [&ui.library, &saved] { - let repertoire = library.repertoire(&id).unwrap(); - assert_eq!(repertoire.max_plies, 1); - assert_eq!(repertoire.disabled_prefixes, [vec!["e2e4".to_owned()]]); - assert_eq!(repertoire.main_answer_overrides, overrides); - assert_eq!(repertoire.pgn, pgn); - } -} - -#[test] -fn persist_does_not_wipe_scope_or_main_answer_overrides() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - let repertoire = library.repertoire_mut(&f.id).unwrap(); - repertoire.max_plies = 1; - repertoire - .set_prefix_disabled(&["e2e4".to_owned()], true) - .unwrap(); - let start = fen4(repertoire.game().start().position()); - repertoire - .set_main_answer_override(&start, "e2e4", LearningSide::White) - .unwrap(); - let pgn = repertoire.pgn.clone(); - let overrides = repertoire.main_answer_overrides.clone(); - - assert!(f.ui.persist(library)); - - let saved = f.ui.library_store.load().unwrap(); - for library in [&f.ui.library, &saved] { - let repertoire = library.repertoire(&f.id).unwrap(); - assert_eq!(repertoire.max_plies, 1); - assert_eq!(repertoire.disabled_prefixes, [vec!["e2e4".to_owned()]]); - assert_eq!(repertoire.main_answer_overrides, overrides); - assert_eq!(repertoire.pgn, pgn); - } - f.deliver(f.completed_job()); - assert_eq!(f.ui.variant_counts[&f.id], 1); -} - -#[test] -fn aggregate_reports_mixed_learning_and_unseen_items() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 *") - .game - .to_pgn(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - assert_eq!(keys.len(), 3); - let at = now(); - let mut learning = trainer::repertoire::LearningData::default(); - for key in keys { - match key.expected_uci.as_str() { - "e2e4" => { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 1; - item.next_review_at = Some(at - 1); - } - "g1f3" => { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(at + 86_400); - item.previous_interval_seconds = Some(86_400); - } - _ => {} - } - } - f.ui.learning.learning = learning; - f.ui.learning.revision += 1; - - let scoped = f.aggregate(); - let summary = &scoped.summary; - assert_eq!(scoped.scope.side, LearningSide::White); - assert_eq!(scoped.scope.repertoire_ids.len(), 1); - assert!(scoped.scope.repertoire_ids.contains(&f.id)); - assert_eq!(summary.total, 3); - assert_eq!(summary.unseen, 1); - assert_eq!(summary.learning, 1); - assert_eq!(summary.learnt, 1); - assert_eq!(summary.uncertain, 0); - assert_eq!(summary.due, 1); - assert_eq!(summary.next_due_at, None); - assert_eq!(summary.learnt_percent, Some(100.0 / 3.0)); - assert_eq!(summary.confident_percent, Some(100.0 / 3.0)); -} - -#[test] -fn migration_v2_is_read_only_and_old_runs_do_not_become_learning_kpis() { - let mut f = Fixture::new(); - let path = f.dir.join("v2-learning.json"); - let mut legacy = trainer::repertoire::StatsData::default(); - legacy.runs.push(trainer::repertoire::RunStats { - repertoire_id: f.id.clone(), - mode: TrainingMode::White, - completions: 42, - last: Some(now()), - recent: Vec::new(), - }); - legacy.legacy_lines.insert( - "legacy-line".to_owned(), - serde_json::json!({"runs": 7, "unknown": [1, 2, 3]}), - ); - trainer::repertoire::StatsStore::new(&path) - .save(&mut legacy) - .unwrap(); - let before = std::fs::read(&path).unwrap(); - - f.ui = RepertoireUi::with_stores(f.ui.library_store.clone(), LearningStore::new(&path)); - - assert!(f.ui.learning_error.is_none()); - let legacy = f.ui.learning.legacy_practice.as_ref().unwrap(); - assert_eq!(legacy["runs"][0]["completions"], 42); - assert_eq!(legacy["legacy_lines"]["legacy-line"]["runs"], 7); - assert!(f.ui.learning.learning.items.is_empty()); - let scoped = f.aggregate(); - assert_eq!(scoped.summary.total, 1); - assert_eq!(scoped.summary.unseen, 1); - assert_eq!(scoped.summary.learning, 0); - assert_eq!(scoped.summary.accuracy_attempts, 0); - assert_eq!(std::fs::read(&path).unwrap(), before); -} - -#[test] -fn stale_index_cannot_replace_a_newer_rebuild() { - let mut f = Fixture::new(); - f.ui.rebuild_tree(); - let old = f.completed_job(); - f.ui.rebuild_tree(); - let current = f.completed_job(); - f.deliver(old); - assert!(f.ui.indexing); - assert!(f.ui.tree.is_none()); - assert!(f.ui.trees.is_empty()); - f.deliver(current); - assert!(!f.ui.indexing); - assert!(f.ui.tree.is_some()); - assert!(f.ui.trees.contains_key(&f.id)); -} - -#[test] -fn completed_training_start_is_ignored_after_leaving_the_workspace() { - let mut f = Fixture::new(); - f.start(); - let ready = f.completed_job(); - f.ui.open_library(); - f.deliver(ready); - assert!(!f.ui.preparing); - assert!(!f.ui.training_visible); - assert!(f.ui.training.is_none()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn stale_training_start_cannot_cancel_or_replace_a_new_generation() { - let mut f = Fixture::new(); - f.start(); - let old = f.completed_job(); - let old_generation = f.ui.training_generation; - f.ui.open_library(); - f.ui.select(f.id.clone(), &f.settings); - f.start(); - let current = f.completed_job(); - assert!(f.ui.training_generation > old_generation); - f.deliver(old); - f.deliver(Event::TrainingReady( - old_generation, - Err("stale failure".into()), - )); - assert!(f.ui.preparing); - assert!(f.ui.training.is_none()); - assert!(f.ui.error.is_none()); - f.deliver(current); - assert!(!f.ui.preparing); - assert!(f.ui.training_visible); - assert!(f.ui.training.is_some()); -} - -#[test] -fn async_start_can_finish_a_real_opening_and_persist_learning() { - let mut f = Fixture::new(); - f.start(); - let ready = f.completed_job(); - f.deliver(ready); - assert!(f.ui.training_visible); - - f.ui.debug_moves("e2e4 settle"); - - let training = f.ui.training.as_ref().unwrap(); - assert!(training.is_finished()); - assert!(!training.target_available()); - assert!(!training.has_unsaved()); - let saved = f.ui.learning_store.load().unwrap(); - assert_eq!(saved.learning.attempts.len(), 1); - assert!(saved.learning.attempts[0].event_type.is_independent()); - assert_eq!( - saved - .learning - .items - .iter() - .map(|item| item.correct_count) - .sum::(), - 1 - ); - assert!(f.ui.error.is_none()); -} - -#[test] -fn unsaved_learning_blocks_start_and_resolve_restores_the_session() { - let mut f = Fixture::new(); - f.start(); - let ready = f.completed_job(); - f.deliver(ready); - let lock = f.dir.join("learning.json.lock"); - std::fs::remove_file(&lock).unwrap(); - std::fs::create_dir(&lock).unwrap(); - f.ui.debug_moves("e2e4"); - assert!(f.ui.has_unsaved()); - - let generation = f.ui.training_generation; - f.ui.start(&mut f.settings); - assert!(!f.ui.preparing); - assert_eq!(f.ui.training_generation, generation); - f.ui.open_library(); - assert!(!f.ui.training_visible); - f.ui.resolve_unsaved(); - assert!(f.ui.training_visible); -} - -#[test] -fn start_uses_the_srs_queue_instead_of_legacy_practice() { - let mut f = Fixture::new(); - f.settings + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + settings .repertoire_modes - .insert(f.id.to_string(), (TrainingMode::White, QueueMode::Practice)); - f.ui.select(f.id.clone(), &f.settings); - assert_eq!(f.ui.side, LearningSide::White); - let summary = f.aggregate().summary.clone(); - assert_eq!(summary.due, 0); - assert_eq!(summary.unseen, 1); - - f.start(); - + .insert(id.to_string(), (TrainingMode::Both, QueueMode::LeastRecent)); + assert_eq!(layout::side_of(&settings, &id), LearningSide::White); + layout::set_side(&mut settings, &id, LearningSide::Black); assert_eq!( - f.settings.repertoire_modes.get(f.id.as_str()), - Some(&(TrainingMode::White, QueueMode::SpacedRepetition)) + settings.repertoire_modes[id.as_str()], + (TrainingMode::Black, QueueMode::SpacedRepetition) ); - f.deliver(f.completed_job()); - assert!(f.ui.training_visible); - let saved = f.ui.learning_store.load().unwrap(); - let session = saved.session_snapshots.last().unwrap(); - assert_eq!(session.session.mode, QueueMode::SpacedRepetition); - assert_eq!(session.queue.len(), 1); - assert_eq!(session.queue[0].key.expected_uci, "e2e4"); } #[test] -fn review_mode_and_priority_are_saved_and_start_without_due_items() { - let mut f = Fixture::new(); - f.settings.repertoire_modes.insert( - f.id.to_string(), - (TrainingMode::White, QueueMode::LeastRecent), +fn the_three_screens_keep_the_board_and_the_panel_in_one_place() { + let dir = TestDir::new("geometry"); + save_library( + &dir, + &[ + ("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *"), + ("London", "1. d4 d5 2. Bf4 *"), + ], ); - f.settings - .repertoire_priorities - .insert(f.id.to_string(), LearningPriority::CommonPositionsFirst); - f.ui.select(f.id.clone(), &f.settings); - assert_eq!(f.ui.queue, QueueMode::LeastRecent); - assert_eq!(f.ui.priority, LearningPriority::CommonPositionsFirst); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - let mut data = LearningStoreData::default(); - for key in keys { - let item = data.learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(now() + 86_400); - item.previous_interval_seconds = Some(86_400); - } - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - f.ui.learning = f.ui.learning_store.load().unwrap(); - let summary = f.aggregate().summary.clone(); - assert_eq!(summary.due, 0); - assert_eq!(summary.unseen, 0); - - f.start(); - - assert_eq!( - f.settings.repertoire_modes.get(f.id.as_str()), - Some(&(TrainingMode::White, QueueMode::LeastRecent)) - ); - assert_eq!( - f.settings.repertoire_priorities.get(f.id.as_str()), - Some(&LearningPriority::CommonPositionsFirst) - ); - f.deliver(f.completed_job()); - assert!(f.ui.training_visible); - let saved = f.ui.learning_store.load().unwrap(); - let session = saved.session_snapshots.last().unwrap(); - assert_eq!(session.session.mode, QueueMode::LeastRecent); - assert_eq!( - session.stats_scope.learning_priority, - LearningPriority::CommonPositionsFirst - ); - assert_eq!(session.queue.len(), 1); -} - -#[test] -fn shared_reset_previews_impact_and_cancel_is_a_no_op_before_confirm() { - let mut f = Fixture::new(); - let mut library = f.ui.library.clone(); - library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game.to_pgn(); - let second = library - .create("Second shared", &chess_core::parse_str("1. e4 c5 *").game) - .unwrap(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - let pgn_before = - f.ui.library - .repertoires - .iter() - .map(|repertoire| repertoire.pgn.clone()) - .collect::>(); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - assert_eq!(keys.len(), 2); - let mut data = LearningStoreData::default(); - for key in keys { - let item = data.learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(now() + 86_400); - } - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - f.ui.learning = f.ui.learning_store.load().unwrap(); - let before = std::fs::read(f.ui.learning_store.path()).unwrap(); - - f.ui.begin_shared_reset(scope.clone()); - f.deliver(f.completed_job()); - let state = f.ui.shared_reset.as_ref().unwrap(); - let impact = state.impact.as_ref().unwrap(); - assert_eq!(impact.reset_count, 2); - assert_eq!(impact.shared_count, 1); - assert_eq!( - impact - .affected_repertoires - .iter() - .map(|repertoire| repertoire.name.as_str()) - .collect::>(), - BTreeSet::from(["Async opening", "Second shared"]) - ); - f.ui.cancel_shared_reset(); - assert!(f.ui.shared_reset.is_none()); - assert_eq!(std::fs::read(f.ui.learning_store.path()).unwrap(), before); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); - - f.ui.begin_shared_reset(scope.clone()); - f.deliver(f.completed_job()); - f.ui.confirm_shared_reset(); - assert!(!f.ui.shared_reset.as_ref().unwrap().busy); - assert_eq!(std::fs::read(f.ui.learning_store.path()).unwrap(), before); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); - - f.ui.shared_reset.as_mut().unwrap().confirmed = true; - f.ui.confirm_shared_reset(); - assert!(f.ui.shared_reset.as_ref().unwrap().busy); - f.deliver(f.completed_job()); - assert!(f.ui.shared_reset.is_none()); - assert!( - f.ui.learning - .learning - .items - .iter() - .all(|item| item.is_unseen()) - ); - let second_scope = StatsScope::for_repertoire(second, LearningSide::White, now()); - let second_summary = aggregate_scope( - &f.ui.library, - &f.ui.learning.learning, - &second_scope, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(second_summary.summary.unseen, 1); - assert_eq!(f.aggregate().summary.unseen, 2); - assert_eq!( - f.ui.library - .repertoires - .iter() - .map(|repertoire| repertoire.pgn.clone()) - .collect::>(), - pgn_before - ); - - f.ui.begin_shared_reset(scope); - let stale = f.completed_job(); - f.ui.select(f.id.clone(), &f.settings); - f.deliver(stale); - assert!(f.ui.shared_reset.is_none()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn review_order_reset_changes_only_the_cycle_cursor() { - let mut f = Fixture::new(); - f.ui.library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game.to_pgn(); - f.ui.queue = QueueMode::ReviewInOrder; - f.ui.priority = LearningPriority::DepthFirst; - f.start(); - f.deliver(f.completed_job()); - f.ui.debug_moves("e2e4 settle"); - f.ui.open_library(); - let before = f.ui.learning.learning.clone(); - let cursor = f.ui.review_snapshot().unwrap(); - assert_eq!(cursor.current_index, 1); - assert_eq!(cursor.completed_keys.len(), 1); - - f.ui.reset_review_cursor(); - assert!(f.ui.review_reset_pending); - f.deliver(f.completed_job()); - - assert!(!f.ui.review_reset_pending); - assert_eq!(f.ui.learning.learning, before); - let cursor = f.ui.review_snapshot().unwrap(); - assert_eq!(cursor.current_index, 0); - assert_eq!(cursor.cycle, 0); - assert!(cursor.completed_keys.is_empty()); -} - -#[test] -fn review_reset_controls_keep_statistics_and_library_visible() { - let mut f = Fixture::new(); - for queue in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] { - f.ui.queue = queue; - f.ui.parameters_open = false; - f.ui.debug_layout.reset_review = None; + for (size, left) in [(vec2(1400.0, 900.0), 940.0), (vec2(960.0, 600.0), 576.0)] { + let mut ui = dir.ui(); + let mut settings = Settings::default(); 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"); + crate::assets::install(&ctx); + settle(&mut ui, &ctx, &mut settings, size); + let repertoires = panel_rect(&ctx); assert!( - table.top() < 600.0, - "table is outside the viewport: {table:?}" + (repertoires.left() - left).abs() <= 1.0, + "{repertoires:?} in {size:?}" ); - assert!(table.height() > 0.0); - assert_eq!( - f.ui.debug_layout.reset_review.is_some(), - queue == QueueMode::ReviewInOrder + // Selecting another row moves nothing. + frame( + &mut ui, + &ctx, + &mut settings, + size, + vec![key(Key::ArrowDown)], ); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert_eq!(panel_rect(&ctx), repertoires); + // Lines. + ui.open_lines(&settings, None); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Lines(_))); + assert_eq!(panel_rect(&ctx), repertoires); + // A session started from Lines, and back to Lines. + ui.start(SessionKind::ReviewAll, &settings); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Session(_))); + assert_eq!(panel_rect(&ctx), repertoires); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(matches!(ui.screen, Screen::Lines(_))); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(matches!(ui.screen, Screen::Repertoires)); + assert_eq!(panel_rect(&ctx), repertoires); } } #[test] -fn due_start_has_priority_and_there_is_no_hidden_early_or_empty_start() { - let mixed = LearningAggregate { - total: 2, - unseen: 1, - due: 1, - ..LearningAggregate::default() - }; - assert_eq!(start_kind(&mixed), StartKind::Review); - let introduce = LearningAggregate { - total: 2, - unseen: 1, - learning: 1, - ..LearningAggregate::default() - }; - assert_eq!(start_kind(&introduce), StartKind::IntroduceNew); - let future = LearningAggregate { - total: 1, - learnt: 1, - learnt_percent: Some(100.0), - confident_percent: Some(100.0), - next_due_at: Some(now() + 86_400), - ..LearningAggregate::default() - }; - assert_eq!(start_kind(&future), StartKind::Unavailable); - assert_eq!( - start_kind(&LearningAggregate::default()), - StartKind::Unavailable - ); -} - -#[test] -fn partial_srs_continue_has_priority_over_introduce_and_keeps_snapshot() { - let mut f = Fixture::new(); - f.ui.library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *") - .game - .to_pgn(); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()) - .with_max_depth(Some(20)); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - let key_for = |expected: &str| { - keys.iter() - .find(|key| key.expected_uci == expected) - .unwrap() - .clone() - }; - let mut learning = trainer::repertoire::LearningData::default(); - for expected in ["e2e4", "g1f3"] { - let item = learning.ensure_item(key_for(expected)); - item.introduced = true; - item.next_review_at = Some(now()); - } - let mut snapshot = LearningSessionSnapshot::new( - "partial-srs-continue", - &f.ui.library, - &learning, - scope, - SrsSettings::default(), - ) - .unwrap(); - let attempt = snapshot - .play_uci(&f.ui.library, "e2e4", "partial-e4", now(), Some(100)) - .unwrap(); - let _ = learning - .apply_attempt(attempt, &SrsSettings::default()) - .unwrap(); - let attempt = snapshot - .advance_context(&f.ui.library, "partial-context", now()) - .unwrap(); - let _ = learning - .apply_attempt(attempt, &SrsSettings::default()) - .unwrap(); - assert_eq!(snapshot.context_index, 1); - assert_ne!(snapshot.phase, LearningSessionPhase::Finished); - for item in &mut learning.items { - item.next_review_at = Some(now() + 86_400); - } - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&LearningStoreData { - sessions: vec![snapshot.session.clone()], - session_snapshots: vec![snapshot.clone()], - learning, - ..LearningStoreData::default() - }) - .unwrap(), - ) - .unwrap(); - f.ui.reload_learning(); - f.ui.aggregates.clear(); - - let summary = f.aggregate().summary.clone(); - assert_eq!(summary.due, 0); - assert!(summary.unseen > 0); - assert_eq!(f.ui.selected_start_kind(&summary), StartKind::Review); - let unfinished = f.ui.learning.session_snapshots[0].clone(); - f.ui.learning.session_snapshots[0].phase = LearningSessionPhase::Finished; - assert_eq!(f.ui.selected_start_kind(&summary), StartKind::IntroduceNew); - f.ui.learning.session_snapshots[0] = unfinished; - - let snapshot_count = f.ui.learning.session_snapshots.len(); - f.ui.start(&mut f.settings); - assert!(f.ui.preparing); - f.deliver(f.completed_job()); - - let training = f.ui.training.as_ref().unwrap(); - assert_eq!(training.session_id(), "partial-srs-continue"); - let saved = f.ui.learning_store.load().unwrap(); - assert_eq!(saved.session_snapshots.len(), snapshot_count); - assert_eq!( - saved - .session_snapshot("partial-srs-continue") - .unwrap() - .context_index, - 1 - ); -} - -#[test] -fn aggregate_reuses_pending_work_across_minutes_and_ignores_evicted_results() { - let mut f = Fixture::new(); - let mut key = f.ui.current_aggregate_key().unwrap(); - key.minute -= 2; - f.ui.aggregates.insert(key.clone(), None); - - f.ui.request_aggregate(f.ui.current_aggregate_key().unwrap()); - - assert_eq!(f.ui.aggregates.len(), 1); - assert_eq!(f.ui.aggregates.get(&key), Some(&None)); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let scoped = aggregate_scope( - &f.ui.library, - &f.ui.learning.learning, - &scope, - &SrsSettings::default(), - ) - .unwrap(); - f.deliver(Event::Aggregated(key.clone(), Box::new(Ok(scoped)))); - assert!(matches!( - f.ui.aggregates.get(&key), - Some(Some(Ok(scoped))) if scoped.summary.total == 1 - )); - f.ui.aggregates.clear(); - f.deliver(Event::Aggregated( - key, - Box::new(Err("stale failure".to_owned())), - )); - assert!(f.ui.aggregates.is_empty()); - assert!(f.ui.error.is_none()); -} - -#[test] -fn variant_count_is_pgn_routes_not_learning_total() { - let mut f = Fixture::new(); - f.ui.library.repertoire_mut(&f.id).unwrap().pgn = - chess_core::parse_str("1. e4 e5 (1... c5) *").game.to_pgn(); - let library = f.ui.library.clone(); - assert!(f.ui.persist(library)); - f.deliver(f.completed_job()); - assert_eq!(f.ui.variant_counts[&f.id], 2); - assert_eq!(f.aggregate().summary.total, 1); - - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let keys = trainer::repertoire::active_learning_keys(&f.ui.library, &scope).unwrap(); - let mut learning = trainer::repertoire::LearningData::default(); - for key in keys { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 3; - item.next_review_at = Some(now() + 86_400); - } - f.ui.learning.learning = learning; - f.ui.learning.revision += 1; - - assert_eq!(f.aggregate().summary.learnt, 1); - assert_eq!(f.ui.variant_counts[&f.id], 2); - assert!(matches!(f.ui.rx.try_recv(), Err(mpsc::TryRecvError::Empty))); -} - -#[test] -fn deleting_a_repertoire_preserves_global_learning() { - let mut f = Fixture::new(); - let scope = StatsScope::for_repertoire(f.id.clone(), LearningSide::White, now()); - let key = trainer::repertoire::active_learning_keys(&f.ui.library, &scope) - .unwrap() - .into_iter() - .next() - .unwrap(); - let mut data = LearningStoreData { - revision: 7, - ..LearningStoreData::default() - }; - let item = data.learning.ensure_item(key.clone()); - item.introduced = true; - item.correct_streak = 2; - std::fs::write( - f.ui.learning_store.path(), - serde_json::to_vec_pretty(&data).unwrap(), - ) - .unwrap(); - f.ui.learning = f.ui.learning_store.load().unwrap(); - let before = std::fs::read(f.ui.learning_store.path()).unwrap(); - - assert!(f.ui.debug_delete(&f.settings)); - - assert!(f.ui.library.repertoire(&f.id).is_none()); - assert_eq!(std::fs::read(f.ui.learning_store.path()).unwrap(), before); - let saved = f.ui.learning_store.load().unwrap(); - assert!(saved.learning.item(&key).is_some()); - assert_eq!(saved.learning.items.len(), 1); -} - -#[test] -fn importing_and_saving_a_repertoire_does_not_change_source_pgn() { - let mut f = Fixture::new(); - let path = f.dir.join("source.pgn"); - let source = b"[Event \"Source\"]\n\n1. e4 e5 (1... c5) 2. Nf3 {keep} *\n"; - std::fs::write(&path, source).unwrap(); - let cancel = AtomicBool::new(false); - - let preview = read_import(&path, None, f.ui.library.clone(), &cancel).unwrap(); - assert!(f.ui.persist(preview.library)); - - assert_eq!(std::fs::read(&path).unwrap(), source); -} - -#[test] -#[ignore = "manual corpus import and indexing measurement"] -fn corpus_import_preserves_source_and_reports_real_outcome() { - for filename in ["The Ruy Lopez - Move by Move.pgn", "Alekhin.pgn"] { - println!("File: {filename}"); - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../pgnFilesforExample") - .join(filename); - let before = std::fs::read(&path).unwrap(); - let cancelled = AtomicBool::new(false); - let started = std::time::Instant::now(); - let imported = read_import(&path, None, Library::default(), &cancelled); - let import_elapsed = started.elapsed(); - assert_eq!( - std::fs::read(&path).unwrap(), - before, - "import changed source bytes" - ); - - // Count the source independently, including records after any rejected one. - let db = PgnDatabase::from_bytes(before.clone(), None, &mut |_| {}, &cancelled).unwrap(); - let source_nodes: usize = (0..db.len()) - .map(|index| { - db.load_game(index) - .unwrap() - .game - .attached_nodes() - .len() - .saturating_sub(1) - }) - .sum(); - println!( - "Corpus: {} bytes; {} records; {} parsed source move nodes", - before.len(), - db.len(), - source_nodes - ); - match imported { - Ok(preview) => { - let repertoire = preview.library.repertoire(&preview.id).unwrap(); - let started = std::time::Instant::now(); - let tree = RepertoireTree::new(repertoire); - let index_elapsed = started.elapsed(); - let nodes = tree.game().attached_nodes().len().saturating_sub(1); - assert_eq!(preview.records, db.len()); - assert!(nodes > 0); - println!( - "IMPORTED: {} records; {} merged move nodes; import {:?}; index {:?}; combined {:?}", - preview.records, - nodes, - import_elapsed, - index_elapsed, - import_elapsed + index_elapsed - ); - } - Err(reason) => { - assert!(!reason.is_empty()); - println!( - "REJECTED (no repertoire imported, indexing not run): {reason}; read_import elapsed {import_elapsed:?}" - ); - } - } - if filename == "Alekhin.pgn" { - let fixture = Fixture::new(); - let subset_path = fixture.dir.join("Alekhin-first-200.pgn"); - let subset = (0..200) - .map(|index| db.raw_text(index).expect("source record exists")) - .collect::>() - .join("\n\n"); - std::fs::write(&subset_path, subset.as_bytes()).unwrap(); - let started = std::time::Instant::now(); - let mut preview = read_import(&subset_path, None, Library::default(), &cancelled) - .expect("the first 200 complete source records must import successfully"); - let subset_import_elapsed = started.elapsed(); - assert_eq!(preview.records, 200); - let repertoire = preview.library.repertoire(&preview.id).unwrap(); - let started = std::time::Instant::now(); - let tree = RepertoireTree::new(repertoire); - let index_elapsed = started.elapsed(); - let nodes = tree.game().attached_nodes().len().saturating_sub(1); - let canonical = tree.game().canonical_tree(); - let started = std::time::Instant::now(); - let store = LibraryStore::new(fixture.dir.join("corpus-library.json")); - store.save(&mut preview.library).unwrap(); - let loaded = store.load().unwrap(); - assert_eq!( - loaded - .repertoire(&preview.id) - .unwrap() - .game() - .canonical_tree(), - canonical - ); - let roundtrip_elapsed = started.elapsed(); - assert_eq!(std::fs::read(&subset_path).unwrap(), subset.as_bytes()); - assert!(nodes > 0); - println!( - "IMPORTED TEMP FIRST 200: {} bytes; {} merged move nodes; import {:?}; index {:?}; import+index {:?}; save/reload+canonical verification {:?}", - subset.len(), - nodes, - subset_import_elapsed, - index_elapsed, - subset_import_elapsed + index_elapsed, - roundtrip_elapsed - ); - } - assert_eq!( - std::fs::read(&path).unwrap(), - before, - "corpus check changed source bytes" - ); - } -} - -#[test] -fn training_scope_uses_repertoire_depth_and_custom_context_policy() { - let mut f = Fixture::new(); - let repertoire = f.ui.library.repertoire_mut(&f.id).unwrap(); - repertoire.pgn = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game.to_pgn(); - repertoire.set_max_plies(2); - let policy = trainer::repertoire::LearningContextPolicy { - use_fixed_piece_speed: false, - move_speed_adjustment: 0.25, - consider_leadup_moves: true, - ..Default::default() - }; - f.settings - .repertoire_context_policies - .insert(f.id.to_string(), policy); - - let scoped = f.aggregate(); - assert_eq!(scoped.scope.max_depth, Some(2)); - assert_eq!(scoped.summary.total, 1); - +fn keys_of_the_screen_do_nothing_under_a_dialog() { + let dir = TestDir::new("dialog-keys"); + save_library(&dir, &[("A", "1. e4 *"), ("B", "1. d4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); 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()); - - let saved = f.ui.learning_store.load().unwrap(); - let session = saved.session_snapshots.last().unwrap(); - assert_eq!(session.stats_scope.max_depth, Some(2)); - assert_eq!(session.queue.len(), 1); - assert_eq!(session.queue[0].key.expected_uci, "e2e4"); - assert_eq!(session.context_policy, policy); - assert!(f.ui.matches_review_snapshot(session)); -} - -#[test] -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 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)); - + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + settle(&mut ui, &ctx, &mut settings, size); + let selected = ui.selected.clone(); + ui.dialog = Some(Dialog::New { + name: String::new(), + side: LearningSide::White, + error: None, + }); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + let actions = frame( + &mut ui, + &ctx, + &mut settings, + size, + vec![key(Key::ArrowDown)], + ); + assert!(actions.is_empty()); + assert_eq!(ui.selected, selected); + let actions = frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); assert!( actions .iter() - .any(|action| matches!(action, RepertoireAction::SettingsChanged)) + .all(|action| !matches!(action, RepertoireAction::Close)), + "Esc closes the dialog, not the screen" ); - let policy = f - .settings - .repertoire_context_policies - .get(f.id.as_str()) - .unwrap(); - assert!(!policy.use_fixed_piece_speed); + frame(&mut ui, &ctx, &mut settings, size, Vec::new()); + assert!(ui.dialog.is_none()); + let actions = frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + assert!(matches!(actions.as_slice(), [RepertoireAction::Close])); } #[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()); +fn names_are_checked_and_a_new_repertoire_keeps_its_colour() { + let dir = TestDir::new("names"); + save_library(&dir, &[("Najdorf", "1. e4 c5 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let mut actions = Vec::new(); + for (name, error) in [ + (" ", tr("The repertoire name must not be empty")), + ("najdorf", tr("A repertoire with this name already exists")), + ] { + ui.dialog = Some(Dialog::New { + name: name.into(), + side: LearningSide::Black, + error: None, + }); + ui.confirm_dialog(&mut settings, &mut actions); + assert!( + matches!(&ui.dialog, Some(Dialog::New { error: Some(e), .. }) if e == error), + "{name:?}" + ); } + ui.dialog = Some(Dialog::New { + name: "Sveshnikov".into(), + side: LearningSide::Black, + error: None, + }); + ui.confirm_dialog(&mut settings, &mut actions); + assert!(ui.dialog.is_none()); + let id = ui.selected.clone().unwrap(); + assert_eq!(ui.library.repertoire(&id).unwrap().name, "Sveshnikov"); + assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); + assert!(matches!( + actions.as_slice(), + [RepertoireAction::SettingsChanged] + )); } #[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()); +fn delete_keeps_the_answers_and_selects_the_neighbour() { + let dir = TestDir::new("delete"); + let ids = save_library( + &dir, + &[("A", "1. e4 *"), ("B", "1. d4 *"), ("C", "1. c4 *")], + ); + let mut learning = LearningData::default(); + let library = dir.stores().0.load().unwrap(); + let scope = StatsScope::for_repertoire(ids[1].clone(), LearningSide::White, 0); + let key = active_learning_keys(&library, &scope) + .unwrap() + .into_iter() + .next() + .unwrap(); + learning.ensure_item(key.clone()).introduced = true; + let data = LearningStoreData { + learning, + ..LearningStoreData::default() + }; + std::fs::write( + dir.0.join("repertoire-training.json"), + serde_json::to_vec(&data).unwrap(), + ) + .unwrap(); + let mut ui = dir.ui(); + ui.select(ids[1].clone()); + ui.dialog = Some(Dialog::Delete { id: ids[1].clone() }); + ui.delete_selected(); + assert!(ui.dialog.is_none()); + assert_eq!(ui.selected, Some(ids[2].clone())); + assert!(ui.library.repertoire(&ids[1]).is_none()); + let kept = dir.stores().1.load().unwrap(); + assert!(kept.learning.item(&key).is_some_and(|item| item.introduced)); +} + +#[test] +fn a_session_needs_no_question_to_go_back_and_counts_refresh_after_it() { + let dir = TestDir::new("session-back"); + save_library(&dir, &[("Scotch", "1. e4 e5 2. Nf3 Nc6 3. d4 *")]); + let mut ui = dir.ui(); + let mut settings = Settings::default(); + let ctx = egui::Context::default(); + crate::assets::install(&ctx); + let size = vec2(1400.0, 900.0); + settle(&mut ui, &ctx, &mut settings, size); + let id = ui.selected.clone().unwrap(); + assert_eq!(ui.selected_card(), CardState::OnlyNew { new: 3 }); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Session(_))); + ui.debug_moves("settle answer settle"); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Escape)]); + frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); + settle(&mut ui, &ctx, &mut settings, size); + assert!(matches!(ui.screen, Screen::Repertoires)); + // One new move was shown and played: it is due again today, two are left new. + let stats = ui.stats.get(&id).unwrap().as_ref().unwrap(); + assert_eq!((stats.unseen, stats.due), (2, 1)); } diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 748ebcb..461b66f 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -11,6 +11,7 @@ pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response { /// A section header: reserve global actions before laying out a long title. /// Returns (back, settings). +#[allow(dead_code)] pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) { let mut clicked = (false, false); let compact = ui.available_width() < 600.0; @@ -29,6 +30,37 @@ pub fn section_header(ui: &mut Ui, back: &str, title: &str) -> (bool, bool) { clicked } +/// A two-line section header in the places of the game's (title and a quiet line under +/// it; an empty subtitle keeps its line, so the header never changes height). +/// Returns (back, settings). +pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) -> (bool, bool) { + let mut clicked = (false, false); + let compact = ui.available_width() < 600.0; + ui.add_space(4.0); + ui.horizontal(|ui| { + clicked.0 = ui.button(back).clicked(); + ui.separator(); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + clicked.1 = settings_button(ui, compact).clicked(); + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + ui.add(egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate()) + .on_hover_text(title); + let sub = ui.add( + egui::Label::new( + egui::RichText::new(if subtitle.is_empty() { " " } else { subtitle }) + .weak(), + ) + .truncate(), + ); + if !subtitle.is_empty() { + sub.on_hover_text(subtitle); + } + }); + }); + }); + clicked +} + /// A dev check (`CP_PANEL_CHECK=1`): a panel whose content is wider than the panel. egui /// then moves a right panel out (its left part under the central panel, its right part /// off the window); the content of every panel must fit its least width diff --git a/docs/dev/opening-trainer-v2-handoff.md b/docs/dev/opening-trainer-v2-handoff.md new file mode 100644 index 0000000..0874c5b --- /dev/null +++ b/docs/dev/opening-trainer-v2-handoff.md @@ -0,0 +1,37 @@ +# Тренировка дебюта v2 — точка продолжения (2026-11-26) + +Как продолжить в новой сессии оркестратора: прочитать этот файл, затем +`docs/qa/opening-trainer-v2-devhooks.md` (раздел «Состояние работы» — пишет разработчик). + +## Где что + +- Рабочая копия: `/home/vrubel/projects/chessbaseLinux-opening-v2`, ветка `feature/opening-trainer-v2` + (от `main` = выпуск 2.3.0). Сборка: `CARGO_TARGET_DIR=/tmp/opencode/v2-target`. +- Основная папка `/home/vrubel/projects/chessbaseLinux` (ветка `feature/opening-repertoire-training`, 2.2.0) + содержит НЕзакоммиченные временные стрелки/круги (board.rs, game_view.rs, …). Не удалять; + при интеграции перенести в v2 (по одной строке `temporary_shapes` в экране задания). +- Документы (в v2): концепция `docs/design/opening-trainer-concept-2026-11-26.md`, + спецификация `docs/design/opening-trainer-v2-spec.md` (+ «Решения оркестратора» в конце), + аудиты `docs/design/opening-trainer-ui-audit-2026-11-26.md`, `docs/research/opening-trainer-*-2026-11-26.md`. +- Снимки аудита: `/home/vrubel/projects/chessbaseLinux/target/qa-opening-rethink/shots/`; + корпус форума/FAQ/блога ChessTempo: там же `chesstempo-corpus/` (читать поиском по вопросу, не целиком). + +## Договорённости с владельцем + +- Менять только раздел «Тренировка дебюта»; другие разделы — ни функционально, ни визуально. +- На UI/UX не экономить; экономить на служебных проходах. Бюджет ограничен (~$30 на реализацию). +- Агенты запускаются строго последовательно (параллельные запросы упираются в лимит провайдера). +- Решения по составу раздела делегированы оркестратору; итог записать в `docs/decisions.md`. +- Строка «Путь» (ходы линии) в занятии — не делать; предложено владельцу как опция, ответа нет. + +## План + +1. ✅ Исследование, аудиты, концепция, спецификация (коммит `bd72aea`). +2. ✅ Ядро: дневная очередь (к повторению + N новых), возврат ошибки, проход/ветка (`3db35e4`). +3. ⏳ Разработчик (сессия `ses_de7ebabe0ffeYd1iH2ZOmQggaQ`): UI — репертуары, карточка, диалоги, + занятие S0–S9, итог, «Повторить всё подряд», ветка, «Варианты», удаление старого UI, i18n, проверки. + Если сессия агента потеряна — запустить нового developer: «продолжи по handoff и devhooks.md». +4. Дизайн-ревью designer (не автор кода) на реальных снимках 1400×900 и 960×600 по §9 спецификации, + сравнение с экраном партии/игры, отсутствие скачков. +5. Исправления → обновить `docs/dev/tasks.md` (задача 37/новая), `docs/decisions.md`, CHANGELOG. +6. Интеграция: перенести временные стрелки; слияние в main — только с разрешения владельца. diff --git a/docs/qa/opening-trainer-v2-devhooks.md b/docs/qa/opening-trainer-v2-devhooks.md new file mode 100644 index 0000000..c9ed544 --- /dev/null +++ b/docs/qa/opening-trainer-v2-devhooks.md @@ -0,0 +1,46 @@ +# Тренировка дебюта v2: dev-хуки для снимков + +Изолированный профиль: `XDG_CONFIG_HOME`, `XDG_DATA_HOME` во временный каталог и +`CP_REPERTOIRE_DIR=<каталог>` (там `repertoires.json`, `repertoire-training.json`). +Снимок: `CP_SCREENSHOT=file.png CP_SCREENSHOT_DELAY=<сек>`. + +| Переменная | Что делает | +| --- | --- | +| `CP_REPERTOIRE=library` | открыть экран «Репертуары» | +| `CP_REPERTOIRE_SELECT=<часть имени>` | выбрать репертуар перед действием | +| `CP_REPERTOIRE=train` / `main` / `review` | занятие «Тренироваться» / главная кнопка карточки / «Повторить всё подряд» | +| `CP_REPERTOIRE=white` / `black` | задать цвет выбранному и начать занятие | +| `CP_REPERTOIRE=lines` (+ `CP_REPERTOIRE_LINE="e2e4 e7e5"`) | экран «Варианты», выбран ход по пути UCI | +| `CP_REPERTOIRE=branch` + `CP_REPERTOIRE_LINE=…` | «Тренировать эту ветку» | +| `CP_REPERTOIRE=menu` | открыть меню `⋯` выбранной строки | +| `CP_REPERTOIRE=new` (+ `CP_REPERTOIRE_NAME=…` — сразу создать) | диалог «Новый репертуар» | +| `CP_REPERTOIRE=rename` / `color` / `reset` / `delete` | диалоги §7.3–7.5 | +| `CP_REPERTOIRE=message` | полоса сообщения с ошибкой | +| `CP_REPERTOIRE_IMPORT_FILE=` (+ `CP_REPERTOIRE_IMPORT_INTO=1` — в выбранный) | диалог импорта с этим файлом | +| `CP_REPERTOIRE_CONFIRM_IMPORT=1` | подтвердить импорт, когда файл прочитан | +| `CP_REPERTOIRE_SLOW=<мс>` | задержать подготовку занятия (виден S0 «Готовим занятие…») | +| `CP_REPERTOIRE_MOVES="…"` | действия в занятии: UCI-ходы, `answer`, `wrong`, `hint`, `skip`, `settle`, `stop` (= Esc) | +| `CP_REPERTOIRE_HINT=1` | подсказка в текущем вопросе | +| `CP_REPERTOIRE_EXPORT=1` (+ `CP_REPERTOIRE_EXPORT_FILE=…`) | экспорт PGN | + +## Состояние работы (2026-11-26, wip) + +Сделано: +- Ядро (`crates/trainer`, коммит 3db35e4): `new_daily` (к повторению + ≤10 новых), `introduce_more`, + возврат ошибки/подсказки в конец очереди, `preview_new`, `new_single_pass_review`, + `new_branch_review`; необязательные флаги снимка; тесты `daily_tests.rs` (7), все 200 тестов trainer зелёные. +- Desktop: новые модули `opening_layout.rs`, `opening_session.rs` (бывший `learning_training.rs`, + движок записи/перетаскивания/подвода сохранён), `opening_lines.rs`; `repertoire_ui.rs` переписан + (таблица, карточка, меню `⋯`, диалоги §7, «Добавить в репертуар» с цветом); `widgets::section_header_sub`. + Удалены `learning_dashboard/branches/charts/context_controls`, `repertoire_editor`, `repertoire_training`. + i18n: 120 новых строк на 9 языках. Тесты opening_* (41) зелёные; repertoire_ui — 10 из 11. + +Следующее: +- Починить тест `a_session_needs_no_question_to_go_back_and_counts_refresh_after_it`: хук `debug_moves` + «answer» после «settle» играет ход до подготовки показа (в журнале лишние AutoContext/Previewed) — + разобраться с порядком `settle`/показа нового хода при асинхронной записи. +- Удалить из `i18n.rs` неиспользуемые строки старого раздела; clippy `-D warnings`; wasm-проверка `apps/web`; + mobile-api; снимки в `target/qa-opening-v2/dev-shots/` (репертуары, новый ход, итог). +- Обрезка пути слева в блоке «Выбранный ход» (сейчас обрезка справа). + +Известные поломки/отклонения: см. выше; визуально не проверено (снимков ещё нет). From 0493965a71ba06e49ec36c87a9b7a16e8894dbe6 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:31:14 +0300 Subject: [PATCH 04/31] wip: repertoire_ui test fixes in progress --- apps/desktop/src/repertoire_ui.rs | 4 ++++ apps/desktop/src/repertoire_ui_tests.rs | 8 +++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 623b470..5086db0 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -270,6 +270,8 @@ pub struct RepertoireUi { index_job: u64, stats: HashMap>, stats_key: Option, + /// The key of the counts shown (older than `stats_key` while counting). + stats_shown: Option, screen: Screen, /// The «Lines» screen a branch session was started from. lines_return: Option>, @@ -320,6 +322,7 @@ impl RepertoireUi { index_job: 0, stats: HashMap::new(), stats_key: None, + stats_shown: None, screen: Screen::Repertoires, lines_return: None, preparing: None, @@ -905,6 +908,7 @@ impl RepertoireUi { Event::Stats(key, stats) => { if self.stats_key.as_ref() == Some(&key) { self.stats = stats; + self.stats_shown = Some(key); } } Event::Imported(job, result) => { diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index 3e0542a..0ebae52 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -69,7 +69,8 @@ fn settle(ui: &mut RepertoireUi, ctx: &egui::Context, settings: &mut Settings, s && ui.stats_key.as_ref().is_some_and(|key| { key.library_revision == ui.library.revision && key.learning_revision == ui.learning.revision - }); + }) + && ui.stats_shown == ui.stats_key; if ready || Instant::now() > deadline { frame(ui, ctx, settings, size, Vec::new()); return; @@ -519,7 +520,8 @@ fn a_session_needs_no_question_to_go_back_and_counts_refresh_after_it() { frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); settle(&mut ui, &ctx, &mut settings, size); assert!(matches!(ui.screen, Screen::Repertoires)); - // One new move was shown and played: it is due again today, two are left new. + // e4 was shown and played, Nf3 shown when the session stopped: both are due + // again today (a shown move comes back a minute later), d4 is still new. let stats = ui.stats.get(&id).unwrap().as_ref().unwrap(); - assert_eq!((stats.unseen, stats.due), (2, 1)); + assert_eq!((stats.unseen, stats.due), (1, 2)); } From 8a94d0882284243e493ea9376178ce0afe02253b Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:34:36 +0300 Subject: [PATCH 05/31] opening session: a new move's showing is recorded only with the played move A new move left on the board when the session stops stays new, as the result and the card say (restores the original expectation of a_session_needs_no_question_to_go_back_and_counts_refresh_after_it). --- apps/desktop/src/opening_session.rs | 76 ++++++++++++++--------- apps/desktop/src/opening_session_tests.rs | 48 ++++++++++++-- apps/desktop/src/repertoire_ui_tests.rs | 6 +- 3 files changed, 95 insertions(+), 35 deletions(-) diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index e4c153e..9fe7337 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -110,11 +110,8 @@ enum CommitKind { outcome: PlayOutcome, shown_prefix: ShownPrefix, }, - /// `new`: the first showing of a new move; otherwise a hint (or the move revealed - /// after another repertoire move). - Preview { - new: bool, - }, + /// A hint, or the move revealed after another repertoire move. + Preview, } #[derive(Clone)] @@ -215,6 +212,9 @@ pub struct OpeningSessionUi { presentation: Option, completed_attempt_ids: BTreeSet, pending_commit: Option, + /// The showing of the new move on the board, recorded together with the move once + /// it is played: a new move left unplayed stays new. + unplayed_preview: Option, commit_in_flight: Option>>, #[cfg(test)] synchronous_commits: bool, @@ -384,6 +384,7 @@ impl OpeningSessionUi { presentation: None, completed_attempt_ids, pending_commit: None, + unplayed_preview: None, commit_in_flight: None, #[cfg(test)] synchronous_commits: false, @@ -635,10 +636,11 @@ impl OpeningSessionUi { LearningSessionPhase::AwaitingIndependent if self.session.current_is_new(&self.learning) => { - // A new move is shown before it is asked (decision 2026-11-26). + // A new move is shown before it is asked; the showing is recorded + // only with the played move. self.ready_since = None; let id = unique_id(self.session.id()); - self.preview_with_id_at(id, true, now, layout::now()); + self.show_new_with_id_at(id, layout::now()); } LearningSessionPhase::AwaitingIndependent | LearningSessionPhase::AwaitingContextIndependent => { @@ -1039,7 +1041,7 @@ impl OpeningSessionUi { if alternative && self.session.phase == LearningSessionPhase::AwaitingIndependent { self.alternative_revealed = true; let id = unique_id(self.session.id()); - self.preview_with_id_at(id, false, now, happened_at); + self.preview_with_id_at(id, now, happened_at); } else if alternative { self.alternative_revealed = true; } @@ -1068,13 +1070,37 @@ impl OpeningSessionUi { if !self.can_hint() || self.completed_attempt_ids.contains(&client_attempt_id) { return false; } - self.preview_with_id_at(client_attempt_id, false, now, happened_at) + self.preview_with_id_at(client_attempt_id, now, happened_at) + } + + /// S2: the new move goes on the board with its arrow. Nothing is written yet. + fn show_new_with_id_at(&mut self, client_attempt_id: String, happened_at: i64) { + if self.has_unsaved() || self.completed_attempt_ids.contains(&client_attempt_id) { + return; + } + match self.session.preview_new(client_attempt_id, happened_at) { + Ok(attempt) => { + self.unplayed_preview = attempt; + self.board.clear(); + } + Err(error) => { + self.error = Some(error.to_string()); + return; + } + } + // The arrow comes from the presentation of the shown move. + match self + .session + .presentation_with_learning(&self.library, &self.learning) + { + Ok(presentation) => self.presentation = Some(presentation), + Err(error) => self.error = Some(error.to_string()), + } } fn preview_with_id_at( &mut self, client_attempt_id: String, - new: bool, now: Instant, happened_at: i64, ) -> bool { @@ -1082,12 +1108,7 @@ impl OpeningSessionUi { return false; } let target = self.session.current_target().cloned(); - let result = if new { - self.session.preview_new(client_attempt_id, happened_at) - } else { - self.session.preview(client_attempt_id, happened_at) - }; - let attempt = match result { + let attempt = match self.session.preview(client_attempt_id, happened_at) { Ok(Some(attempt)) => attempt, Ok(None) => return false, Err(error) => { @@ -1096,7 +1117,7 @@ impl OpeningSessionUi { } }; self.board.clear(); - self.begin_commit_for(attempt, CommitKind::Preview { new }, target, now); + self.begin_commit_for(attempt, CommitKind::Preview, target, now); true } @@ -1116,8 +1137,10 @@ impl OpeningSessionUi { Some("another learning event is still waiting to be saved".to_owned()); return; } + let mut attempts: Vec<_> = self.unplayed_preview.take().into_iter().collect(); + attempts.push(attempt); self.pending_commit = Some(PendingCommit { - attempts: vec![attempt], + attempts, kind, target, }); @@ -1214,7 +1237,7 @@ impl OpeningSessionUi { .then_some(shown_prefix); self.start_playback(*visual, outcome, now); } - CommitKind::Preview { .. } => { + CommitKind::Preview => { self.needs_prepare = true; self.prepare_presentation(now); } @@ -1250,12 +1273,11 @@ impl OpeningSessionUi { | PlayOutcome::ReplayAfterError | PlayOutcome::PreviewedReplay => {} }, - CommitKind::Preview { new: false } => { + CommitKind::Preview => { self.tally.hints += 1; self.tally.miss(target); } - CommitKind::Preview { new: true } | CommitKind::Context | CommitKind::ReusedContext => { - } + CommitKind::Context | CommitKind::ReusedContext => {} } } @@ -1298,6 +1320,7 @@ impl OpeningSessionUi { fn stop(&mut self) { self.stopped = true; + self.unplayed_preview = None; self.pending_automatic = None; if let Some(Playback::Automatic { .. }) = self.playback { self.playback = None; @@ -1486,12 +1509,9 @@ impl OpeningSessionUi { if self.pending_automatic.is_some() { return Some(self.watch()); } - if let Some(pending) = &self.pending_commit { - return match pending.kind { - CommitKind::Preview { new: true } => Some(State::New), - // Between moves: the card keeps what it said. - _ => None, - }; + if self.pending_commit.is_some() { + // Between moves: the card keeps what it said. + return None; } if self.needs_prepare { return None; diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index 6a2b614..7515ab2 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -1275,10 +1275,9 @@ fn a_new_move_is_shown_before_it_is_asked_and_counts_once_played() { ); assert_eq!(f.ui.session.remaining(), 1); tick_with_prime(&mut f.ui, Instant::now(), Duration::ZERO, NOW); - // Shown at once: PREVIEWED recorded, the arrow and the comment visible, no hint. - let attempts = f.attempts(); - assert_eq!(attempts.len(), 1); - assert_eq!(attempts[0].event_type, TrainingEventType::Previewed); + // Shown at once: the arrow and the comment visible, no hint; nothing recorded + // until it is played. + assert!(f.attempts().is_empty()); assert!(f.ui.session.showing_new); assert_eq!(f.ui.state(), Some(State::New)); assert_eq!(f.ui.revealed_uci().as_deref(), Some("e2e4")); @@ -1304,9 +1303,50 @@ fn a_new_move_is_shown_before_it_is_asked_and_counts_once_played() { ); let attempts = f.attempts(); assert_eq!(attempts.len(), 2); + assert_eq!(attempts[0].event_type, TrainingEventType::Previewed); assert_eq!(attempts[1].event_type, TrainingEventType::AutoContext); } +#[test] +fn a_new_move_left_unplayed_stays_new() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &[], + &["e2e4", "g1f3"], + "new-move-unplayed", + SessionKind::Daily, + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + assert!(f.ui.play_uci_with_id_at("e2e4", "play-e4".into(), at, NOW)); + let later = at + Duration::from_secs(5); + for _ in 0..4 { + tick_with_prime(&mut f.ui, later, Duration::ZERO, NOW); + } + assert_eq!(f.ui.state(), Some(State::New)); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + // A wrong move on a shown new move records nothing either. + assert!(f.ui.play_uci_with_id_at("d2d4", "wrong-nf3".into(), later, NOW)); + tick_with_prime(&mut f.ui, later + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::New)); + let mut actions = Vec::new(); + f.ui.request_exit(&mut actions); + assert!(f.ui.summary_visible()); + let attempts = f.attempts(); + let nf3 = attempts + .iter() + .filter(|attempt| attempt.expected_uci == "g1f3") + .count(); + assert_eq!( + nf3, + 0, + "{:?}", + attempts.iter().map(|a| a.event_type).collect::>() + ); + assert_eq!(f.ui.tally.new_moves, 1); +} + #[test] fn a_daily_session_brings_mistakes_and_hints_back_and_its_numbers_agree() { // White's moves: e4, Nf3, Bb5, then O-O after a6 Ba4 Nf6 is new. diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index 0ebae52..a2611ab 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -520,8 +520,8 @@ fn a_session_needs_no_question_to_go_back_and_counts_refresh_after_it() { frame(&mut ui, &ctx, &mut settings, size, vec![key(Key::Enter)]); settle(&mut ui, &ctx, &mut settings, size); assert!(matches!(ui.screen, Screen::Repertoires)); - // e4 was shown and played, Nf3 shown when the session stopped: both are due - // again today (a shown move comes back a minute later), d4 is still new. + // e4 was shown and played: it is due again today. Nf3 was on the board, unplayed, + // when the session stopped: like d4 it is still new. let stats = ui.stats.get(&id).unwrap().as_ref().unwrap(); - assert_eq!((stats.unseen, stats.due), (1, 2)); + assert_eq!((stats.unseen, stats.due), (2, 1)); } From d54e359f76e3f78c731d23536c24730c9c1a44c6 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:40:14 +0300 Subject: [PATCH 06/31] opening trainer: whole card frames, buttons never cut, path cut on the left, no arrow after a stopped session --- apps/desktop/src/i18n.rs | 11 +++++++ apps/desktop/src/opening_layout.rs | 47 +++++++++++++++++++++++++++++ apps/desktop/src/opening_lines.rs | 9 ++---- apps/desktop/src/opening_session.rs | 19 +++++++++--- apps/desktop/src/repertoire_ui.rs | 26 +++++++++------- 5 files changed, 90 insertions(+), 22 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 431e489..b5e6efd 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -315,6 +315,17 @@ const ROWS: &[[&str; 9]] = &[ "Yurishlar sanalmoqda…", "Жүрістер саналуда…", ], + [ + "Review all", + "Повторить всё", + "Tout réviser", + "Alles wiederholen", + "Repasar todo", + "Ripassa tutto", + "Revisar tudo", + "Hammasini takrorlash", + "Барлығын қайталау", + ], [ "Review all lines", "Повторить всё подряд", diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs index 61df871..ffadbed 100644 --- a/apps/desktop/src/opening_layout.rs +++ b/apps/desktop/src/opening_layout.rs @@ -83,6 +83,12 @@ pub(crate) fn card(ui: &Ui, active: bool, alert: bool) -> egui::Frame { frame } +/// The content size of a [`card`] filling a block of `height`: the frame's margins and +/// its stroke stay inside the block. +pub(crate) fn card_inner(ui: &Ui, height: f32) -> egui::Vec2 { + vec2(ui.available_width() - 22.0, height - 14.0).max(egui::Vec2::ZERO) +} + /// A block of a fixed height: whatever it holds, what follows never moves. pub(crate) fn fixed_block(ui: &mut Ui, height: f32, add: impl FnOnce(&mut Ui) -> R) -> R { let width = ui.available_width().max(1.0); @@ -108,6 +114,47 @@ pub(crate) fn line(ui: &mut Ui, text: impl Into) -> egui::Response { } } +/// `text` cut on the left by whole words ("… 4. Ba4 Nf6") to fit `width` in `font`: +/// the last moves of a path matter most. +pub(crate) fn cut_left(ui: &Ui, text: &str, font: &egui::FontId, width: f32) -> String { + let fits = |text: &str| { + ui.fonts_mut(|fonts| { + fonts + .layout_no_wrap(text.to_owned(), font.clone(), Color32::WHITE) + .size() + .x + }) <= width + }; + if fits(text) { + return text.to_owned(); + } + let mut rest = text; + while let Some((_, tail)) = rest.split_once(' ') { + rest = tail; + let cut = format!("… {rest}"); + if fits(&cut) { + return cut; + } + } + format!("… {rest}") +} + +/// One line cut on the left ([`cut_left`]), the whole text on hover. +pub(crate) fn line_left(ui: &mut Ui, text: &str, strong: bool) -> egui::Response { + let font = egui::TextStyle::Body.resolve(ui.style()); + let shown = cut_left(ui, text, &font, ui.available_width()); + let mut rich = RichText::new(shown); + if strong { + rich = rich.strong(); + } + let response = ui.add(egui::Label::new(rich).truncate()); + if text.is_empty() { + response + } else { + response.on_hover_text(text) + } +} + /// The trained colour of a repertoire, kept in the settings since 2.2.0 (an old "both /// colours" repertoire opens for White). pub(crate) fn side_of(settings: &Settings, id: &RepertoireId) -> LearningSide { diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs index a1f3b98..2f9fb60 100644 --- a/apps/desktop/src/opening_lines.rs +++ b/apps/desktop/src/opening_lines.rs @@ -292,7 +292,7 @@ impl OpeningLinesUi { let path = self.cursor_path(); let disabled = self.disabled_by(&path); layout::fixed_block(ui, SELECTED_H, |ui| { - let inner = vec2(ui.available_width() - 20.0, SELECTED_H - 12.0); + let inner = layout::card_inner(ui, SELECTED_H); layout::card(ui, false, false).show(ui, |ui| { ui.set_min_size(inner); ui.set_max_size(inner); @@ -300,12 +300,7 @@ impl OpeningLinesUi { if self.cursor == NodeId::ROOT { layout::line(ui, RichText::new(tr("Start position")).strong()); } else { - let label = self.path_label(self.cursor); - // Cut on the left: the last moves matter. - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.set_max_height(20.0); - layout::line(ui, RichText::new(label).strong()); - }); + layout::line_left(ui, &self.path_label(self.cursor), true); } if disabled.is_some() { layout::line( diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index 9fe7337..6d5a174 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -36,6 +36,8 @@ const DEFAULT_ANIMATION: Duration = Duration::from_millis(250); /// Mistakes listed under «Moves to remember». const REMEMBER_ROWS: usize = 8; const CARD_H: f32 = 64.0; +/// The words of a branch's path in the header ("4. Ba4 Nf6" is three). +const BRANCH_WORDS: usize = 12; const LINE_H: f32 = 20.0; const ROW_H: f32 = 30.0; const TOOL_H: f32 = 28.0; @@ -74,7 +76,15 @@ impl SessionKind { LearningSide::White => tr("Review all lines · you play White").to_owned(), LearningSide::Black => tr("Review all lines · you play Black").to_owned(), }, - Self::Branch { label, .. } => trf("Branch: {path}", &[("path", label)]), + Self::Branch { label, .. } => { + // Cut on the left: the last moves name the branch. + let words: Vec<&str> = label.split_whitespace().collect(); + let path = match words.len().checked_sub(BRANCH_WORDS) { + Some(skip) if skip > 0 => format!("… {}", words[skip..].join(" ")), + _ => label.clone(), + }; + trf("Branch: {path}", &[("path", &path)]) + } } } } @@ -1464,7 +1474,7 @@ impl OpeningSessionUi { /// The move shown by an arrow: revealed by the core, or a new move about to be shown. fn revealed_uci(&self) -> Option { - if self.playback.is_some() || self.pending_automatic.is_some() { + if self.playback.is_some() || self.pending_automatic.is_some() || self.stopped { return None; } if let Some(uci) = self @@ -1570,7 +1580,8 @@ impl OpeningSessionUi { } fn more_new_count(&self) -> usize { - if self.kind != SessionKind::Daily { + // A stopped session still has questions: the card starts the next one. + if self.kind != SessionKind::Daily || self.stopped { return 0; } self.summary.as_ref().map_or(0, |summary| summary.more_new) @@ -2262,7 +2273,7 @@ struct CardView { fn show_card(ui: &mut Ui, view: &CardView) { layout::fixed_block(ui, CARD_H, |ui| { let frame = layout::card(ui, view.active, view.alert); - let inner = vec2(ui.available_width() - 20.0, CARD_H - 12.0); + let inner = layout::card_inner(ui, CARD_H); frame.show(ui, |ui| { ui.set_min_size(inner); ui.set_max_size(inner); diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 5086db0..3236ef2 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -1524,11 +1524,11 @@ impl RepertoireUi { let name = self.selected_name(); let mut chosen = None; layout::fixed_block(ui, CARD_H, |ui| { - let inner = vec2(ui.available_width() - 20.0, CARD_H - 12.0); + let inner = layout::card_inner(ui, CARD_H); layout::card(ui, false, false).show(ui, |ui| { ui.set_min_size(inner); ui.set_max_size(inner); - ui.spacing_mut().item_spacing.y = 7.0; + ui.spacing_mut().item_spacing.y = 6.0; let width = ui.available_width(); // 1. The name and the colour. layout::fixed_block(ui, 26.0, |ui| { @@ -1564,16 +1564,19 @@ impl RepertoireUi { layout::fixed_block(ui, 30.0, |ui| { ui.horizontal(|ui| { let (label, enabled, item) = main_button(&state, side); - let third = matches!(state, CardState::OnlyNew { .. }); let gap = ui.spacing().item_spacing.x; + let pad = 2.0 * ui.spacing().button_padding.x + 2.0; let room = ui.available_width(); - let (main_w, lines_w, third_w) = - if MAIN_W + LINES_W + THIRD_W + 2.0 * gap <= room || !third { - (MAIN_W, LINES_W, THIRD_W) - } else { - let rest = ((room - MAIN_W - 2.0 * gap) / 2.0).max(60.0); - (MAIN_W.min(room / 2.0), rest, rest) - }; + let main_w = MAIN_W.min((room - LINES_W - gap).max(0.0)); + // Buttons are never cut: in a narrow panel the third one (always + // in the `⋯` menu too) stays out. + let third_need = text_width(ui, tr("Review all"), 14.0) + pad; + let lines_w = LINES_W.min(text_width(ui, tr("Lines…"), 14.0) + pad + 12.0); + let third_w = room - main_w - lines_w - 2.0 * gap; + let third = + matches!(state, CardState::OnlyNew { .. }) && third_w >= third_need; + let lines_w = if third { lines_w } else { LINES_W }; + let third_w = third_w.min(THIRD_W.max(third_need)); let response = ui .add_enabled_ui(enabled, |ui| { crate::widgets::primary_wide(ui, &label, main_w) @@ -1601,10 +1604,11 @@ impl RepertoireUi { if third && ui .add( - egui::Button::new(tr("Review all lines")) + egui::Button::new(tr("Review all")) .truncate() .min_size(vec2(third_w, 30.0)), ) + .on_hover_text(tr("Review all lines")) .clicked() { chosen = Some(MenuItem::ReviewAll); From 22aedf90110c10b381e78448ee5dfafb3607158b Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:47:23 +0300 Subject: [PATCH 07/31] docs: handoff state 2026-11-27, review notes --- docs/dev/opening-trainer-v2-handoff.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/dev/opening-trainer-v2-handoff.md b/docs/dev/opening-trainer-v2-handoff.md index 0874c5b..99e715e 100644 --- a/docs/dev/opening-trainer-v2-handoff.md +++ b/docs/dev/opening-trainer-v2-handoff.md @@ -35,3 +35,23 @@ сравнение с экраном партии/игры, отсутствие скачков. 5. Исправления → обновить `docs/dev/tasks.md` (задача 37/новая), `docs/decisions.md`, CHANGELOG. 6. Интеграция: перенести временные стрелки; слияние в main — только с разрешения владельца. + +## Состояние на 2026-11-27 (оркестратор) + +- Коммиты разработчика после handoff: `8a94d08` (показ нового хода записывается только вместе с сыгранным ходом), + `d54e359` (рамки карточек, кнопки не обрезаются, путь обрезается слева, нет стрелки после остановки). + Сессия разработчика оборвалась на дневном лимите ключа OpenRouter. +- Проверено оркестратором: `cargo fmt --check` — ок; `cargo clippy --workspace --all-targets -D warnings` — ок; + `cargo test -p trainer` — 200 passed; `cargo test -p chesspenguin` — 157 passed, 1 failed + (`review_engine::…stockfish_19…` — ищет `fake_uci` в `../../target/debug`, не в CARGO_TARGET_DIR; к разделу не относится, + перед финалом собрать `cargo build -p uci --bin fake_uci` в штатный target и перепроверить); + `cargo check -p mobile-api` — ок; wasm-проверка не выполнена: на ноутбуке нет `wasm32-unknown-unknown`. + Вне раздела изменены только `lib.rs` (модули) и `widgets.rs` (+32 строки, только добавление). +- Предварительный просмотр снимков разработчика (`target/qa-opening-v2/dev-shots/`), к исправлению: + 1. `s2-new` → `s5-wrong`: счётчик «осталось» 10 → 20 после одной ошибки на первом ходу — проверить, что ошибка + возвращает один ход, а не всю порцию; если счётчик верен, текст должен объяснять рост. + 2. `s8-done`: «Следующее повторение — сегодня, ещё 10» непонятно; при оставшихся новых писать «Новых ходов + осталось: 10», а дату следующего повторения — отдельно (завтра/дата). + 3. `s8-done`: на итоге одновременно «К репертуарам (Enter)» и «× Закончить» — лишнее, «Закончить» скрыть на итоге. + 4. Старые неиспользуемые строки i18n не удалены (i18n +1338/−13). +- Далее: исправить 1–4 → дизайн-ревью designer по §9 спецификации (1400×900, 960×600, светлая тема, переходы). From a5b07e9409d2b59106fbe4b725a984164176226e Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:51:22 +0300 Subject: [PATCH 08/31] opening trainer: starter repertoires (Spanish for White, Najdorf for Black) on the first opening --- .../assets/repertoires/sicilian-black.pgn | 11 +++ .../assets/repertoires/spanish-white.pgn | 13 ++++ apps/desktop/src/i18n.rs | 22 ++++++ apps/desktop/src/repertoire_ui.rs | 69 ++++++++++++++++++- apps/desktop/src/repertoire_ui_tests.rs | 40 +++++++++++ 5 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/assets/repertoires/sicilian-black.pgn create mode 100644 apps/desktop/assets/repertoires/spanish-white.pgn diff --git a/apps/desktop/assets/repertoires/sicilian-black.pgn b/apps/desktop/assets/repertoires/sicilian-black.pgn new file mode 100644 index 0000000..a050f88 --- /dev/null +++ b/apps/desktop/assets/repertoires/sicilian-black.pgn @@ -0,0 +1,11 @@ +[Event "ChessPenguin: Sicilian Najdorf for Black"] +[White "?"] +[Black "Repertoire"] +[Result "*"] +[ECO "B90"] + +{Sicilian Defence, Najdorf Variation for Black, with answers to 6.Be3, 6.Bg5 and the Alapin 2.c3.} +1. e4 c5 2. Nf3 (2. c3 {Alapin Variation.} 2... Nf6 3. e5 Nd5 4. d4 cxd4 5. Nf3 Nc6 6. cxd4 d6 {Black attacks the e5 pawn at once.}) +2... d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 {The Najdorf: ...a6 controls b5 and prepares ...e5 or ...b5.} +6. Be3 (6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 {Black keeps the position solid and prepares ...b5.}) +6... e5 7. Nb3 Be6 8. f3 Be7 9. Qd2 O-O 10. O-O-O Nbd7 11. g4 b5 {English Attack: both sides race on opposite wings.} * diff --git a/apps/desktop/assets/repertoires/spanish-white.pgn b/apps/desktop/assets/repertoires/spanish-white.pgn new file mode 100644 index 0000000..c1d8739 --- /dev/null +++ b/apps/desktop/assets/repertoires/spanish-white.pgn @@ -0,0 +1,13 @@ +[Event "ChessPenguin: Spanish Opening for White"] +[White "Repertoire"] +[Black "?"] +[Result "*"] +[ECO "C84"] + +{Spanish Opening (Ruy Lopez) for White: the Closed main line, the Marshall Attack and the Berlin Defence.} +1. e4 e5 2. Nf3 Nc6 3. Bb5 {The Spanish bishop pressures the knight that defends e5.} +3... a6 (3... Nf6 {Berlin Defence.} 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 +8. Qxd8+ Kxd8 {The Berlin endgame: White has the healthier pawn majority.}) +4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 (7... O-O 8. c3 d5 {Marshall Attack.} +9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 {White returns material later if needed, but keeps the extra pawn for now.}) +8. c3 O-O 9. h3 {Stops ...Bg4 and prepares d4.} 9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 {Chigorin Variation: the knight heads for f1 and g3.} * diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index b5e6efd..70dd1c9 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -18015,6 +18015,28 @@ const ROWS: &[[&str; 9]] = &[ "Bo‘sh repertuar yarating yoki PGN import qiling. Shuningdek, istalgan partiyada yurishni tanlab “Repertuariga qo‘shish…”ni tanlashingiz mumkin.", "Бос репертуар жасаңыз немесе PGN импорттаңыз. Сондай-ақ, кез келген партияда жүрісті таңдап, «Репертуарға қосу…» таңдауыңызға болады.", ], + [ + "Spanish Opening", + "Испанская партия", + "Partie espagnole", + "Spanische Partie", + "Apertura española", + "Partita spagnola", + "Abertura Espanhola", + "Ispan o'yini", + "Испан партиясы", + ], + [ + "Sicilian Defence: Najdorf", + "Сицилианская защита: Найдорф", + "Défense sicilienne : Najdorf", + "Sizilianische Verteidigung: Najdorf", + "Defensa siciliana: Najdorf", + "Difesa siciliana: Najdorf", + "Defesa Siciliana: Najdorf", + "Sitsiliya himoyasi: Naydorf", + "Сицилия қорғанысы: Найдорф", + ], [ "New repertoire", "Новый репертуар", diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 3236ef2..c2aadfa 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -292,12 +292,21 @@ pub struct RepertoireUi { debug_start: Option, debug_pending_moves: Option, debug_menu: bool, + /// Colours of the starter repertoires created on the first opening, written to the + /// settings by the next `show`. + starter_sides: Vec<(RepertoireId, LearningSide)>, } impl RepertoireUi { pub fn new() -> Self { let (library_store, learning_store) = stores(); - Self::with_stores(library_store, learning_store) + let starter = seed_starter(&library_store); + let mut this = Self::with_stores(library_store, learning_store); + match starter { + Ok(sides) => this.starter_sides = sides, + Err(error) => this.show_message(error, true), + } + this } fn with_stores(library_store: LibraryStore, learning_store: LearningStore) -> Self { @@ -341,6 +350,7 @@ impl RepertoireUi { debug_start: None, debug_pending_moves: None, debug_menu: false, + starter_sides: Vec::new(), }; this.selected = this.sorted_ids().first().cloned(); this.reindex(); @@ -1075,6 +1085,12 @@ impl RepertoireUi { pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec { self.poll(settings); let mut actions = Vec::new(); + if !self.starter_sides.is_empty() { + for (id, side) in self.starter_sides.drain(..) { + layout::set_side(settings, &id, side); + } + actions.push(RepertoireAction::SettingsChanged); + } let available = ui.available_rect_before_wrap(); let background = ui.visuals().window_fill(); ui.painter_at(available) @@ -2798,6 +2814,57 @@ fn read_import( }) } +const STARTER_REPERTOIRES: [(&str, &str, LearningSide); 2] = [ + ( + "Spanish Opening", + include_str!("../assets/repertoires/spanish-white.pgn"), + LearningSide::White, + ), + ( + "Sicilian Defence: Najdorf", + include_str!("../assets/repertoires/sicilian-black.pgn"), + LearningSide::Black, + ), +]; + +/// The first opening of the section, before any repertoire library file exists, gets +/// two example repertoires. An existing file, even an empty one, is never touched, so +/// examples deleted by the user do not come back. +fn seed_starter(store: &LibraryStore) -> Result, String> { + if store.path().exists() { + return Ok(Vec::new()); + } + let mut library = Library::default(); + let mut sides = Vec::new(); + let cancel = AtomicBool::new(false); + for (name, pgn, side) in STARTER_REPERTOIRES { + let db = PgnDatabase::from_bytes(pgn.as_bytes().to_vec(), None, &mut |_| {}, &cancel) + .map_err(|e| e.to_string())?; + let mut id = None; + for index in 0..db.len() { + let Some(parsed) = db.load_game(index) else { + continue; + }; + let current = match &id { + Some(id) => id, + None => id.insert( + library + .create(tr(name), &Game::from_start(parsed.game.start().clone())) + .map_err(|e| e.to_string())?, + ), + }; + library + .add_game(current, &parsed.game) + .map_err(|e| e.to_string())?; + } + if let Some(id) = id { + sides.push((id, side)); + } + } + store.save(&mut library).map_err(|e| e.to_string())?; + Ok(sides) +} + fn load_library(store: &LibraryStore) -> Result { let mut library = store.load().map_err(|error| error.to_string())?; // The depth limit of 2.2 is not a user's choice: trained lines go to their ends. diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index a2611ab..fee0c71 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -525,3 +525,43 @@ fn a_session_needs_no_question_to_go_back_and_counts_refresh_after_it() { let stats = ui.stats.get(&id).unwrap().as_ref().unwrap(); assert_eq!((stats.unseen, stats.due), (2, 1)); } + +#[test] +fn starter_repertoires_are_created_once_with_their_colours() { + let dir = TestDir::new("starter"); + let (store, _) = dir.stores(); + let sides = seed_starter(&store).unwrap(); + let library = store.load().unwrap(); + assert_eq!(library.repertoires.len(), 2); + assert_eq!( + sides.iter().map(|(_, side)| *side).collect::>(), + [LearningSide::White, LearningSide::Black] + ); + for ((id, _), lines) in sides.iter().zip([3, 3]) { + let repertoire = library.repertoire(id).unwrap(); + assert_eq!(layout::lines(&repertoire.game(), |_| false).len(), lines); + } + assert_eq!(library.repertoires[0].name, "Spanish Opening"); + assert_eq!(library.repertoires[1].name, "Sicilian Defence: Najdorf"); + + let mut settings = Settings::default(); + let mut ui = dir.ui(); + ui.starter_sides = sides; + egui::__run_test_ui(|egui_ui| { + ui.show(egui_ui, &mut settings); + }); + let black = &library.repertoires[1].id; + assert_eq!(layout::side_of(&settings, black), LearningSide::Black); + + assert!(seed_starter(&store).unwrap().is_empty()); + assert_eq!(store.load().unwrap().repertoires.len(), 2); +} + +#[test] +fn starter_repertoires_do_not_return_to_an_existing_library() { + let dir = TestDir::new("starter-existing"); + let (store, _) = dir.stores(); + store.save(&mut Library::default()).unwrap(); + assert!(seed_starter(&store).unwrap().is_empty()); + assert!(store.load().unwrap().repertoires.is_empty()); +} From e1ea994da4ce7b8724fca0d183d9883431ab1c87 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:55:43 +0300 Subject: [PATCH 09/31] =?UTF-8?q?opening=20session:=20test=20that=20a=20fi?= =?UTF-8?q?rst-move=20mistake=20returns=20once=20and=20keeps=20the=20count?= =?UTF-8?q?=20(10=20=E2=86=92=2020=20is=20the=20next=20session:=2010=20lea?= =?UTF-8?q?rned=20moves=20due=20today=20+=2010=20new)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/opening_session_tests.rs | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index 7515ab2..13f8d31 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -2167,3 +2167,42 @@ fn async_failed_commit_preserves_event_for_retry_without_double_counting() { assert_eq!(f.attempts().len(), 1); assert_eq!(f.attempts()[0].client_attempt_id, "async-retry"); } + +#[test] +fn a_mistake_on_the_first_move_returns_it_once_and_keeps_the_count() { + // The next daily session after learning new moves: the learned e4 is due again + // today, Nf3 and Bb5 are still new. The count is due + new, and a mistake on the + // first move does not grow it. + let pgn = "1. e4 e5 2. Nf3 Nc6 3. Bb5 *"; + let mut f = Fixture::with( + pgn, + LearningSide::White, + &["e2e4"], + &["g1f3", "f1b5"], + "first-move-wrong", + SessionKind::Daily, + ); + let at = Instant::now(); + assert_eq!(f.ui.session.remaining(), 3); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + assert_eq!(f.ui.session.current_expected_uci(), Some("e2e4")); + assert!(f.ui.play_uci_with_id_at("d2d4", "e4-wrong".into(), at, NOW)); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.state(), Some(State::Wrong)); + assert_eq!(f.ui.session.remaining(), 3); + answer_current(&mut f, at + WRONG_SHOWN, NOW, "e4-replay"); + assert_eq!(f.ui.session.remaining(), 3); + let mut asked = Vec::new(); + for _ in 0..4 { + f.ui.debug_settle(); + let Some(uci) = f.ui.session.current_expected_uci().map(str::to_owned) else { + break; + }; + answer_current(&mut f, at, NOW, &format!("again-{uci}-{}", asked.len())); + asked.push(uci); + } + f.ui.debug_settle(); + assert!(f.ui.is_finished()); + assert_eq!(asked, ["g1f3", "f1b5", "e2e4"]); + assert_eq!(f.ui.session.remaining(), 0); +} From a9fc7b98fe9488ee6f01a257c6b3a55055108b40 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:57:37 +0300 Subject: [PATCH 10/31] =?UTF-8?q?opening=20session:=20summary=20shows=20ne?= =?UTF-8?q?w=20moves=20left=20and=20the=20next=20review=20separately;=20no?= =?UTF-8?q?=20=C2=AB=C3=97=20Finish=C2=BB=20on=20the=20summary?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/i18n.rs | 29 +++++++++++----- apps/desktop/src/opening_session.rs | 42 +++++++++++++---------- apps/desktop/src/opening_session_tests.rs | 3 ++ 3 files changed, 46 insertions(+), 28 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 70dd1c9..da94988 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -811,15 +811,26 @@ const ROWS: &[[&str; 9]] = &[ "Тармақ: {path}", ], [ - "today, {n} more", - "сегодня, ещё {n}", - "aujourd’hui, encore {n}", - "heute, noch {n}", - "hoy, {n} más", - "oggi, altre {n}", - "hoje, mais {n}", - "bugun, yana {n} ta", - "бүгін, тағы {n}", + "New moves left", + "Новых ходов осталось", + "Nouveaux coups restants", + "Neue Züge übrig", + "Jugadas nuevas restantes", + "Mosse nuove rimaste", + "Lances novos restantes", + "Qolgan yangi yurishlar", + "Қалған жаңа жүрістер", + ], + [ + "nothing scheduled", + "нет запланированных", + "rien de prévu", + "nichts geplant", + "nada programado", + "niente in programma", + "nada agendado", + "rejalashtirilmagan", + "жоспарланған жоқ", ], [ "{k} of {n}", diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index 6d5a174..425e372 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -210,6 +210,8 @@ enum State { /// Computed once when the result is shown. struct Summary { next_review: String, + /// Moves never shown yet, all of them (the «more new» button takes up to 10). + unseen: usize, more_new: usize, } @@ -1597,30 +1599,26 @@ impl OpeningSessionUi { .iter() .map(|item| (&item.key, item)) .collect(); - let today = layout::end_of_today(); let now = layout::now(); - let mut due_today = 0usize; let mut next: Option = None; let mut unseen = 0usize; for key in &self.repertoire_keys { match items.get(key) { Some(item) if item.introduced => { - if item.is_due(today) { - due_today += 1; - } else if let Some(at) = item.next_review_at { + if let Some(at) = item.next_review_at { next = Some(next.map_or(at, |old| old.min(at))); } } _ => unseen += 1, } } - let next_review = if due_today > 0 { - trf("today, {n} more", &[("n", &due_today)]) - } else { - next.map(|at| layout::when(at, now)).unwrap_or_default() + let next_review = match next { + Some(at) => layout::when(at.max(now), now), + None => tr("nothing scheduled").to_owned(), }; self.summary = Some(Summary { next_review, + unseen, more_new: unseen.min(layout::NEW_PER_SESSION), }); } @@ -1903,9 +1901,10 @@ impl OpeningSessionUi { ui.add_space(4.0); ui.separator(); ui.add_space(4.0); - if let Some(summary) = &self.summary - && !summary.next_review.is_empty() - { + if let Some(summary) = &self.summary { + if self.kind == SessionKind::Daily && summary.unseen > 0 { + row(ui, tr("New moves left"), summary.unseen.to_string()); + } row(ui, tr("Next review"), summary.next_review.clone()); } if self.tally.missed.is_empty() { @@ -2007,6 +2006,8 @@ impl OpeningSessionUi { left, right, *state == State::Summary || matches!(state, State::SaveError(_)), + // The summary has its own way out; «× Finish» there would be a second one. + *state != State::Summary, ); match clicked { Some(Clicked::Left) => match state { @@ -2222,6 +2223,7 @@ pub fn show_preparing( Some((tr("Hint (H)").to_owned(), false)), None, false, + true, ); if clicked == Some(Clicked::Finish) { actions.push(SessionAction::Back); @@ -2321,6 +2323,7 @@ fn side_panel( left: Option<(String, bool)>, right: Option<(String, bool)>, right_primary: bool, + finish: bool, ) -> Option { let mut clicked = None; let rect = ui.available_rect_before_wrap(); @@ -2391,13 +2394,14 @@ fn side_panel( clicked = Some(Clicked::Flip); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui - .add( - egui::Button::new(RichText::new(tr("× Finish")).size(14.0)) - .min_size(vec2(0.0, TOOL_H)), - ) - .on_hover_text(tr("Finish the session (Esc)")) - .clicked() + if finish + && ui + .add( + egui::Button::new(RichText::new(tr("× Finish")).size(14.0)) + .min_size(vec2(0.0, TOOL_H)), + ) + .on_hover_text(tr("Finish the session (Esc)")) + .clicked() { clicked = Some(Clicked::Finish); } diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index 13f8d31..0b51aa8 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -2205,4 +2205,7 @@ fn a_mistake_on_the_first_move_returns_it_once_and_keeps_the_count() { assert!(f.ui.is_finished()); assert_eq!(asked, ["g1f3", "f1b5", "e2e4"]); assert_eq!(f.ui.session.remaining(), 0); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!((summary.unseen, summary.more_new), (0, 0)); + assert!(!summary.next_review.is_empty()); } From 9a26290b9326adba575004e853e40d74718e0b2f Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:57:49 +0300 Subject: [PATCH 11/31] opening session: the summary test computes the summary --- apps/desktop/src/opening_session_tests.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index 0b51aa8..5d70016 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -1423,6 +1423,7 @@ fn a_daily_session_brings_mistakes_and_hints_back_and_its_numbers_agree() { // e4 wrong, e4 right, Nf3 right, Bb5 right. assert_eq!(independent, 4); f.ui.compute_summary(); + f.ui.compute_summary(); let summary = f.ui.summary.as_ref().unwrap(); assert_eq!(summary.more_new, 0); assert!(!summary.next_review.is_empty()); @@ -2205,6 +2206,7 @@ fn a_mistake_on_the_first_move_returns_it_once_and_keeps_the_count() { assert!(f.ui.is_finished()); assert_eq!(asked, ["g1f3", "f1b5", "e2e4"]); assert_eq!(f.ui.session.remaining(), 0); + f.ui.compute_summary(); let summary = f.ui.summary.as_ref().unwrap(); assert_eq!((summary.unseen, summary.more_new), (0, 0)); assert!(!summary.next_review.is_empty()); From 04af686dfc31dbf124725909e5dac2eff931542e Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 01:59:14 +0300 Subject: [PATCH 12/31] i18n: drop 202 strings of the removed training section --- apps/desktop/src/i18n.rs | 2222 -------------------------------------- 1 file changed, 2222 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index da94988..fedcf03 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1558,116 +1558,6 @@ const ROWS: &[[&str; 9]] = &[ "{n}-partiyada yurishlar yo‘q", "{n}-партияда жүріс жоқ", ], - [ - "Your turn: play a repertoire move.", - "Ваш ход: сыграйте ход из репертуара.", - "À vous : jouez un coup du répertoire.", - "Sie sind am Zug: Spielen Sie einen Repertoirezug.", - "Tu turno: juega una jugada del repertorio.", - "Tocca a te: gioca una mossa del repertorio.", - "Sua vez: jogue um lance do repertório.", - "Sizning navbatingiz: repertuardan yurish qiling.", - "Сіздің кезегіңіз: репертуардағы жүрісті жасаңыз.", - ], - [ - "Repertoire answers remaining here: {count}", - "Осталось ответов репертуара в этой позиции: {count}", - "Réponses du répertoire restantes ici : {count}", - "Verbleibende Repertoireantworten in dieser Stellung: {count}", - "Respuestas del repertorio pendientes aquí: {count}", - "Risposte del repertorio rimanenti qui: {count}", - "Respostas do repertório restantes aqui: {count}", - "Bu pozitsiyada qolgan repertuar javoblari: {count}", - "Осы позицияда қалған репертуар жауаптары: {count}", - ], - [ - "This repertoire move has already been reviewed in this session.", - "Этот ход репертуара уже повторён в этой сессии.", - "Ce coup du répertoire a déjà été révisé pendant cette séance.", - "Dieser Repertoirezug wurde in dieser Sitzung bereits wiederholt.", - "Esta jugada del repertorio ya se ha repasado en esta sesión.", - "Questa mossa del repertorio è già stata ripassata in questa sessione.", - "Este lance do repertório já foi revisado nesta sessão.", - "Bu repertuar yurishi ushbu mashg‘ulotda allaqachon takrorlangan.", - "Бұл репертуар жүрісі осы жаттығуда қайталанған.", - ], - [ - "This move is in your repertoire, but is not a task in this session.", - "Этот ход есть в репертуаре, но не входит в задания этой сессии.", - "Ce coup figure dans votre répertoire, mais ne fait pas partie des exercices de cette séance.", - "Dieser Zug gehört zum Repertoire, ist aber keine Aufgabe dieser Sitzung.", - "Esta jugada está en tu repertorio, pero no es una tarea de esta sesión.", - "Questa mossa è nel repertorio, ma non è un esercizio di questa sessione.", - "Este lance está no seu repertório, mas não é uma tarefa desta sessão.", - "Bu yurish repertuaringizda bor, lekin ushbu mashg‘ulot topshirig‘i emas.", - "Бұл жүріс репертуарда бар, бірақ осы жаттығудың тапсырмасына кірмейді.", - ], - [ - "Preferred move", - "Предпочтительный ход", - "Coup préféré", - "Bevorzugter Zug", - "Jugada preferida", - "Mossa preferita", - "Lance preferido", - "Afzal yurish", - "Таңдаулы жүріс", - ], - [ - "Prefer this move", - "Предпочитать этот ход", - "Préférer ce coup", - "Diesen Zug bevorzugen", - "Preferir esta jugada", - "Preferisci questa mossa", - "Preferir este lance", - "Bu yurishni afzal ko‘rish", - "Осы жүрісті таңдаулы ету", - ], - [ - "PGN order", - "Порядок из PGN", - "Ordre du PGN", - "PGN-Reihenfolge", - "Orden del PGN", - "Ordine del PGN", - "Ordem do PGN", - "PGN tartibi", - "PGN реті", - ], - [ - "All enabled variations are trained. The preferred move only affects their order.", - "Изучаются все включённые варианты. Предпочтительный ход влияет только на порядок.", - "Toutes les variantes activées sont étudiées. Le coup préféré ne change que leur ordre.", - "Alle aktivierten Varianten werden trainiert. Der bevorzugte Zug beeinflusst nur ihre Reihenfolge.", - "Se entrenan todas las variantes habilitadas. La jugada preferida solo cambia su orden.", - "Si studiano tutte le varianti attive. La mossa preferita ne cambia solo l’ordine.", - "Todas as variantes ativadas são treinadas. O lance preferido só altera a ordem.", - "Barcha yoqilgan variantlar o‘rganiladi. Afzal yurish faqat ularning tartibiga ta’sir qiladi.", - "Барлық қосылған нұсқалар үйретіледі. Таңдаулы жүріс тек олардың ретіне әсер етеді.", - ], - [ - "preferred", - "предпочтительный", - "préféré", - "bevorzugt", - "preferida", - "preferita", - "preferido", - "afzal", - "таңдаулы", - ], - [ - "No learning data for this move", - "Для этого хода нет данных обучения", - "Aucune donnée d’apprentissage pour ce coup", - "Keine Lerndaten für diesen Zug", - "No hay datos de aprendizaje para esta jugada", - "Nessun dato di apprendimento per questa mossa", - "Sem dados de aprendizagem para este lance", - "Bu yurish uchun o‘rganish ma’lumotlari yo‘q", - "Бұл жүріске арналған оқу деректері жоқ", - ], [ "Checking access to Lichess and Chess.com…", "Проверяем доступность Lichess и Chess.com…", @@ -1679,17 +1569,6 @@ const ROWS: &[[&str; 9]] = &[ "Lichess va Chess.com mavjudligi tekshirilmoqda…", "Lichess пен Chess.com қолжетімділігі тексерілуде…", ], - [ - "Exit", - "Выйти", - "Quitter", - "Verlassen", - "Salir", - "Esci", - "Sair", - "Chiqish", - "Шығу", - ], [ "Saving progress…", "Сохранение прогресса…", @@ -1701,83 +1580,6 @@ const ROWS: &[[&str; 9]] = &[ "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", "Тренироваться", @@ -1789,72 +1591,6 @@ const ROWS: &[[&str; 9]] = &[ "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", "Учить новые", @@ -1866,160 +1602,6 @@ const ROWS: &[[&str; 9]] = &[ "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.", @@ -17894,17 +17476,6 @@ const ROWS: &[[&str; 9]] = &[ "Faqat boshlang‘ichdan shu yurishgacha bo‘lgan yo‘lni izohlar va NAG bilan qo‘shish", "Тек басынан осы жүріске дейінгі жолды түсініктемелері мен NAG арқылы қосу", ], - [ - "Repertoire not found", - "Репертуар не найден", - "Répertoire introuvable", - "Repertoire nicht gefunden", - "Repertorio no encontrado", - "Repertorio non trovato", - "Repertório não encontrado", - "Repertuar topilmadi", - "Репертуар табылмады", - ], [ "No enabled moves in this repertoire", "В репертуаре нет включённых ходов", @@ -17949,28 +17520,6 @@ const ROWS: &[[&str; 9]] = &[ "PGN eksport…", "PGN экспорт…", ], - [ - "← Databases", - "← Базы", - "← Bases de données", - "← Datenbanken", - "← Bases de datos", - "← Database", - "← Bases de dados", - "← Bazalar", - "← Базалар", - ], - [ - "+ Create", - "+ Создать", - "+ Créer", - "+ Erstellen", - "+ Crear", - "+ Crea", - "+ Criar", - "+ Yaratish", - "+ Жасау", - ], [ "Repertoires", "Репертуары", @@ -18015,17 +17564,6 @@ const ROWS: &[[&str; 9]] = &[ "Hozircha repertuarlar yo‘q", "Әзірге репертуар жоқ", ], - [ - "Create an empty one or import PGN. You can also select a move in any game and choose “Add to repertoire…”.", - "Создайте пустой или импортируйте PGN. Можно также выбрать ход в любой партии и нажать «Добавить в репертуар…».", - "Créez un répertoire vide ou importez un PGN. Vous pouvez aussi sélectionner un coup dans une partie et choisir « Ajouter au répertoire… ».", - "Erstellen Sie ein leeres Repertoire oder importieren Sie PGN. Sie können auch in einer Partie einen Zug wählen und „Zum Repertoire hinzufügen…“ wählen.", - "Crea uno vacío o importa PGN. También puedes seleccionar una jugada en cualquier partida y elegir «Añadir al repertorio…».", - "Crea un repertorio vuoto o importa un PGN. Puoi anche selezionare una mossa in una partita e scegliere «Aggiungi al repertorio…».", - "Crie um vazio ou importe PGN. Também pode selecionar um lance em qualquer partida e escolher “Adicionar ao repertório…”.", - "Bo‘sh repertuar yarating yoki PGN import qiling. Shuningdek, istalgan partiyada yurishni tanlab “Repertuariga qo‘shish…”ni tanlashingiz mumkin.", - "Бос репертуар жасаңыз немесе PGN импорттаңыз. Сондай-ақ, кез келген партияда жүрісті таңдап, «Репертуарға қосу…» таңдауыңызға болады.", - ], [ "Spanish Opening", "Испанская партия", @@ -18103,28 +17641,6 @@ const ROWS: &[[&str; 9]] = &[ "Ikkala tomon", "Екі тарап", ], - [ - "Variants", - "Варианты", - "Variantes", - "Varianten", - "Variantes", - "Varianti", - "Variantes", - "Variantlar", - "Варианттар", - ], - [ - "No targets in this mode", - "В этом режиме нет целей", - "Aucune cible dans ce mode", - "Keine Ziele in diesem Modus", - "No hay objetivos en este modo", - "Nessun obiettivo in questa modalità", - "Não há objetivos neste modo", - "Bu rejimda maqsadlar yo‘q", - "Бұл режимде мақсаттар жоқ", - ], [ "This mode has not been used yet", "Этот режим ещё не использовался", @@ -18147,17 +17663,6 @@ const ROWS: &[[&str; 9]] = &[ "Takrorlash", "Қайталау", ], - [ - "Import PGN into this repertoire…", - "Импортировать PGN в этот репертуар…", - "Importer un PGN dans ce répertoire…", - "PGN in dieses Repertoire importieren…", - "Importar PGN en este repertorio…", - "Importa PGN in questo repertorio…", - "Importar PGN para este repertório…", - "Bu repertuarga PGN import qilish…", - "Бұл репертуарға PGN импорттау…", - ], [ "Delete…", "Удалить…", @@ -18246,39 +17751,6 @@ const ROWS: &[[&str; 9]] = &[ "← Repertuarlar", "← Репертуарлар", ], - [ - "Importing PGN…", - "Импорт PGN…", - "Import du PGN…", - "PGN wird importiert…", - "Importando PGN…", - "Importazione PGN…", - "Importando PGN…", - "PGN import qilinmoqda…", - "PGN импортталуда…", - ], - [ - "Indexing variations and ECO names…", - "Индексация вариантов и названий ECO…", - "Indexation des variantes et des noms ECO…", - "Varianten und ECO-Namen werden indiziert…", - "Indexando variantes y nombres ECO…", - "Indicizzazione di varianti e nomi ECO…", - "Indexando variantes e nomes ECO…", - "Variantlar va ECO nomlari indekslanmoqda…", - "Варианттар мен ECO атаулары индекстелуде…", - ], - [ - "Preparing the training session…", - "Подготовка тренировки…", - "Préparation de l’entraînement…", - "Training wird vorbereitet…", - "Preparando el entrenamiento…", - "Preparazione dell’allenamento…", - "Preparando o treino…", - "Mashg‘ulot tayyorlanmoqda…", - "Жаттығу дайындалуда…", - ], [ "Start over", "Начать заново", @@ -18290,17 +17762,6 @@ const ROWS: &[[&str; 9]] = &[ "Qaytadan boshlash", "Қайта бастау", ], - [ - "Mode", - "Режим", - "Mode", - "Modus", - "Modo", - "Modalità", - "Modo", - "Rejim", - "Режим", - ], [ "Queue", "Очередь", @@ -18323,17 +17784,6 @@ const ROWS: &[[&str; 9]] = &[ "Yo‘l navbatlari joriy yadro API sida mavjud emas", "Жол кезектері ағымдағы ядро API-інде жоқ", ], - [ - "Depth", - "Глубина", - "Profondeur", - "Tiefe", - "Profundidad", - "Profondità", - "Profundidade", - "Chuqurlik", - "Тереңдік", - ], [ "half-moves", "полуходов", @@ -18356,17 +17806,6 @@ const ROWS: &[[&str; 9]] = &[ "Cheksiz", "Шектеусіз", ], - [ - "Scope: whole repertoire", - "Область: весь репертуар", - "Zone : tout le répertoire", - "Bereich: gesamtes Repertoire", - "Ámbito: todo el repertorio", - "Ambito: tutto il repertorio", - "Âmbito: todo o repertório", - "Hudud: butun repertuar", - "Аймақ: бүкіл репертуар", - ], [ "Start branch run", "Начать проход веток", @@ -18400,17 +17839,6 @@ const ROWS: &[[&str; 9]] = &[ "Daraxt", "Ағаш", ], - [ - "Statistics", - "Статистика", - "Statistiques", - "Statistik", - "Estadísticas", - "Statistiche", - "Estatísticas", - "Statistika", - "Статистика", - ], [ "Enable for training", "Вернуть в тренировку", @@ -18510,17 +17938,6 @@ const ROWS: &[[&str; 9]] = &[ "Filtr", "Сүзгі", ], - [ - "Unseen", - "Новый", - "Nouveau", - "Neu", - "Nuevo", - "Nuovo", - "Novo", - "Yangi", - "Жаңа", - ], [ "With mistakes", "С ошибками", @@ -18532,28 +17949,6 @@ const ROWS: &[[&str; 9]] = &[ "Xatolar bilan", "Қателермен", ], - [ - "Attempts", - "Попытки", - "Tentatives", - "Versuche", - "Intentos", - "Tentativi", - "Tentativas", - "Urinishlar", - "Әрекеттер", - ], - [ - "Correct", - "Верных", - "Corrects", - "Richtig", - "Correctas", - "Corrette", - "Corretos", - "To‘g‘ri", - "Дұрыс", - ], [ "Wrong", "Неверных", @@ -18664,17 +18059,6 @@ const ROWS: &[[&str; 9]] = &[ "Statistikani o‘qib bo‘lmadi: {error}. Fayl almashtirilmadi", "Статистиканы оқу мүмкін емес: {error}. Файл ауыстырылмады", ], - [ - "Could not save changes: {error}", - "Не удалось сохранить изменения: {error}", - "Impossible d’enregistrer les modifications : {error}", - "Änderungen konnten nicht gespeichert werden: {error}", - "No se pudieron guardar los cambios: {error}", - "Impossibile salvare le modifiche: {error}", - "Não foi possível salvar as alterações: {error}", - "O‘zgarishlarni saqlab bo‘lmadi: {error}", - "Өзгерістерді сақтау мүмкін емес: {error}", - ], [ "Reading PGN · records: {n}", "Чтение PGN · записей: {n}", @@ -18917,17 +18301,6 @@ const ROWS: &[[&str; 9]] = &[ "PGN {n}-yozuv: {error}", "PGN {n}-жазба: {error}", ], - [ - "Accepted · it will be repeated sooner", - "Принято · будет повторено раньше", - "Accepté · sera répété plus tôt", - "Angenommen · wird früher wiederholt", - "Aceptado · se repetirá antes", - "Accettato · sarà ripetuto prima", - "Aceito · será revisto mais cedo", - "Qabul qilindi · tezroq takrorlanadi", - "Қабылданды · ертерек қайталанады", - ], [ "× This move is outside the enabled variations", "× Этот ход вне включённых вариантов", @@ -18972,50 +18345,6 @@ const ROWS: &[[&str; 9]] = &[ "Chuqurlik chegarasigacha yoki variant oxirigacha", "Тереңдік шегіне дейін немесе нұсқа аяғына дейін", ], - [ - "With hint", - "С подсказкой", - "Avec indice", - "Mit Hinweis", - "Con pista", - "Con suggerimento", - "Com dica", - "Maslahat bilan", - "Кеңеспен", - ], - [ - "Branch complete", - "Ветка завершена", - "Variante terminée", - "Variante abgeschlossen", - "Variante completada", - "Variante completata", - "Variante concluída", - "Variant yakunlandi", - "Нұсқа аяқталды", - ], - [ - "Training complete", - "Тренировка завершена", - "Entraînement terminé", - "Training abgeschlossen", - "Entrenamiento completado", - "Allenamento completato", - "Treino concluído", - "Mashg‘ulot yakunlandi", - "Жаттығу аяқталды", - ], - [ - "Repeat path", - "Повторить путь", - "Répéter le chemin", - "Pfad wiederholen", - "Repetir la ruta", - "Ripeti percorso", - "Repetir caminho", - "Yo‘lni takrorlash", - "Жолды қайталау", - ], [ "New run", "Новый проход", @@ -19027,72 +18356,6 @@ const ROWS: &[[&str; 9]] = &[ "Yangi o‘tish", "Жаңа өту", ], - [ - "Review in order", - "Подряд", - "Réviser dans l’ordre", - "Der Reihe nach", - "Repasar en orden", - "Ripassa in ordine", - "Revisar em ordem", - "Tartib bilan takrorlash", - "Ретімен қайталау", - ], - [ - "Back to repertoire", - "К репертуару", - "Retour au répertoire", - "Zum Repertoire", - "Volver al repertorio", - "Torna al repertorio", - "Voltar ao repertório", - "Repertuarga qaytish", - "Репертуарға қайту", - ], - [ - "Leave without saving", - "Выйти без сохранения", - "Quitter sans enregistrer", - "Ohne Speichern verlassen", - "Salir sin guardar", - "Esci senza salvare", - "Sair sem salvar", - "Saqlamasdan chiqish", - "Сақтамай шығу", - ], - [ - "Only the events that could not be saved will be discarded", - "Будут отброшены только события, которые не удалось сохранить", - "Seuls les événements qui n’ont pas pu être enregistrés seront abandonnés", - "Nur Ereignisse, die nicht gespeichert werden konnten, werden verworfen", - "Solo se descartarán los eventos que no se pudieron guardar", - "Solo gli eventi che non è stato possibile salvare saranno eliminati", - "Apenas os eventos que não puderam ser salvos serão descartados", - "Faqat saqlab bo‘lmagan hodisalar tashlab yuboriladi", - "Тек сақталмаған оқиғалар алынып тасталған", - ], - [ - "← Back to repertoire", - "← К репертуару", - "← Retour au répertoire", - "← Zum Repertoire", - "← Volver al repertorio", - "← Torna al repertorio", - "← Voltar ao repertório", - "← Repertuarga qaytish", - "← Репертуарға қайту", - ], - [ - "Illegal move in the current position", - "Нелегальный ход в текущей позиции", - "Coup illégal dans la position actuelle", - "Illegaler Zug in der aktuellen Stellung", - "Jugada ilegal en la posición actual", - "Mossa illegale nella posizione attuale", - "Lance ilegal na posição atual", - "Joriy pozitsiyada noqonuniy yurish", - "Ағымдағы позициядағы заңсыз жүріс", - ], [ "Half-moves played: {n}", "Сыграно полуходов: {n}", @@ -19104,17 +18367,6 @@ const ROWS: &[[&str; 9]] = &[ "O‘ynalgan yarim yurishlar: {n}", "Ойналған жарты жүрістер: {n}", ], - [ - "Tasks: {done} of {total}", - "Заданий: {done} из {total}", - "Tâches : {done} sur {total}", - "Aufgaben: {done} von {total}", - "Tareas: {done} de {total}", - "Attività: {done} di {total}", - "Tarefas: {done} de {total}", - "Vazifalar: {done} / {total}", - "Тапсырмалар: {done} / {total}", - ], [ "Half-move {n}", "Полуход {n}", @@ -19126,17 +18378,6 @@ const ROWS: &[[&str; 9]] = &[ "{n}-yarim yurish", "{n}-жарты жүріс", ], - [ - "Task {current} of {total}", - "Задание {current} из {total}", - "Tâche {current} sur {total}", - "Aufgabe {current} von {total}", - "Tarea {current} de {total}", - "Attività {current} di {total}", - "Tarefa {current} de {total}", - "Vazifa {current} / {total}", - "Тапсырма {current} / {total}", - ], [ "Half-moves played: {n} · mistakes: {m}", "Пройдено полуходов: {n} · ошибок: {m}", @@ -19148,28 +18389,6 @@ const ROWS: &[[&str; 9]] = &[ "O‘ynalgan yarim yurishlar: {n} · xatolar: {m}", "Ойналған жарты жүрістер: {n} · қателер: {m}", ], - [ - "Without hint", - "Без подсказки", - "Sans indice", - "Ohne Hinweis", - "Sin pista", - "Senza suggerimento", - "Sem dica", - "Maslahatsiz", - "Кеңессіз", - ], - [ - "Tasks: {n} · correct: {c} · wrong attempts: {w} · with hint: {h}", - "Заданий: {n} · правильных: {c} · неверных попыток: {w} · с подсказкой: {h}", - "Tâches : {n} · correctes : {c} · tentatives incorrectes : {w} · avec indice : {h}", - "Aufgaben: {n} · richtig: {c} · falsche Versuche: {w} · mit Hinweis: {h}", - "Tareas: {n} · correctas: {c} · intentos incorrectos: {w} · con pista: {h}", - "Attività: {n} · corrette: {c} · tentativi sbagliati: {w} · con suggerimento: {h}", - "Tarefas: {n} · corretas: {c} · tentativas incorretas: {w} · com dica: {h}", - "Vazifalar: {n} · to‘g‘ri: {c} · noto‘g‘ri urinishlar: {w} · maslahat bilan: {h}", - "Тапсырмалар: {n} · дұрыс: {c} · қате әрекеттер: {w} · кеңеспен: {h}", - ], [ "Enabled half-moves: {targets} · completed runs: {runs}", "Включено полуходов: {targets} · завершено проходов: {runs}", @@ -19236,17 +18455,6 @@ const ROWS: &[[&str; 9]] = &[ "Oraliq jadval", "Аралық кесте", ], - [ - "Least recent and unseen first", - "Сначала новые и давние", - "D’abord les nouveaux et les moins récents", - "Neue und älteste zuerst", - "Primero nuevas y menos recientes", - "Prima nuove e meno recenti", - "Primeiro novos e menos recentes", - "Avval yangi va eng eski", - "Алдымен жаңа және ескі", - ], [ "Unscheduled", "Вне расписания", @@ -19390,17 +18598,6 @@ const ROWS: &[[&str; 9]] = &[ "· Avtomatik yurish/kontekst", "· Автоматты жүріс/контекст", ], - [ - "Automatic move/context", - "Автоматический ход/контекст", - "Coup/contexte automatique", - "Automatischer Zug/Kontext", - "Jugada/contexto automático", - "Mossa/contesto automatico", - "Lance/contexto automático", - "Avtomatik yurish/kontekst", - "Автоматты жүріс/контекст", - ], [ "Early review · schedule unchanged", "Досрочный обзор · сроки не меняются", @@ -19613,17 +18810,6 @@ const ROWS: &[[&str; 9]] = &[ "PGN faylni tanlang", "PGN файлды таңдаңыз", ], - [ - "← To game", - "← К партии", - "← Vers la partie", - "← Zur Partie", - "← A la partida", - "← Alla partita", - "← Para a partida", - "← Partiyaga", - "← Партияға", - ], [ "Start training", "Начать", @@ -19847,17 +19033,6 @@ const ROWS: &[[&str; 9]] = &[ "Avval yuqori variantni yoqing", "Алдымен жоғарғы нұсқаны қосыңыз", ], - [ - "Cancelled", - "Отменено", - "Annulé", - "Abgebrochen", - "Cancelado", - "Annullato", - "Cancelado", - "Bekor qilindi", - "Бас тартылды", - ], [ "No games", "Нет партий", @@ -19902,17 +19077,6 @@ const ROWS: &[[&str; 9]] = &[ "Yangi yurishlarni qo‘shish", "Жаңа жүрістерді қосу", ], - [ - "New moves", - "Новые ходы", - "Nouveaux coups", - "Neue Züge", - "Nuevas jugadas", - "Nuove mosse", - "Novos lances", - "Yangi yurishlar", - "Жаңа жүрістер", - ], [ "Move statistics", "Статистика хода", @@ -20001,116 +19165,6 @@ const ROWS: &[[&str; 9]] = &[ "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", ], - [ - "This move is not in the enabled repertoire. Try another move or show a hint.", - "Этого хода нет во включённых вариантах. Попробуйте другой или воспользуйтесь подсказкой.", - "This move is not in the enabled repertoire. Try another move or show a hint.", - "Dieser Zug ist in den aktivierten Varianten nicht enthalten. Versuchen Sie einen anderen oder nutzen Sie einen Hinweis.", - "This move is not in the enabled repertoire. Try another move or show a hint.", - "This move is not in the enabled repertoire. Try another move or show a hint.", - "This move is not in the enabled repertoire. Try another move or show a hint.", - "This move is not in the enabled repertoire. Try another move or show a hint.", - "This move is not in the enabled repertoire. Try another move or show a hint.", - ], - [ - "Play both sides. Any enabled move is accepted.", - "Играйте за обе стороны. Любой ход из включённых вариантов принимается.", - "Play both sides. Any enabled move is accepted.", - "Spielen Sie beide Seiten. Jeder Zug aus den aktivierten Varianten wird akzeptiert.", - "Play both sides. Any enabled move is accepted.", - "Play both sides. Any enabled move is accepted.", - "Play both sides. Any enabled move is accepted.", - "Play both sides. Any enabled move is accepted.", - "Play both sides. Any enabled move is accepted.", - ], - [ - "Your turn: play any move from your repertoire. The program will reply.", - "Ваш ход: сыграйте любой ход из репертуара. Затем ответит программа.", - "Your turn: play any move from your repertoire. The program will reply.", - "Sie sind am Zug: Spielen Sie einen beliebigen Repertoirezug. Dann antwortet das Programm.", - "Your turn: play any move from your repertoire. The program will reply.", - "Your turn: play any move from your repertoire. The program will reply.", - "Your turn: play any move from your repertoire. The program will reply.", - "Your turn: play any move from your repertoire. The program will reply.", - "Your turn: play any move from your repertoire. The program will reply.", - ], - [ - "Several continuations are available. Choose the variation you want to practise.", - "Здесь несколько продолжений — выберите вариант, который хотите пройти.", - "Several continuations are available. Choose the variation you want to practise.", - "Hier gibt es mehrere Fortsetzungen. Wählen Sie die Variante, die Sie üben möchten.", - "Several continuations are available. Choose the variation you want to practise.", - "Several continuations are available. Choose the variation you want to practise.", - "Several continuations are available. Choose the variation you want to practise.", - "Several continuations are available. Choose the variation you want to practise.", - "Several continuations are available. Choose the variation you want to practise.", - ], - [ - "I don't remember — show a move", - "Не помню — показать ход", - "I don't remember — show a move", - "Zug vergessen — Hinweis zeigen", - "I don't remember — show a move", - "I don't remember — show a move", - "I don't remember — show a move", - "I don't remember — show a move", - "I don't remember — show a move", - ], - [ - "Next variation", - "Следующая ветка", - "Next variation", - "Nächste Variante", - "Next variation", - "Next variation", - "Next variation", - "Next variation", - "Next variation", - ], - [ - "Choose a move from your repertoire or show a hint.", - "Сыграйте ход из репертуара или откройте подсказку.", - "Choose a move from your repertoire or show a hint.", - "Spielen Sie einen Repertoirezug oder zeigen Sie einen Hinweis an.", - "Choose a move from your repertoire or show a hint.", - "Choose a move from your repertoire or show a hint.", - "Choose a move from your repertoire or show a hint.", - "Choose a move from your repertoire or show a hint.", - "Choose a move from your repertoire or show a hint.", - ], - [ - "Move accepted", - "Ход принят", - "Move accepted", - "Zug akzeptiert", - "Move accepted", - "Move accepted", - "Move accepted", - "Move accepted", - "Move accepted", - ], - [ - "Continue the variation", - "Продолжайте вариант", - "Continue the variation", - "Setzen Sie die Variante fort", - "Continue the variation", - "Continue the variation", - "Continue the variation", - "Continue the variation", - "Continue the variation", - ], - [ - "Your moves: {n} · mistakes: {m}", - "Ваших ходов: {n} · ошибок: {m}", - "Your moves: {n} · mistakes: {m}", - "Ihre Züge: {n} · Fehler: {m}", - "Your moves: {n} · mistakes: {m}", - "Your moves: {n} · mistakes: {m}", - "Your moves: {n} · mistakes: {m}", - "Your moves: {n} · mistakes: {m}", - "Your moves: {n} · mistakes: {m}", - ], // --- strict learning session --- [ "Spaced repetition (SRS)", @@ -20156,326 +19210,7 @@ const ROWS: &[[&str; 9]] = &[ "Sizning yurishingiz: repertuardagi asosiy yurishni o‘ynang.", "Сіздің жүрісіңіз: репертуардың негізгі жүрісін жасаңыз.", ], - [ - "Automatic context · {current} of {total}", - "Автоматический контекст · {current} из {total}", - "Contexte automatique · {current} sur {total}", - "Automatischer Kontext · {current} von {total}", - "Contexto automático · {current} de {total}", - "Contesto automatico · {current} di {total}", - "Contexto automático · {current} de {total}", - "Avtomatik kontekst · {current} / {total}", - "Автоматты контекст · {current} / {total}", - ], - [ - "Correct independent answer.", - "Правильный самостоятельный ответ.", - "Réponse indépendante correcte.", - "Richtige unabhängige Antwort.", - "Respuesta independiente correcta.", - "Risposta indipendente corretta.", - "Resposta independente correta.", - "Mustaqil javob to‘g‘ri.", - "Өздігінен берілген жауап дұрыс.", - ], - [ - "Wrong move. Replay the revealed move; it will not count as an independent success.", - "Неверный ход. Повторите показанный ход; это не будет самостоятельным успехом.", - "Coup incorrect. Rejouez le coup indiqué ; cela ne comptera pas comme une réussite indépendante.", - "Falscher Zug. Wiederholen Sie den angezeigten Zug; dies zählt nicht als unabhängiger Erfolg.", - "Jugada incorrecta. Repite la jugada mostrada; no contará como un acierto independiente.", - "Mossa errata. Rigioca la mossa mostrata; non conterà come successo indipendente.", - "Lance incorreto. Repita o lance mostrado; isso não contará como sucesso independente.", - "Noto‘g‘ri yurish. Ko‘rsatilgan yurishni takrorlang; bu mustaqil muvaffaqiyat hisoblanmaydi.", - "Қате жүріс. Көрсетілген жүрісті қайталаңыз; бұл өздігінен орындалған табыс болып саналмайды.", - ], - [ - "REPLAY_AFTER_ERROR · not an independent success.", - "Ход повторён после ошибки. Самостоятельный ответ не засчитан.", - "REPLAY_AFTER_ERROR · pas une réussite indépendante.", - "REPLAY_AFTER_ERROR · kein unabhängiger Erfolg.", - "REPLAY_AFTER_ERROR · no es un acierto independiente.", - "REPLAY_AFTER_ERROR · non è un successo indipendente.", - "REPLAY_AFTER_ERROR · não é um sucesso independente.", - "REPLAY_AFTER_ERROR · mustaqil muvaffaqiyat emas.", - "REPLAY_AFTER_ERROR · өздігінен орындалған табыс емес.", - ], - [ - "PREVIEWED · replay the shown move; this is not an independent success.", - "Повторите показанный ход. Ответ с подсказкой не считается самостоятельным.", - "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.", - "PREVIEWED · rigioca la mossa mostrata; non è un successo indipendente.", - "PREVIEWED · repita o lance mostrado; não é um sucesso independente.", - "PREVIEWED · ko‘rsatilgan yurishni takrorlang; bu mustaqil muvaffaqiyat emas.", - "PREVIEWED · көрсетілген жүрісті қайталаңыз; бұл өздігінен орындалған табыс емес.", - ], - [ - "PREVIEWED · shown move completed; no independent success recorded.", - "Ход выполнен с подсказкой. Самостоятельный ответ не засчитан.", - "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.", - "PREVIEWED · mossa mostrata completata; nessun successo indipendente registrato.", - "PREVIEWED · lance mostrado concluído; nenhum sucesso independente registrado.", - "PREVIEWED · ko‘rsatilgan yurish bajarildi; mustaqil muvaffaqiyat yozilmadi.", - "PREVIEWED · көрсетілген жүріс орындалды; өздігінен орындалған табыс жазылмады.", - ], - [ - "No due moves. New items are introduced only on request.", - "Нет ходов к повторению. Новые элементы добавляются только по запросу.", - "Aucun coup à réviser. De nouveaux éléments ne sont introduits que sur demande.", - "Keine fälligen Züge. Neue Elemente werden nur auf Anfrage eingeführt.", - "No hay jugadas pendientes. Los nuevos elementos solo se introducen a petición.", - "Nessuna mossa da ripassare. I nuovi elementi vengono introdotti solo su richiesta.", - "Não há lances por revisar. Novos elementos só são introduzidos a pedido.", - "Takrorlanadigan yurishlar yo‘q. Yangi elementlar faqat so‘rov bo‘yicha qo‘shiladi.", - "Қайталанатын жүрістер жоқ. Жаңа элементтер тек сұраныс бойынша қосылады.", - ], - [ - "Pause", - "Пауза", - "Pause", - "Pause", - "Pausa", - "Pausa", - "Pausa", - "Pauza", - "Үзіліс", - ], - [ - "Paused", - "Приостановлено", - "En pause", - "Pausiert", - "En pausa", - "In pausa", - "Pausado", - "Pauzada", - "Үзілісте", - ], ["T", "T", "T", "T", "T", "T", "T", "T", "T"], - [ - "Learning", - "Изучается", - "Apprentissage", - "Lernen", - "Aprendiendo", - "Apprendimento", - "Aprendendo", - "O‘rganilmoqda", - "Үйренілуде", - ], - [ - "Learnt", - "Изучено", - "Acquis", - "Gelernt", - "Aprendido", - "Appreso", - "Aprendido", - "O‘rganilgan", - "Үйренілген", - ], - [ - "Uncertain", - "Не подтверждено", - "Incertain", - "Unsicher", - "Incierto", - "Incerto", - "Incerto", - "Noaniq", - "Белгісіз", - ], - [ - "Learnt %", - "Изучено %", - "Acquis %", - "Gelernt %", - "Aprendido %", - "Appreso %", - "Aprendido %", - "O‘rganilgan %", - "Үйренілген %", - ], - [ - "Confident %", - "Надёжно изучено %", - "Confirmé %", - "Bestätigt %", - "Confirmado %", - "Confermato %", - "Confirmado %", - "Tasdiqlangan %", - "Расталған %", - ], - [ - "Calculated at", - "Рассчитано в", - "Calculé à", - "Berechnet um", - "Calculado a las", - "Calcolato alle", - "Calculado às", - "Hisoblash vaqti", - "Есептеу уақыты", - ], - [ - "Delete repertoire? Source PGN files and learning history will not change.", - "Удалить репертуар? Исходные PGN-файлы и история обучения не изменятся.", - "Supprimer le répertoire ? Les fichiers PGN sources et l’historique d’apprentissage resteront inchangés.", - "Repertoire löschen? Quell-PGN-Dateien und Lernhistorie bleiben unverändert.", - "¿Eliminar repertorio? Los archivos PGN de origen y el historial de aprendizaje no cambiarán.", - "Eliminare il repertorio? I file PGN di origine e la cronologia di apprendimento non cambieranno.", - "Excluir repertório? Os arquivos PGN de origem e o histórico de aprendizado não serão alterados.", - "Repertuarni o‘chirishni xohlaysizmi? Asl PGN fayllari va o‘rganish tarixi o‘zgarmaydi.", - "Репертуарды жою керек пе? Бастапқы PGN файлдары мен үйрену тарихы өзгермейді.", - ], - [ - "Edit", - "Изменить", - "Modifier", - "Bearbeiten", - "Editar", - "Modifica", - "Editar", - "Tahrirlash", - "Өңдеу", - ], - [ - "Learning priority", - "Порядок изучения", - "Priorité d’apprentissage", - "Lernpriorität", - "Prioridad de aprendizaje", - "Priorità di apprendimento", - "Prioridade de aprendizagem", - "O‘rganish ustuvorligi", - "Үйрену басымдығы", - ], - [ - "Depth first", - "Сначала вглубь", - "Profondeur d’abord", - "Tiefe zuerst", - "Profundidad primero", - "Prima in profondità", - "Profundidade primeiro", - "Avval chuqurlik", - "Алдымен тереңдік", - ], - [ - "Breadth over depth", - "Сначала вширь", - "Largeur avant profondeur", - "Breite vor Tiefe", - "Anchura antes que profundidad", - "Prima in ampiezza", - "Amplitude antes de profundidade", - "Chuqurlikdan ko‘ra kenglik", - "Тереңдікке қарағанда кеңдік", - ], - [ - "Main lines first", - "Сначала главные линии", - "Lignes principales d’abord", - "Hauptvarianten zuerst", - "Líneas principales primero", - "Prima le linee principali", - "Linhas principais primeiro", - "Avval asosiy yo‘nalishlar", - "Алдымен негізгі желілер", - ], - [ - "Common positions first", - "Сначала частые позиции", - "Positions fréquentes d’abord", - "Häufige Stellungen zuerst", - "Posiciones comunes primero", - "Prima le posizioni comuni", - "Posições comuns primeiro", - "Avval umumiy pozitsiyalar", - "Алдымен жиі позициялар", - ], - [ - "Reset Review Order", - "Сбросить порядок повторения", - "Réinitialiser l’ordre de révision", - "Wiederholreihenfolge zurücksetzen", - "Restablecer orden de repaso", - "Reimposta ordine di ripasso", - "Redefinir ordem de revisão", - "Takrorlash tartibini tiklash", - "Қайталау ретін қалпына келтіру", - ], - [ - "Learning items", - "Элементы обучения", - "Éléments d’apprentissage", - "Lernelemente", - "Elementos de aprendizaje", - "Elementi di apprendimento", - "Elementos de aprendizagem", - "O‘rganish elementlari", - "Үйрену элементтері", - ], - [ - "Shared", - "Общие", - "Partagés", - "Geteilt", - "Compartidos", - "Condivisi", - "Compartilhados", - "Umumiy", - "Ортақ", - ], - [ - "Affected repertoires", - "Затронутые репертуары", - "Répertoires concernés", - "Betroffene Repertoires", - "Repertorios afectados", - "Repertori interessati", - "Repertórios afetados", - "Ta’sirlangan repertuarlar", - "Әсер етілетін репертуарлар", - ], - [ - "Progress in other repertoires will also become Unseen. PGN files will not change.", - "Прогресс в других репертуарах тоже станет новым. PGN-файлы не изменятся.", - "La progression dans les autres répertoires deviendra également « Nouveau ». Les fichiers PGN ne changeront pas.", - "Der Fortschritt in anderen Repertoires wird ebenfalls zu „Neu“. PGN-Dateien bleiben unverändert.", - "El progreso en otros repertorios también pasará a «Nuevo». Los archivos PGN no cambiarán.", - "Anche i progressi negli altri repertori diventeranno «Nuovo». I file PGN non cambieranno.", - "O progresso em outros repertórios também ficará «Novo». Os arquivos PGN não serão alterados.", - "Boshqa repertuarlardagi jarayon ham “Yangi” holatiga o‘tadi. PGN fayllari o‘zgarmaydi.", - "Басқа репертуарлардағы үйрену де «Жаңа» күйіне өтеді. PGN файлдары өзгермейді.", - ], - [ - "I understand that shared progress will be reset", - "Я понимаю, что общий прогресс будет сброшен", - "Je comprends que la progression partagée sera réinitialisée", - "Ich verstehe, dass der gemeinsame Fortschritt zurückgesetzt wird", - "Entiendo que el progreso compartido se restablecerá", - "Comprendo che i progressi condivisi saranno azzerati", - "Entendo que o progresso compartilhado será redefinido", - "Umumiy jarayon tiklanishini tushunaman", - "Ортақ үйрену қалпына келтірілетінін түсінемін", - ], - [ - "Reset shared learning data", - "Сбросить общие данные обучения", - "Réinitialiser les données d’apprentissage partagées", - "Gemeinsame Lerndaten zurücksetzen", - "Restablecer datos de aprendizaje compartidos", - "Reimposta dati di apprendimento condivisi", - "Redefinir dados de aprendizagem compartilhados", - "Umumiy o‘rganish ma’lumotlarini tiklash", - "Ортақ үйрену деректерін қалпына келтіру", - ], [ "Context and move speed", "Контекст и скорость ходов", @@ -20553,17 +19288,6 @@ const ROWS: &[[&str; 9]] = &[ "Variantni o‘rganda oldingi yurishlarni hisobga olish", "Нұсқаны үйренгенде алдыңғы жүрістерді ескеру", ], - [ - "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×.", - "Диапазон −2…2. Адаптивная скорость = коэффициент × (1 + доля изученности), от 0,25× до 4×: 1,5 даёт 3× для полностью изученного хода; 0 и меньше — 0,25×.", - "Plage −2…2. Vitesse adaptative = ajustement × (1 + fraction apprise), limitée à 0,25×–4× : 1,5 donne 3× pour un coup entièrement appris ; 0 ou moins donne 0,25×.", - "Bereich −2…2. Adaptive Geschwindigkeit = Anpassung × (1 + gelernter Anteil), begrenzt auf 0,25×–4×: 1,5 ergibt 3× für einen vollständig gelernten Zug; 0 oder weniger ergibt 0,25×.", - "Rango −2…2. Velocidad adaptativa = ajuste × (1 + fracción aprendida), limitada a 0,25×–4×: 1,5 da 3× para una jugada totalmente aprendida; 0 o menos da 0,25×.", - "Intervallo −2…2. Velocità adattiva = regolazione × (1 + frazione appresa), limitata a 0,25×–4×: 1,5 dà 3× per una mossa completamente appresa; 0 o meno dà 0,25×.", - "Intervalo −2…2. Velocidade adaptativa = ajuste × (1 + fração aprendida), limitada a 0,25×–4×: 1,5 dá 3× para um lance totalmente aprendido; 0 ou menos dá 0,25×.", - "Diapazon −2…2. Moslashuvchan tezlik = koeffitsiyent × (1 + o‘rganilgan ulush), 0,25×–4× bilan cheklangan: to‘liq o‘rganilgan yurishda 1,5 3× beradi; 0 yoki undan kam 0,25× beradi.", - "Ауқым −2…2. Бейімделгіш жылдамдық = коэффициент × (1 + үйренілген үлес), 0,25×–4× шегінде: толық үйренілген жүрісте 1,5 — 3×; 0 немесе одан аз — 0,25×.", - ], [ "plies", "полуходов", @@ -20575,17 +19299,6 @@ const ROWS: &[[&str; 9]] = &[ "yarim yurishlar", "жарты жүрістер", ], - [ - "Select a move in the PGN tree", - "Выберите ход в дереве PGN", - "Sélectionnez un coup dans l’arbre PGN", - "Wählen Sie einen Zug im PGN-Baum", - "Selecciona una jugada en el árbol PGN", - "Seleziona una mossa nell’albero PGN", - "Selecione um lance na árvore PGN", - "PGN daraxtidan yurishni tanlang", - "PGN ағашынан жүрісті таңдаңыз", - ], [ "Main answer", "Основной ответ", @@ -20619,61 +19332,6 @@ const ROWS: &[[&str; 9]] = &[ "Almashtirishni bekor qilish", "Қайта анықтауды жою", ], - [ - "Enable", - "Включить", - "Activer", - "Aktivieren", - "Activar", - "Attiva", - "Ativar", - "Yoqish", - "Қосу", - ], - [ - "Disable", - "Отключить", - "Désactiver", - "Deaktivieren", - "Desactivar", - "Disattiva", - "Desativar", - "O‘chirish", - "Өшіру", - ], - [ - "Disabled for training", - "Отключено для тренировки", - "Désactivé pour l’entraînement", - "Für das Training deaktiviert", - "Desactivado para el entrenamiento", - "Disattivato per l’allenamento", - "Desativado para treinamento", - "Mashg‘ulot uchun o‘chirilgan", - "Жаттығу үшін өшірілген", - ], - [ - "PGN tree", - "Дерево PGN", - "Arbre PGN", - "PGN-Baum", - "Árbol PGN", - "Albero PGN", - "Árvore PGN", - "PGN daraxti", - "PGN ағашы", - ], - [ - "Initial position", - "Начальная позиция", - "Position initiale", - "Anfangsstellung", - "Posición inicial", - "Posizione iniziale", - "Posição inicial", - "Boshlang‘ich pozitsiya", - "Бастапқы позиция", - ], [ "main", "основной", @@ -20685,50 +19343,6 @@ const ROWS: &[[&str; 9]] = &[ "asosiy", "негізгі", ], - [ - "disabled", - "отключено", - "désactivé", - "deaktiviert", - "desactivado", - "disattivato", - "desativado", - "o‘chirilgan", - "өшірілген", - ], - [ - "Move analytics", - "Аналитика хода", - "Statistiques du coup", - "Zugstatistik", - "Estadísticas de la jugada", - "Statistiche della mossa", - "Estatísticas do lance", - "Yurish statistikasi", - "Жүріс статистикасы", - ], - [ - "Select a move to see its learning analytics", - "Выберите ход, чтобы увидеть аналитику его обучения", - "Sélectionnez un coup pour voir ses statistiques d’apprentissage", - "Wählen Sie einen Zug, um seine Lernstatistik zu sehen", - "Selecciona una jugada para ver sus estadísticas de aprendizaje", - "Seleziona una mossa per vedere le sue statistiche di apprendimento", - "Selecione um lance para ver suas estatísticas de aprendizagem", - "O‘rganish statistikasini ko‘rish uchun yurishni tanlang", - "Үйрену статистикасын көру үшін жүрісті таңдаңыз", - ], - [ - "Shared learning data is not connected", - "Общие данные обучения не подключены", - "Les données d’apprentissage partagées ne sont pas connectées", - "Gemeinsame Lerndaten sind nicht verbunden", - "Los datos de aprendizaje compartidos no están conectados", - "I dati di apprendimento condivisi non sono collegati", - "Os dados de aprendizagem compartilhados não estão conectados", - "Umumiy o‘rganish ma’lumotlari ulanmagan", - "Ортақ үйрену деректері қосылмаған", - ], [ "Learning analytics is kept for the current main answer", "Аналитика обучения ведётся для текущего основного ответа", @@ -20740,83 +19354,6 @@ const ROWS: &[[&str; 9]] = &[ "O‘rganish statistikasi joriy asosiy javob uchun saqlanadi", "Үйрену статистикасы ағымдағы негізгі жауап үшін сақталады", ], - [ - "The selected move cannot be the main answer for this position", - "Выбранный ход не может быть основным ответом в этой позиции", - "Le coup sélectionné ne peut pas être la réponse principale pour cette position", - "Der ausgewählte Zug kann in dieser Stellung nicht der Hauptzug sein", - "La jugada seleccionada no puede ser la respuesta principal para esta posición", - "La mossa selezionata non può essere la risposta principale per questa posizione", - "O lance selecionado não pode ser a resposta principal para esta posição", - "Tanlangan yurish bu pozitsiyada asosiy javob bo‘la olmaydi", - "Таңдалған жүріс бұл позицияда негізгі жауап бола алмайды", - ], - [ - "The selected PGN branch cannot be disabled", - "Выбранную ветку PGN нельзя отключить", - "La variante PGN sélectionnée ne peut pas être désactivée", - "Der ausgewählte PGN-Zweig kann nicht deaktiviert werden", - "La variante PGN seleccionada no se puede desactivar", - "La variante PGN selezionata non può essere disattivata", - "A variante PGN selecionada não pode ser desativada", - "Tanlangan PGN variantini o‘chirish mumkin emas", - "Таңдалған PGN нұсқасын өшіру мүмкін емес", - ], - [ - "The selected PGN branch cannot be enabled", - "Выбранную ветку PGN нельзя включить", - "La variante PGN sélectionnée ne peut pas être activée", - "Der ausgewählte PGN-Zweig kann nicht aktiviert werden", - "La variante PGN seleccionada no se puede activar", - "La variante PGN selezionata non può essere attivata", - "A variante PGN selecionada não pode ser ativada", - "Tanlangan PGN variantini yoqish mumkin emas", - "Таңдалған PGN нұсқасын қосу мүмкін емес", - ], - [ - "Next due", - "Следующее повторение", - "Prochaine révision", - "Nächste Wiederholung", - "Próximo repaso", - "Prossimo ripasso", - "Próxima revisão", - "Keyingi takrorlash", - "Келесі қайталау", - ], - [ - "Response median", - "Медиана времени ответа", - "Médiane du temps de réponse", - "Median der Antwortzeit", - "Mediana del tiempo de respuesta", - "Mediana del tempo di risposta", - "Mediana do tempo de resposta", - "Javob vaqti medianasi", - "Жауап уақытының медианасы", - ], - [ - "Wrong moves", - "Ошибочные ходы", - "Coups erronés", - "Falsche Züge", - "Jugadas erróneas", - "Mosse errate", - "Lances errados", - "Noto‘g‘ri yurishlar", - "Қате жүрістер", - ], - [ - "Unknown move", - "Неизвестный ход", - "Coup inconnu", - "Unbekannter Zug", - "Jugada desconocida", - "Mossa sconosciuta", - "Lance desconhecido", - "Noma’lum yurish", - "Белгісіз жүріс", - ], // --- learning dashboard --- [ "Learning dashboard", @@ -20829,28 +19366,6 @@ const ROWS: &[[&str; 9]] = &[ "O‘rganish paneli", "Үйрену панелі", ], - [ - "The selected scope is no longer available", - "Выбранная область больше недоступна", - "La portée sélectionnée n’est plus disponible", - "Der ausgewählte Bereich ist nicht mehr verfügbar", - "El ámbito seleccionado ya no está disponible", - "L’ambito selezionato non è più disponibile", - "O escopo selecionado não está mais disponível", - "Tanlangan doira endi mavjud emas", - "Таңдалған аумақ енді қолжетімді емес", - ], - [ - "Side", - "Сторона", - "Camp", - "Seite", - "Lado", - "Lato", - "Lado", - "Tomon", - "Тарап", - ], [ "All repertoires (union)", "Все репертуары (объединение)", @@ -20873,28 +19388,6 @@ const ROWS: &[[&str; 9]] = &[ "Jami yurishlar", "Барлық жүрістер", ], - [ - "Learnt = Confident + Uncertain · percentages use Total.", - "Изучено = надёжно изучено + неподтверждено · проценты считаются от общего числа.", - "Acquis = confirmés + incertains · les pourcentages utilisent le total.", - "Gelernt = Sicher + Unsicher · Prozentwerte beziehen sich auf die Gesamtzahl.", - "Aprendidas = fiables + inciertas · los porcentajes usan el total.", - "Apprese = affidabili + incerte · le percentuali usano il totale.", - "Aprendidos = confiáveis + incertos · as porcentagens usam o total.", - "O‘rganilgan = ishonchli + noaniq · foizlar jami sonidan hisoblanadi.", - "Үйренілген = сенімді + расталмаған · пайыздар жалпы санынан есептеледі.", - ], - [ - "Save statistics to History", - "Сохранить статистику в историю", - "Enregistrer les statistiques dans l’historique", - "Statistiken im Verlauf speichern", - "Guardar estadísticas en el historial", - "Salva statistiche nella cronologia", - "Salvar estatísticas no histórico", - "Statistikani tarixga saqlash", - "Статистиканы тарихқа сақтау", - ], [ "Save the current numbers for the selected scope and side. PGN and learning progress do not change.", "Сохранить текущие показатели для выбранной области и стороны. PGN и прогресс обучения не изменятся.", @@ -20917,28 +19410,6 @@ const ROWS: &[[&str; 9]] = &[ "O‘lchovni saqlash", "Түсірімді сақтау", ], - [ - "Snapshot captured: {date}", - "Снимок сохранён: {date}", - "Instantané capturé : {date}", - "Snapshot aufgenommen: {date}", - "Instantánea capturada: {date}", - "Istantanea acquisita: {date}", - "Instantâneo capturado: {date}", - "O‘lchov saqlandi: {date}", - "Түсірім сақталды: {date}", - ], - [ - "Snapshot already exists for this date and scope: {date}", - "Снимок для этой даты и области уже есть: {date}", - "Un instantané existe déjà pour cette date et cette portée : {date}", - "Für Datum und Bereich existiert bereits ein Snapshot: {date}", - "Ya existe una instantánea para esta fecha y ámbito: {date}", - "Esiste già un’istantanea per questa data e ambito: {date}", - "Já existe um instantâneo para esta data e escopo: {date}", - "Bu sana va doira uchun o‘lchov allaqachon mavjud: {date}", - "Бұл күн мен аумақ үшін түсірім бар: {date}", - ], [ "Summary", "Сводка", @@ -20950,39 +19421,6 @@ const ROWS: &[[&str; 9]] = &[ "Qisqacha", "Қорытынды", ], - [ - "Scheduled", - "Расписание", - "Planification", - "Zeitplan", - "Programación", - "Pianificazione", - "Agendamento", - "Jadval", - "Кесте", - ], - [ - "Sequences", - "Серии", - "Séquences", - "Sequenzen", - "Secuencias", - "Sequenze", - "Sequências", - "Ketma-ketliklar", - "Тізбектер", - ], - [ - "Loading learning statistics…", - "Загрузка статистики обучения…", - "Chargement des statistiques d’apprentissage…", - "Lernstatistik wird geladen…", - "Cargando estadísticas de aprendizaje…", - "Caricamento delle statistiche di apprendimento…", - "Carregando estatísticas de aprendizagem…", - "O‘rganish statistikasi yuklanmoqda…", - "Үйрену статистикасы жүктелуде…", - ], [ "T = Unseen + Learning + Learnt. Uncertain is already included in Learnt.", "T = новые + изучаемые + изученные. Неподтверждённые уже входят в изученные.", @@ -21005,28 +19443,6 @@ const ROWS: &[[&str; 9]] = &[ "Noaniqlar o‘rganilganga kiradi va T ga alohida qo‘shilmaydi.", "Расталмағандар үйренілгенге кіреді және T санына бөлек қосылмайды.", ], - [ - "Global total", - "Общий итог", - "Total global", - "Gesamtsumme", - "Total global", - "Totale globale", - "Total global", - "Umumiy jami", - "Жалпы қорытынды", - ], - [ - "Global total counts each shared learning item once; repertoire rows can add up to more.", - "В общем итоге каждый общий элемент учитывается один раз, поэтому сумма строк репертуаров может быть больше.", - "Le total global compte chaque élément partagé une seule fois ; la somme des répertoires peut être supérieure.", - "Die Gesamtsumme zählt jedes gemeinsame Lernelement nur einmal; die Summe der Repertoirezeilen kann größer sein.", - "El total global cuenta cada elemento compartido una vez; la suma de los repertorios puede ser mayor.", - "Il totale globale conta ogni elemento condiviso una sola volta; la somma dei repertori può essere maggiore.", - "O total global conta cada elemento compartilhado uma vez; a soma dos repertórios pode ser maior.", - "Umumiy jami har bir umumiy elementni bir marta sanaydi; repertuar qatorlari yig‘indisi kattaroq bo‘lishi mumkin.", - "Жалпы қорытынды ортақ элементті бір рет санайды; репертуар жолдарының қосындысы үлкен болуы мүмкін.", - ], [ "Next due at", "Следующее повторение", @@ -21049,17 +19465,6 @@ const ROWS: &[[&str; 9]] = &[ "Hali o‘lchovlar yo‘q. Joriy doirani yozish uchun «Statistikani tarixga saqlash» bosing.", "Әзірге түсірім жоқ. Ағымдағы аумақты жазу үшін «Статистиканы тарихқа сақтау» басыңыз.", ], - [ - "Overdue", - "Просрочено", - "En retard", - "Überfällig", - "Atrasado", - "In ritardo", - "Atrasado", - "Muddati o‘tgan", - "Мерзімі өткен", - ], [ "Today", "Сегодня", @@ -21071,391 +19476,6 @@ const ROWS: &[[&str; 9]] = &[ "Bugun", "Бүгін", ], - [ - "Next 7 days", - "Следующие 7 дней", - "7 prochains jours", - "Nächste 7 Tage", - "Próximos 7 días", - "Prossimi 7 giorni", - "Próximos 7 dias", - "Keyingi 7 kun", - "Келесі 7 күн", - ], - [ - "Next 30 days", - "Следующие 30 дней", - "30 prochains jours", - "Nächste 30 Tage", - "Próximos 30 días", - "Prossimi 30 giorni", - "Próximos 30 dias", - "Keyingi 30 kun", - "Келесі 30 күн", - ], - [ - "Next 365 days", - "Следующие 365 дней", - "365 prochains jours", - "Nächste 365 Tage", - "Próximos 365 días", - "Prossimi 365 giorni", - "Próximos 365 dias", - "Keyingi 365 kun", - "Келесі 365 күн", - ], - [ - "Introduced", - "Введено в обучение", - "Introduits", - "Eingeführt", - "Introducidas", - "Introdotti", - "Introduzidos", - "O‘rganishga kiritilgan", - "Үйренуге енгізілген", - ], - [ - "Today ends at local midnight; the other buckets use fixed 7, 30 and 365-day ranges.", - "«Сегодня» заканчивается в локальную полночь; остальные корзины используют фиксированные 7, 30 и 365 дней.", - "« Aujourd’hui » se termine à minuit local ; les autres catégories utilisent des durées fixes de 7, 30 et 365 jours.", - "„Heute“ endet um Mitternacht vor Ort; die anderen Gruppen verwenden feste Bereiche von 7, 30 und 365 Tagen.", - "«Hoy» termina a medianoche local; las demás categorías usan intervalos fijos de 7, 30 y 365 días.", - "«Oggi» termina a mezzanotte locale; le altre categorie usano intervalli fissi di 7, 30 e 365 giorni.", - "«Hoje» termina à meia-noite local; as outras categorias usam intervalos fixos de 7, 30 e 365 dias.", - "«Bugun» mahalliy yarim tunda tugaydi; qolgan guruhlar 7, 30 va 365 kunlik qat’iy oraliqlarni ishlatadi.", - "«Бүгін» жергілікті түн ортасында аяқталады; басқа топтар 7, 30 және 365 күндік тұрақты аралықты қолданады.", - ], - [ - "No moves in this scope", - "В этой области нет ходов", - "Aucun coup dans cette portée", - "Keine Züge in diesem Bereich", - "No hay jugadas en este ámbito", - "Nessuna mossa in questo ambito", - "Não há lances neste escopo", - "Bu doirada yurishlar yo‘q", - "Бұл аумақта жүрістер жоқ", - ], - [ - "Items", - "Элементы", - "Éléments", - "Elemente", - "Elementos", - "Elementi", - "Itens", - "Elementlar", - "Элементтер", - ], - [ - "Total", - "Итого", - "Total", - "Gesamt", - "Total", - "Totale", - "Total", - "Jami", - "Барлығы", - ], - [ - "Correct streak", - "Серия верных", - "Série de réussites", - "Serie richtiger Antworten", - "Racha de aciertos", - "Serie di risposte corrette", - "Sequência de acertos", - "To‘g‘ri javoblar seriyasi", - "Дұрыс жауаптар тізбегі", - ], - [ - "Wrong streak", - "Серия ошибок", - "Série d’erreurs", - "Serie falscher Antworten", - "Racha de errores", - "Serie di errori", - "Sequência de erros", - "Xato javoblar seriyasi", - "Қате жауаптар тізбегі", - ], - [ - "Length / attempts", - "Длина / попытки", - "Longueur / tentatives", - "Länge / Versuche", - "Longitud / intentos", - "Lunghezza / tentativi", - "Comprimento / tentativas", - "Uzunlik / urinishlar", - "Ұзындық / әрекеттер", - ], - [ - "Status", - "Статус", - "Statut", - "Status", - "Estado", - "Stato", - "Estado", - "Holat", - "Күй", - ], - [ - "Streak", - "Серия", - "Série", - "Serie", - "Racha", - "Serie", - "Sequência", - "Seriya", - "Тізбек", - ], - [ - "Learnt fresh", - "Изучено и актуально", - "Acquis et à jour", - "Gelernt und aktuell", - "Aprendido y al día", - "Appreso e aggiornato", - "Aprendido e atualizado", - "O‘rganilgan va dolzarb", - "Үйренілген және өзекті", - ], - [ - "Resistant", - "Проблемный", - "Résistant", - "Hartnäckig", - "Resistente", - "Resistente", - "Resistente", - "Qiyin", - "Қиын", - ], - [ - "Wrong answers", - "Ошибочные ответы", - "Réponses erronées", - "Falsche Antworten", - "Respuestas incorrectas", - "Risposte errate", - "Respostas erradas", - "Noto‘g‘ri javoblar", - "Қате жауаптар", - ], - [ - "No wrong answers", - "Ошибочных ответов нет", - "Aucune réponse erronée", - "Keine falschen Antworten", - "No hay respuestas incorrectas", - "Nessuna risposta errata", - "Não há respostas erradas", - "Noto‘g‘ri javoblar yo‘q", - "Қате жауаптар жоқ", - ], - [ - "Count", - "Количество", - "Nombre", - "Anzahl", - "Cantidad", - "Conteggio", - "Contagem", - "Soni", - "Саны", - ], - [ - "Last at", - "Последний раз", - "Dernière fois", - "Zuletzt", - "Última vez", - "Ultima volta", - "Última vez", - "Oxirgi marta", - "Соңғы рет", - ], - [ - "Found in", - "Встречается в", - "Présent dans", - "Enthalten in", - "Presente en", - "Presente in", - "Presente em", - "Uchraydi", - "Кездеседі", - ], - [ - "Repertoires and branches that contain this learning item.", - "Репертуары и ветки, содержащие этот элемент обучения.", - "Répertoires et branches contenant cet élément d’apprentissage.", - "Repertoires und Varianten, die dieses Lernelement enthalten.", - "Repertorios y ramas que contienen este elemento de aprendizaje.", - "Repertori e diramazioni che contengono questo elemento di apprendimento.", - "Repertórios e ramificações que contêm este elemento de aprendizagem.", - "Bu o‘rganish elementini o‘z ichiga olgan repertuar va shoxobchalar.", - "Осы үйрену элементін қамтитын репертуарлар мен тармақтар.", - ], - [ - "The current learning status of this move.", - "Текущий статус обучения этого хода.", - "Le statut d’apprentissage actuel de ce coup.", - "Der aktuelle Lernstatus dieses Zuges.", - "El estado de aprendizaje actual de esta jugada.", - "Lo stato di apprendimento attuale di questa mossa.", - "O estado atual de aprendizagem deste lance.", - "Bu yurishning joriy o‘rganish holati.", - "Осы жүрістің ағымдағы үйрену күйі.", - ], - [ - "Independent correct answers divided by all independent attempts.", - "Верные самостоятельные ответы, делённые на все самостоятельные попытки.", - "Réponses correctes indépendantes divisées par toutes les tentatives indépendantes.", - "Unabhängige richtige Antworten geteilt durch alle unabhängigen Versuche.", - "Aciertos independientes divididos entre todos los intentos independientes.", - "Risposte corrette indipendenti divise per tutti i tentativi indipendenti.", - "Acertos independentes divididos por todas as tentativas independentes.", - "Mustaqil to‘g‘ri javoblarning barcha mustaqil urinishlarga nisbati.", - "Өздік дұрыс жауаптардың барлық өздік әрекеттерге қатынасы.", - ], - [ - "Only independent attempts count; previews, automatic context and replays are excluded.", - "Учитываются только самостоятельные попытки; предпросмотр, автоконтекст и повторы исключены.", - "Seules les tentatives indépendantes comptent ; aperçus, contextes automatiques et répétitions sont exclus.", - "Nur unabhängige Versuche zählen; Vorschauen, automatischer Kontext und Wiederholungen sind ausgeschlossen.", - "Solo cuentan los intentos independientes; se excluyen vistas previas, contexto automático y repeticiones.", - "Contano solo i tentativi indipendenti; anteprime, contesto automatico e repliche sono esclusi.", - "Somente tentativas independentes contam; prévias, contexto automático e repetições são excluídos.", - "Faqat mustaqil urinishlar hisoblanadi; ko‘rib chiqish, avtomatik kontekst va takrorlar chiqariladi.", - "Тек өздік әрекеттер есептеледі; алдын ала қарау, авто контекст және қайталаулар есептен шығарылады.", - ], - [ - "Consecutive independent correct answers.", - "Подряд идущие верные самостоятельные ответы.", - "Réponses correctes indépendantes consécutives.", - "Aufeinanderfolgende unabhängige richtige Antworten.", - "Aciertos independientes consecutivos.", - "Risposte corrette indipendenti consecutive.", - "Acertos independentes consecutivos.", - "Ketma-ket mustaqil to‘g‘ri javoblar.", - "Қатарынан өздік дұрыс жауаптар.", - ], - [ - "Consecutive independent wrong answers.", - "Подряд идущие ошибочные самостоятельные ответы.", - "Réponses erronées indépendantes consécutives.", - "Aufeinanderfolgende unabhängige falsche Antworten.", - "Errores independientes consecutivos.", - "Errori indipendenti consecutivi.", - "Erros independentes consecutivos.", - "Ketma-ket mustaqil xato javoblar.", - "Қатарынан өздік қате жауаптар.", - ], - [ - "The scheduled review time, or a dash for an unseen move.", - "Назначенное время повторения или прочерк для нового хода.", - "L’heure de révision prévue, ou un tiret pour un coup nouveau.", - "Die geplante Wiederholungszeit oder ein Strich bei einem neuen Zug.", - "La hora de repaso programada o un guion para una jugada nueva.", - "L’orario di ripetizione pianificato o un trattino per una mossa nuova.", - "A hora de revisão agendada ou um traço para um lance novo.", - "Rejalashtirilgan takrorlash vaqti yoki yangi yurish uchun chiziqcha.", - "Жоспарланған қайталау уақыты немесе жаңа жүріс үшін сызықша.", - ], - [ - "Review in", - "До повтора", - "Révision dans", - "Wiederholung in", - "Repaso en", - "Ripetizione tra", - "Revisão em", - "Takrorlashga", - "Қайталауға", - ], - [ - "Time remaining until the scheduled review.", - "Время до назначенного повторения.", - "Temps restant avant la révision prévue.", - "Verbleibende Zeit bis zur geplanten Wiederholung.", - "Tiempo restante hasta el repaso programado.", - "Tempo rimanente fino alla ripetizione pianificata.", - "Tempo restante até a revisão agendada.", - "Rejalashtirilgan takrorlashgacha qolgan vaqt.", - "Жоспарланған қайталауға дейінгі уақыт.", - ], - [ - "Overdue by", - "Просрочено на", - "En retard de", - "Überfällig seit", - "Atrasado por", - "In ritardo di", - "Atrasado por", - "Kechikkan vaqt", - "Кешігу уақыты", - ], - [ - "Elapsed time since the scheduled review.", - "Время, прошедшее после назначенного повторения.", - "Temps écoulé depuis la révision prévue.", - "Vergangene Zeit seit der geplanten Wiederholung.", - "Tiempo transcurrido desde el repaso programado.", - "Tempo trascorso dalla ripetizione pianificata.", - "Tempo decorrido desde a revisão agendada.", - "Rejalashtirilgan takrorlashdan keyin o‘tgan vaqt.", - "Жоспарланған қайталаудан кейін өткен уақыт.", - ], - [ - "Median response", - "Медиана времени ответа", - "Temps de réponse médian", - "Median der Antwortzeit", - "Tiempo de respuesta mediano", - "Tempo di risposta mediano", - "Tempo de resposta mediano", - "Javob vaqti medianasi", - "Жауап уақытының медианасы", - ], - [ - "Median response time over independent attempts.", - "Медиана времени ответа по самостоятельным попыткам.", - "Temps de réponse médian sur les tentatives indépendantes.", - "Median der Antwortzeit über unabhängige Versuche.", - "Tiempo de respuesta mediano en intentos independientes.", - "Tempo di risposta mediano sui tentativi indipendenti.", - "Tempo de resposta mediano nas tentativas independentes.", - "Mustaqil urinishlardagi javob vaqti medianasi.", - "Өздік әрекеттердегі жауап уақытының медианасы.", - ], - [ - "Uncertain grace", - "Отсрочка до потери подтверждения", - "Délai avant incertitude", - "Karenzzeit bis Unsicherheit", - "Margen antes de incertidumbre", - "Periodo di grazia prima dell’incertezza", - "Período de tolerância antes da incerteza", - "Noaniqlikka qadar vaqt", - "Расталмауға дейінгі мерзім", - ], - [ - "The overdue grace period before a learnt move becomes uncertain.", - "Допустимая просрочка, после которой изученный ход становится неподтверждённым.", - "Le délai de retard avant qu’un coup acquis ne devienne incertain.", - "Die Karenzzeit, nach der ein gelernter Zug unsicher wird.", - "El margen de atraso antes de que una jugada aprendida pase a ser incierta.", - "Il periodo di tolleranza prima che una mossa appresa diventi incerta.", - "O período de tolerância antes de um lance aprendido se tornar incerto.", - "O‘rganilgan yurish noaniq holga kelishidan oldingi kechikish muddati.", - "Үйренілген жүріс расталмаған күйге өтпес бұрынғы кешігу мерзімі.", - ], [ "Branches", "Ветки", @@ -21500,248 +19520,6 @@ const ROWS: &[[&str; 9]] = &[ "Oxirgi mashg‘ulot", "Соңғы жаттығу", ], - [ - "No branches in this scope", - "В этой области нет веток", - "Aucune branche dans cette portée", - "Keine Varianten in diesem Bereich", - "No hay ramas en este ámbito", - "Nessun ramo in questo ambito", - "Não há ramos neste escopo", - "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)] From 94ddbfa27a84e59bd9c2a299c2c81fcd1c7cef91 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:08:29 +0300 Subject: [PATCH 13/31] qa: opening trainer v2 design review --- docs/qa/opening-trainer-v2-design-review.md | 51 +++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 docs/qa/opening-trainer-v2-design-review.md diff --git a/docs/qa/opening-trainer-v2-design-review.md b/docs/qa/opening-trainer-v2-design-review.md new file mode 100644 index 0000000..f2b1cd3 --- /dev/null +++ b/docs/qa/opening-trainer-v2-design-review.md @@ -0,0 +1,51 @@ +# Тренировка дебюта v2 — независимая дизайн-приёмка + +Дата: 2026-11-27. Ревьюер: designer (не автор кода). Ветка `feature/opening-trainer-v2`, сборка на 04af686. +Профиль изолирован (`XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `CP_REPERTOIRE_DIR` → `/tmp/opencode/prof.*`), RU, тёмная +тема, если не указано иное. Дисплей HiDPI: все снимки сняты при pixels_per_point = 2 (файл 2800×1800 = окно +1400×900 pt; 1920×1200 = 960×600 pt). Координаты ниже — в pt. Снимки: `target/qa-opening-v2/review/`. + +## Вердикт: ACCEPTED WITH FIXES + +Занятие устроено понятно и стабильно: карточка, ряд кнопок и полоса не двигаются ни на одном переходе, новый ход +показан стрелкой и словами, ошибка — красной обводкой и словом «Не тот ход» с правильным ходом, итог отвечает на +вопрос «что дальше». Блокирует выпуск одно: в подписи «Тренировать эту ветку» показан сырой UCI. Остальное — +геометрия шапки относительно экрана партии и потерянная строка пути. + +## Дефекты + +| # | Пр. | Снимок, размер, состояние | Факт → ожидание | Предложение | +|---|---|---|---|---| +| 1 | P1 | `r24-branch.png` 1400, «Тренировать эту ветку», S2 | Подпись шапки «Ветка: e2e4 e7e5 g1f3 b8c6 f1b5 g8f6» — UCI в интерфейсе | `Ветка · 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6` через `san::show`, обрезка слева, полный текст в подсказке | +| 2 | P2 | все экраны раздела (`r01`, `r06`, `r23`, `r03`, `r27`) против `x-game.png` (экран партии той же сборки) и `ref-04` | Разделитель шапки y=45 (у партии 52); доска 1400: x 51…889, y 53…891 (838 pt) вместо 54…886, y 60…892 (832); 960: x 19…557 вместо 22…554. Левый край панели 940/576 — совпадает. §9.1–2 не выполнены (допуск 1 px) | Использовать ту же высоту шапки, что у партии (общий `widgets::section_header_sub` с той же минимальной высотой/отступом 7 pt); доску считать от той же области | +| 3 | P2 | `r07-after1.png` (S2 после 1. e4 e5), `r19-review-next.png` (S3 после 1. e4 e5) | Блок C «Путь» пустой: виден только дебют «C20 · King's Pawn Game» | Выводить `1. e4 e5` (§4.1 C), обрезка слева; в глубоких вопросах это единственная подсказка, в какой ветке находишься | +| 4 | P2 | `r01-rep-white.png` (1400, ничего не выучено) → `r14-lib-after.png` (после 10 новых) → `r03-rep-960.png` (960) | Кнопка «Повторить всё» есть в первом кадре и пропадает во втором и на 960; новичок не находит «повторить подряд» (остаётся только в `⋯`) | Если по §3 это не намеренно — держать ряд из трёх кнопок постоянным; на 960 сокращать ширину, а не убирать кнопку | +| 5 | P3 | `r14-lib-after.png` | «Выучено 0 из 22 ходов», при этом полоса прогресса заполнена на ~45 % — читается как противоречие | Подписать полосу или окрасить «учится» иначе с легендой «учится: 10» рядом с полосой (сейчас справа отдельно) | +| 6 | P3 | `r12-summary.png`, `r31-summary-960.png` | В карточке итога счётчик «0 осталось» — лишний шум | На итоге счётчик не показывать (место остаётся пустым, высота 64 сохраняется) | +| 7 | P3 | `r05-train-prep.png` → `r06-new.png` | S0 «Готовим занятие…» показывает позицию из библиотеки (после 3. Bb5), затем доска прыгает в начальную | В S0 ставить исходную позицию занятия или начальную позицию | +| 8 | P3 | `r04-menu.png` | Пункт меню «Играть чёрными» звучит как «начать партию» | «Цвет: чёрные…» / «Сменить цвет на чёрные» | +| 9 | P3 | `r06-new.png`, `r07`, `r19` | В русском интерфейсе названия дебютов и комментарии стартовых репертуаров по-английски | Комментарии — контент PGN, оставить; для стартовых репертуаров дать русские комментарии; названия дебютов — по решению о локализации базы | +| 10 | P3 | `r08-new2-wrong.png` (S2, хук `wrong`) | Кадр не отличается от S2: нет слова «Не тот ход». Не уверен, что хук сыграл ход в S2 | Тестировщику проверить вручную неверный ход в S2: по §4.2 ожидается S5 | + +## Что проверено + +- Репертуары: выбран белый `r01`, чёрный `r02`, 960 `r03`, светлая тема `r28`, после обучения `r14`; меню `⋯` `r04`. + Таблица, король-значок цвета, выделение строки и обводка карточки читаются, в светлой теме тоже. +- Диалоги: импорт с выбором цвета `r20` (подсказка «Выбрано по PGN — проверьте», одна главная кнопка справа внизу), + сброс с общими позициями `r21` (предупреждение словами), удаление `r22`. Всё в стиле `ref-03/05`. +- Занятие: S0 `r05`, S2 `r06`/`r07`, S3 `r15`/`r19`, S4 «Верно» `r18`, S5 «Не тот ход» `r17`/`r29` (светлая) — + правильный ход назван и показан стрелкой, S7 «Подсказка» `r26`, S8 итог `r12`/`r30`/`r31`, чёрные (доска + перевёрнута) `r25`, 960 `r27`. +- «Повторить всё подряд» `r09`/`r15` (подпись «Повторение подряд», счётчик «1/3 вариант»), «Варианты» с выбранным + 3…a6 `r23` (комментарии PGN в линии, «Тренировать эту ветку» / «Не тренировать»), ветка `r24`. +- Скачки (серия C, 8 кадров `r05 r06 r07 r17 r18 r19 r26 r12`, проверка столбцов и строк по краям): рамка карточки + y 52…116 (64 ✓), ряд кнопок 828…858 (30 ✓), полоса 861…885, доска x 51, панель 940 — **смещение 0 px на всех + кадрах**. Между экранами раздела (репертуары, занятие, варианты) доска и панель совпадают (0 px). +- Польза для обучения: новый ход показан стрелкой и словами «Сыграйте 2. Nf3 — он показан стрелкой»; на ошибке + правильный ход сразу; дебют обновляется по ходу (B00 → C20 → C96); комментарии PGN видны в D и в «Вариантах». + +## Не проверено + +S3a, S5a, S9 и повтор после ошибки записи; пустой список, 12 репертуаров, имя 120 знаков; импорт с +предупреждениями и полоса ошибки; англоязычный интерфейс; серии A, B, E, F; клавиатура (H, N, Enter, Esc, F) и +фокус; панель, суженная до 320. Масштаб 1 не снят: в окружении только HiDPI (ppp 2), все замеры приведены к pt. From ebd705cf5decac465076f2dea4b4205888641214 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:10:00 +0300 Subject: [PATCH 14/31] opening trainer: the branch header names the branch in SAN with move numbers (also from the QA hook) --- apps/desktop/src/opening_layout.rs | 19 +++++++++++++++++++ apps/desktop/src/opening_lines.rs | 16 +--------------- apps/desktop/src/repertoire_ui.rs | 11 ++++++++++- 3 files changed, 30 insertions(+), 16 deletions(-) diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs index ffadbed..c7da68b 100644 --- a/apps/desktop/src/opening_layout.rs +++ b/apps/desktop/src/opening_layout.rs @@ -203,6 +203,25 @@ pub(crate) fn move_text(game: &Game, node: NodeId) -> Option { }) } +/// "1. e4 e5 2. Nf3": the moves from the start to `node` with move numbers. +pub(crate) fn path_text(game: &Game, node: NodeId) -> String { + let mut words = Vec::new(); + for id in game.path(node).into_iter().skip(1) { + let Some(mv) = game.game_move(id) else { + continue; + }; + let san = crate::san::show(&mv.san).into_owned(); + match game.move_number(id) { + Some((number, Color::White)) => words.push(format!("{number}. {san}")), + Some((number, Color::Black)) if words.is_empty() => { + words.push(format!("{number}… {san}")) + } + _ => words.push(san), + } + } + words.join(" ") +} + /// The symbol of a move's assessment (`!`, `?!` …) and its colour for text. pub(crate) fn assessment(game: &Game, node: NodeId, dark: bool) -> Option<(&'static str, Color32)> { let nag = game diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs index 2f9fb60..01fe24c 100644 --- a/apps/desktop/src/opening_lines.rs +++ b/apps/desktop/src/opening_lines.rs @@ -252,21 +252,7 @@ impl OpeningLinesUi { /// "… 4. Ba4 Nf6": the moves to a node in the notation of the application. fn path_label(&self, node: NodeId) -> String { - let mut words = Vec::new(); - for id in self.game.path(node).into_iter().skip(1) { - let Some(mv) = self.game.game_move(id) else { - continue; - }; - let san = crate::san::show(&mv.san).into_owned(); - match self.game.move_number(id) { - Some((number, Color::White)) => words.push(format!("{number}. {san}")), - Some((number, Color::Black)) if words.is_empty() => { - words.push(format!("{number}… {san}")) - } - _ => words.push(san), - } - } - words.join(" ") + layout::path_text(&self.game, node) } fn below(&self, path: &[String]) -> Option<(usize, usize, usize)> { diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index c2aadfa..9186520 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -2231,7 +2231,16 @@ impl RepertoireUi { .split_whitespace() .map(str::to_owned) .collect(); - let label = through.join(" "); + // The label in the notation of the application, as «Lines» gives it. + let label = self + .selected + .as_ref() + .and_then(|id| self.library.repertoire(id)) + .map(|r| r.game()) + .and_then(|game| { + layout::node_at(&game, &through).map(|at| layout::path_text(&game, at)) + }) + .unwrap_or_else(|| through.join(" ")); self.start(SessionKind::Branch { through, label }, settings); } "menu" => self.debug_menu = true, From 2128573b5d9dce05695489ee5cd077608dfbb045 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:13:19 +0300 Subject: [PATCH 15/31] opening trainer: the section header has the game screen's height (separator at 52, the same board) --- apps/desktop/src/widgets.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index 461b66f..cec25ad 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -43,8 +43,13 @@ pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { clicked.1 = settings_button(ui, compact).clicked(); ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - ui.add(egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate()) + // The rows of the game screen's header (game_view.rs): the same height. + ui.horizontal(|ui| { + ui.add( + egui::Label::new(egui::RichText::new(title).strong().size(16.0)).truncate(), + ) .on_hover_text(title); + }); let sub = ui.add( egui::Label::new( egui::RichText::new(if subtitle.is_empty() { " " } else { subtitle }) @@ -58,6 +63,7 @@ pub fn section_header_sub(ui: &mut Ui, back: &str, title: &str, subtitle: &str) }); }); }); + ui.add_space(4.0); clicked } From f717644b6d2ee5c20a72a82fe87b83ab0c38393b Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:14:57 +0300 Subject: [PATCH 16/31] =?UTF-8?q?opening=20trainer:=20=C2=ABReview=20all?= =?UTF-8?q?=C2=BB=20is=20always=20in=20the=20card's=20button=20row=20when?= =?UTF-8?q?=20the=20repertoire=20has=20moves;=20a=20narrow=20panel=20narro?= =?UTF-8?q?ws=20the=20buttons?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/repertoire_ui.rs | 35 +++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 9186520..aa6a442 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -1583,16 +1583,33 @@ impl RepertoireUi { let gap = ui.spacing().item_spacing.x; let pad = 2.0 * ui.spacing().button_padding.x + 2.0; let room = ui.available_width(); - let main_w = MAIN_W.min((room - LINES_W - gap).max(0.0)); - // Buttons are never cut: in a narrow panel the third one (always - // in the `⋯` menu too) stays out. + // The row is the same in every state with moves: «Review all» is + // there unless the main button already is it. A narrow panel makes + // the buttons narrower, down to their words. + let third = !matches!( + state, + CardState::Empty + | CardState::Failed(_) + | CardState::Counting + | CardState::OtherColor + ) && !matches!(item, Some(MenuItem::ReviewAll)); + let main_need = text_width(ui, &label, 14.0) + pad; + let lines_need = text_width(ui, tr("Lines…"), 14.0) + pad; let third_need = text_width(ui, tr("Review all"), 14.0) + pad; - let lines_w = LINES_W.min(text_width(ui, tr("Lines…"), 14.0) + pad + 12.0); - let third_w = room - main_w - lines_w - 2.0 * gap; - let third = - matches!(state, CardState::OnlyNew { .. }) && third_w >= third_need; - let lines_w = if third { lines_w } else { LINES_W }; - let third_w = third_w.min(THIRD_W.max(third_need)); + let (main_w, lines_w, third_w) = if third { + let spare = room - main_need - lines_need - third_need - 2.0 * gap; + let grow = |need: f32, most: f32, spare: &mut f32| { + let add = (most - need).max(0.0).min(spare.max(0.0)); + *spare -= add; + need + add + }; + let mut spare = spare; + let main_w = grow(main_need, MAIN_W, &mut spare); + let lines_w = grow(lines_need, LINES_W, &mut spare); + (main_w, lines_w, grow(third_need, THIRD_W, &mut spare)) + } else { + (MAIN_W.min((room - LINES_W - gap).max(0.0)), LINES_W, 0.0) + }; let response = ui .add_enabled_ui(enabled, |ui| { crate::widgets::primary_wide(ui, &label, main_w) From 358e1bf08e611739a47355cbc78f00b78d8d4a18 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:16:55 +0300 Subject: [PATCH 17/31] =?UTF-8?q?opening=20trainer:=20no=20=C2=AB0=20left?= =?UTF-8?q?=C2=BB=20on=20the=20summary;=20=C2=ABLearned=20X=20of=20Y=20?= =?UTF-8?q?=C2=B7=20learning=20Z=C2=BB;=20S0=20shows=20the=20repertoire's?= =?UTF-8?q?=20start;=20=C2=ABSwitch=20colour=20to=20=E2=80=A6=C2=BB=20in?= =?UTF-8?q?=20the=20menu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/i18n.rs | 54 +++++++++++------------ apps/desktop/src/opening_session.rs | 11 +++-- apps/desktop/src/opening_session_tests.rs | 4 +- apps/desktop/src/repertoire_ui.rs | 30 ++++++------- apps/desktop/src/repertoire_ui_tests.rs | 2 +- 5 files changed, 50 insertions(+), 51 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index fedcf03..c2ad246 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -1119,26 +1119,26 @@ const ROWS: &[[&str; 9]] = &[ "Бұл репертуарды оқу мүмкін болмады", ], [ - "Play as Black", - "Играть чёрными", - "Jouer les Noirs", - "Mit Schwarz spielen", - "Jugar con negras", - "Gioca con il Nero", - "Jogar de pretas", - "Qora bilan o‘ynash", - "Қарамен ойнау", + "Switch colour to Black", + "Сменить цвет на чёрные", + "Passer aux Noirs", + "Farbe auf Schwarz wechseln", + "Cambiar a negras", + "Passa al Nero", + "Mudar para pretas", + "Rangni qoraga almashtirish", + "Түсті қараға ауыстыру", ], [ - "Play as White", - "Играть белыми", - "Jouer les Blancs", - "Mit Weiß spielen", - "Jugar con blancas", - "Gioca con il Bianco", - "Jogar de brancas", - "Oq bilan o‘ynash", - "Ақпен ойнау", + "Switch colour to White", + "Сменить цвет на белые", + "Passer aux Blancs", + "Farbe auf Weiß wechseln", + "Cambiar a blancas", + "Passa al Bianco", + "Mudar para brancas", + "Rangni oqqa almashtirish", + "Түсті аққа ауыстыру", ], [ "Lines…", @@ -1482,15 +1482,15 @@ const ROWS: &[[&str; 9]] = &[ "{y} жүрістің {x} үйренілді", ], [ - "{k} in progress", - "учится: {k}", - "{k} en cours", - "{k} in Arbeit", - "{k} en curso", - "{k} in corso", - "{k} em andamento", - "o‘rganilmoqda: {k}", - "үйренілуде: {k}", + "learning {k}", + "учится {k}", + "en cours {k}", + "in Arbeit {k}", + "en curso {k}", + "in corso {k}", + "em andamento {k}", + "o‘rganilmoqda {k}", + "үйренілуде {k}", ], [ "Add PGN to “{name}”", diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index 425e372..43f165e 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -1766,12 +1766,11 @@ impl OpeningSessionUi { fn counter(&self, state: &State) -> (String, &'static str) { match &self.kind { SessionKind::Daily => { - let left = if matches!(state, State::Summary) && !self.stopped { - 0 - } else { - self.session.remaining() - }; - (left.to_string(), tr("left")) + // A finished session has nothing left: no «0 left» on its summary. + if matches!(state, State::Summary) && !self.stopped { + return (String::new(), ""); + } + (self.session.remaining().to_string(), tr("left")) } SessionKind::ReviewAll | SessionKind::Branch { .. } => { let k = if self.is_finished() { diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index 5d70016..e2f1b0a 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -1423,11 +1423,11 @@ fn a_daily_session_brings_mistakes_and_hints_back_and_its_numbers_agree() { // e4 wrong, e4 right, Nf3 right, Bb5 right. assert_eq!(independent, 4); f.ui.compute_summary(); - f.ui.compute_summary(); let summary = f.ui.summary.as_ref().unwrap(); assert_eq!(summary.more_new, 0); assert!(!summary.next_review.is_empty()); - assert_eq!(f.ui.counter(&State::Summary).0, "0"); + // A finished session shows no «0 left». + assert_eq!(f.ui.counter(&State::Summary).0, ""); } #[test] diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index aa6a442..4a7e945 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -66,6 +66,8 @@ static NEXT_JOB: AtomicU64 = AtomicU64::new(1); #[derive(Clone)] struct RowIndex { start: Chess, + /// The position a session starts from (S0 shows it, not the library's preview). + initial: Chess, last_move: Option<(Square, Square)>, has_moves: bool, } @@ -452,6 +454,7 @@ impl RepertoireUi { r.id.clone(), RowIndex { start: layout::position_of(&game, start), + initial: layout::position_of(&game, NodeId::ROOT), last_move: layout::last_move(&game, start), has_moves: !game.children(NodeId::ROOT).is_empty(), }, @@ -1103,7 +1106,7 @@ impl RepertoireUi { { let side = layout::side_of(settings, &preparing.id); let index = self.index.get(&preparing.id); - let start = index.map(|row| row.start.clone()).unwrap_or_default(); + let start = index.map(|row| row.initial.clone()).unwrap_or_default(); let subtitle = preparing.kind.subtitle(side); let view = PreparingView { name: &preparing.name, @@ -1115,7 +1118,7 @@ impl RepertoireUi { }, position: &start, orientation: layout::orientation(side), - last_move: index.and_then(|row| row.last_move), + last_move: None, lines: preparing.kind != SessionKind::Daily, }; for action in show_preparing(ui, settings, &mut self.board, &view) { @@ -2433,8 +2436,8 @@ fn main_button(state: &CardState, side: LearningSide) -> (String, bool, Option (tr("Add PGN…").to_owned(), true, Some(MenuItem::AddPgn)), CardState::OtherColor => ( match side { - LearningSide::White => tr("Play as Black"), - LearningSide::Black => tr("Play as White"), + LearningSide::White => tr("Switch colour to Black"), + LearningSide::Black => tr("Switch colour to White"), } .to_owned(), true, @@ -2474,15 +2477,12 @@ fn progress(ui: &mut Ui, stats: Option<&RowStats>) { (stats.learnt, stats.total, stats.learning) }); if stats.is_some() { - layout::line( - ui, - trf("Learned {x} of {y} moves", &[("x", &learnt), ("y", &total)]), - ); - } - if learning > 0 { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(RichText::new(trf("{k} in progress", &[("k", &learning)])).weak()); - }); + let mut text = trf("Learned {x} of {y} moves", &[("x", &learnt), ("y", &total)]); + // The bar's second segment, named where the bar is read. + if learning > 0 { + text = format!("{text} · {}", trf("learning {k}", &[("k", &learning)])); + } + layout::line(ui, text); } }); } @@ -2509,8 +2509,8 @@ fn menu_items( ui, true, match side { - LearningSide::White => tr("Play as Black"), - LearningSide::Black => tr("Play as White"), + LearningSide::White => tr("Switch colour to Black"), + LearningSide::Black => tr("Switch colour to White"), }, MenuItem::SwitchColor, ); diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index fee0c71..f8613e8 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -172,7 +172,7 @@ fn the_card_says_what_to_do_in_every_state() { assert!(!main_button(&CardState::Counting, LearningSide::White).1); assert_eq!( main_button(&CardState::OtherColor, LearningSide::White).0, - tr("Play as Black") + tr("Switch colour to Black") ); assert_eq!( card_texts(&CardState::Review { due: 3, new: 10 }, LearningSide::White), From e59f01c47d571e0fbd1ed076a8c215a4828d269a Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:20:25 +0300 Subject: [PATCH 18/31] =?UTF-8?q?docs:=20opening=20trainer=20v2=20?= =?UTF-8?q?=E2=80=94=20task,=20decisions,=20changelog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 ++ docs/decisions.md | 13 +++++++++++++ docs/dev/tasks.md | 8 ++++++++ 3 files changed, 23 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec0ac3..8d9ac46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Desktop opening training rewritten to be simpler: one screen with repertoires and a clear daily session (reviews plus up to 10 new moves), new moves are shown before they are asked, mistakes show the right move and return in the same session, PGN comments and opening names are shown. Review all, train a branch and a lines view remain; modes, context parameters, the statistics dashboard and the both-colours mode are gone. Two example repertoires (Spanish for White, Najdorf for Black) are added on first use. Saved progress is kept. + ## [2.3.0] — 2026-11-06 - Desktop opening training (α version) avoids repeated PGN parsing and repeated context planning during diff --git a/docs/decisions.md b/docs/decisions.md index b061184..ce4789a 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -509,3 +509,16 @@ PGN для точного выбора пометок, минимальная г Публикация через main и штатный фильтр GitHub; существующие теги не меняются. Незавершённых изменений продуктовых правил NAG и авторских стрелок в выпуске нет: все включённые ветки изучаются, рисунки PGN сами не меняют тип зачёта. + +## Тренировка дебюта v2 (2026-11-26) + +Владелец поручил оркестратору самостоятельно переработать раздел: «проще, понятнее, функционально», остальные разделы не трогать. Принято (концепция `docs/design/opening-trainer-concept-2026-11-26.md`, спецификация `docs/design/opening-trainer-v2-spec.md`): + +- Ядро сохраняется: LearningItem `(профиль, FEN4, UCI)`, SRS, несколько собственных ответов (2.3.0), формат файлов и типы Settings без изменений. +- Занятие = все ходы к повторению + до 10 новых, «Ещё 10 новых». Подача линией от начала; спрашиваются только ходы к повторению и новые; новый ход сначала показывается стрелкой; ошибка показывает правильный ход и возвращается в том же занятии. Только что показанные ходы по расписанию возвращаются через минуту, поэтому следующее занятие в тот же день включает их. +- Прогресс — в ходах: «Выучено X из Y · учится Z». +- Из UI удалены выбор режима и порядка, шесть параметров контекста, дашборд с вкладками и графиками, отчёт Branches/Lines, режим «за оба цвета». Сохранённые значения остаются на диске, но не действуют; лимит `max_plies` снимается при загрузке; незавершённые сессии 2.x не возобновляются. Это заменяет UI-части решений 2026-11-04/05. +- Вторичные действия: «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты». Редактирования ходов на доске в этом этапе нет. Строка ходов линии в занятии не показывается (решение владельца 03.11). +- Цвет задаётся при импорте/создании. При первом открытии раздела (файла библиотеки ещё нет) создаются два примера: Испанская партия (белые) и Найдорф (чёрные); удалённые примеры не возвращаются. +- Неверный ход на только что показанном новом ходе ошибкой не считается: «Не тот ход» ~0,4 с, затем снова показ. + diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index ca6bed5..f4917ee 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -280,6 +280,14 @@ - **Замеры:** в release-probe на копии истории из 6049 событий обработка 49 уже показанных ходов ускорилась с 2226 до 46 мс; расчёт контекста на пути 513 полуходов — с 73,2 до 1,39 мс. Проверена сохранность каждого события и идемпотентность повторной записи. - **Статус:** выпущено в 2.3.0. Workspace — 696 passed, 17 ignored; Clippy/fmt, desktop build и wasm check успешны. В изолированном приложении проверены ответ программы после хода пользователя с большой историей, пауза/продолжение, сохранность PGN и отсутствие дублей. Подробности: `docs/qa/training-performance-2026-11-06.md`. +### 40. Тренировка дебюта v2: простой и понятный раздел (2026-11-26) +- **Статус:** реализовано в ветке `feature/opening-trainer-v2` (от 2.3.0), принято дизайн-ревью с исправлениями; ждёт решения владельца о слиянии в `main` и выпуске. +- **Суть (владелец):** переписать раздел как ChessTempo, но проще и понятнее; остальные разделы не менять. Решения делегированы оркестратору — `docs/decisions.md`, «Тренировка дебюта v2». +- **Сделано:** один экран «Репертуары» (таблица + карточка: «Сегодня: N повторить · M новых», «Выучено X из Y · учится Z», «Тренироваться», «Варианты…», «Повторить всё»); занятие — линия от начала, новый ход показывается стрелкой, на ошибке — правильный ход, ошибка возвращается в том же занятии, комментарии и название дебюта; итог; «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты»; цвет при импорте; два стартовых репертуара (Испанская за белых, Найдорф за чёрных). Удалены режимы/порядки, окно параметров, дашборд с графиками, Branches/Lines, режим «за оба цвета», скрытый лимит глубины; ~13 тыс. строк старого UI. +- **Проверено:** fmt, clippy `-D warnings`; trainer 200 passed, desktop 161 passed / 3 ignored (перепроверено оркестратором); mobile-api check. Дизайн-ревью `docs/qa/opening-trainer-v2-design-review.md`: скачков нет (0 px в серии состояний), шапка и доска совпадают с экраном партии после исправлений. +- **Не проверено:** wasm (на ноутбуке нет цели `wasm32-unknown-unknown`), английский интерфейс, клавиатура, масштаб 1, длинные имена/большой список, 960×600 для экранов занятия; независимый функциональный прогон tester не проводился (бюджет). +- **Осталось:** перенести незакоммиченные временные стрелки из основной папки; удалить мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) отдельной задачей. + ## Сделано (пусто) From af0a89a6f6913ecdb6ddbc14f66f112349d8951e Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:37:11 +0300 Subject: [PATCH 19/31] =?UTF-8?q?qa:=20opening=20trainer=20v2=20=E2=80=94?= =?UTF-8?q?=20user=20data=20from=202.2/2.3=20is=20read=20unchanged?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/qa/opening-trainer-v2-migration.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/qa/opening-trainer-v2-migration.md diff --git a/docs/qa/opening-trainer-v2-migration.md b/docs/qa/opening-trainer-v2-migration.md new file mode 100644 index 0000000..ac253e5 --- /dev/null +++ b/docs/qa/opening-trainer-v2-migration.md @@ -0,0 +1,14 @@ +# Тренировка дебюта v2: данные пользователя 2.2/2.3 (оркестратор, 2026-11-27) + +Независимый tester не запустился (лимит кредитов); сценарий сохранности данных выполнен оркестратором вручную. + +- Копии реальных `~/.local/share/chesspenguin/repertoires.json` (v1, 5 репертуаров) и `repertoire-training.json` (v3) + и `~/.config/chesspenguin/settings.json` помещены в изолированный профиль `/tmp/opencode/mig`; запуск + `CP_REPERTOIRE=library`, снимок `target/qa-opening-v2/migration-library.png`. +- **PASS:** все 5 репертуаров видны, счётчики построены («Испанка: Сегодня 1 повторить · 10 новых, учится 1»). +- **PASS:** sha256 обоих файлов до и после запуска совпадают (простое открытие ничего не переписывает). +- **PASS:** settings.json — ни один ключ не потерян; изменилось только `last_version`. +- **Замечание:** в старых данных цвет хранился только для одного репертуара (`repertoire_modes`), остальные + открываются белыми, как и в 2.3. Если репертуар за чёрных — «⋯ → Сменить цвет на чёрные». Не дефект v2. +- «Франзузкая» (PGN 95 байт, без ходов) — прочерки в таблице, ожидаемо. +- Не проверено: занятие на этих данных и последующая запись, импорт/экспорт с sha256, сценарии 2–5 плана tester. From e938abf0c5d6f9718714e70742ceec52399b8ff4 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:43:37 +0300 Subject: [PATCH 20/31] =?UTF-8?q?qa:=20opening=20trainer=20v2=20=E2=80=94?= =?UTF-8?q?=20functional=20scenarios=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/qa/opening-trainer-v2-functional.md | 49 ++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/qa/opening-trainer-v2-functional.md diff --git a/docs/qa/opening-trainer-v2-functional.md b/docs/qa/opening-trainer-v2-functional.md new file mode 100644 index 0000000..f0fcf6f --- /dev/null +++ b/docs/qa/opening-trainer-v2-functional.md @@ -0,0 +1,49 @@ +# Тренировка дебюта v2: функциональная проверка (tester, 2026-11-27) + +Окружение: ветка feature/opening-trainer-v2 @ af0a89a, бинарник `/tmp/opencode/v2-target/debug/chesspenguin` +(собран 02:18, после последнего кодового коммита 358e1bf), Linux, Wayland (`wayland-1`, Xwayland `:1`). +Изолированные профили `/tmp/opencode/qa-ot/p*` (XDG_CONFIG_HOME, XDG_DATA_HOME, CP_REPERTOIRE_DIR). +Управление — dev-хуки (`docs/qa/opening-trainer-v2-devhooks.md`) и `CP_KEYS`; доказательства — снимки +`CP_SCREENSHOT` и содержимое `repertoires.json` / `repertoire-training.json`. + +| # | Сценарий | Итог | +| --- | --- | --- | +| 1 | Свежий профиль: два примера, цвета; удаление не возвращается | PASS | +| 2 | Импорт najdorf.pgn за чёрных, экспорт, sha256 исходника | PASS | +| 3 | Стрелка → вопрос без стрелки; ошибка возвращается 1 раз; Esc сохраняет; «Повторить всё», «Ветка» | PASS | +| 4 | `git diff main` вне раздела | PASS (с оговоркой) | + +1. Пустой профиль → `repertoires.json` revision 1: «Испанская партия» (карточка «Вы играете белыми», белый король), + «Сицилианская защита: Найдорф» (доска перевёрнута, «Вы играете чёрными»). `CP_REPERTOIRE_DELETE=1` на Найдорфе → + revision 2, остался один; перезапуск — один. Доп.: пустой список `[]` после перезапуска остаётся пустым. +2. Диалог импорта сам выбрал «Чёрные» («Выбрано по PGN — проверьте»), «Партий: 3 · вариантов: 3 · ваших ходов: 11» + (пересчитано вручную — верно); цвет записан в settings (`repertoire_modes … Black`). Три партии слиты в одно дерево, + экспорт содержит все три линии (6.Be3/6.Bg5/6.Be2). В examples/najdorf.pgn нет комментариев и NAG, поэтому + дополнительно импортирован/экспортирован собственный файл: комментарий у корня, у хода и в ветке, RAV 2 уровней, + `$1 $5 $14`, нестандартный тег `[MyTag]` — экспорт семантически совпал (отличие только перенос строк). + sha256 до/после: najdorf.pgn `fd406e1f…7302` (и копия, и examples/), annot.pgn `c7348f07…8abd` — совпали. +3. Испанская, 1-е занятие: «Новый ход · Сыграйте 1. e4 — он показан стрелкой», зелёная стрелка e2–e4. + `e2e4 settle g1f3 settle stop` → `repertoire-training.json` создан (PREVIEWED e2e4, g1f3; next_review +60 с); + карточка после возврата: «Сегодня: 2 повторить · 10 новых», «учится 2». Через 60 с 2-е занятие: + «Ваш ход · Сыграйте ход из репертуара», стрелки нет. `wrong` + ответы до конца: INCORRECT e2e4(a2a3) → + REPLAY_AFTER_ERROR e2e4 → CORRECT g1f3 → 10 PREVIEWED → CORRECT e2e4 (ровно один возврат, в конце); + итог «Верно с первого раза 1 · Ошибки 1 · Новых ходов 10», «Что запомнить: 1. e4». + «Повторить всё подряд»: 22 вопроса (12 верных + 10 показов = все 22 хода), итог «3 из 3 вариантов». + «Тренировать эту ветку» (после 3…Nf6): 5 ходов Берлинской ветки, итог «1 из 1». +4. Вне раздела в коде: `lib.rs` — только замена объявлений модулей, `widgets.rs` — только добавления (38 строк). + Оговорка: изменены также `i18n.rs` (−202 старых ключа; ни один не упоминается в других `.rs` вне i18n — + проверено скриптом) и `crates/trainer` (только добавления: 2 новых файла, 2 строки `mod`). Ветка не отстаёт от main. + +## Дефекты + +Не найдено. + +## Не подтвердилось / не проверено + +- Подтверждение удаления с клавиатуры: через `CP_KEYS` (`Enter`, `Tab Space`, `Tab Enter`, `Shift+Tab Space`) + удалить не удалось — диалог закрывался без удаления. Enter=«Отмена» в опасном диалоге задуман кодом + (`dialog_buttons`, repertoire_ui.rs:2560); дошла ли фокусировка через инъекцию так же, как с реальной клавиатуры, + не установлено → дефектом не считаю, нужна ручная проверка. +- Клики мышью, перетаскивание, «Не тот ход» ~0,4 с на показанном ходе, «Ещё 10 новых», X11-сессия, HiDPI — не проверялись. +- Наблюдение без оценки: при каждой подаче линии пишутся события AUTO_CONTEXT (в «Повторить всё» — 282 на 22 вопроса); + на расписание не влияет по результатам выше, но журнал растёт. From 67044d7b4838cf716b414e2466d900e8bd4556cb Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 02:43:52 +0300 Subject: [PATCH 21/31] =?UTF-8?q?docs:=20task=2040=20=E2=80=94=20QA=20resu?= =?UTF-8?q?lts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/dev/tasks.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index f4917ee..0d7f72f 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -285,7 +285,7 @@ - **Суть (владелец):** переписать раздел как ChessTempo, но проще и понятнее; остальные разделы не менять. Решения делегированы оркестратору — `docs/decisions.md`, «Тренировка дебюта v2». - **Сделано:** один экран «Репертуары» (таблица + карточка: «Сегодня: N повторить · M новых», «Выучено X из Y · учится Z», «Тренироваться», «Варианты…», «Повторить всё»); занятие — линия от начала, новый ход показывается стрелкой, на ошибке — правильный ход, ошибка возвращается в том же занятии, комментарии и название дебюта; итог; «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты»; цвет при импорте; два стартовых репертуара (Испанская за белых, Найдорф за чёрных). Удалены режимы/порядки, окно параметров, дашборд с графиками, Branches/Lines, режим «за оба цвета», скрытый лимит глубины; ~13 тыс. строк старого UI. - **Проверено:** fmt, clippy `-D warnings`; trainer 200 passed, desktop 161 passed / 3 ignored (перепроверено оркестратором); mobile-api check. Дизайн-ревью `docs/qa/opening-trainer-v2-design-review.md`: скачков нет (0 px в серии состояний), шапка и доска совпадают с экраном партии после исправлений. -- **Не проверено:** wasm (на ноутбуке нет цели `wasm32-unknown-unknown`), английский интерфейс, клавиатура, масштаб 1, длинные имена/большой список, 960×600 для экранов занятия; независимый функциональный прогон tester не проводился (бюджет). +- **Не проверено:** wasm (на ноутбуке нет цели `wasm32-unknown-unknown`), английский интерфейс, клавиатура, масштаб 1, длинные имена/большой список, 960×600 для экранов занятия; клавиатурное подтверждение удаления, клики мышью, X11. Независимый tester: 4/4 PASS, `docs/qa/opening-trainer-v2-functional.md`; данные 2.2/2.3 читаются без изменений — `docs/qa/opening-trainer-v2-migration.md`. - **Осталось:** перенести незакоммиченные временные стрелки из основной папки; удалить мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) отдельной задачей. ## Сделано From 8ca7f43c3c82510596ce64ec8f69cef8d4736bb5 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:18:33 +0300 Subject: [PATCH 22/31] board: temporary right-button arrows and circles in play and opening training (ported from the working tree) --- CHANGELOG.md | 3 + apps/desktop/src/adjourned.rs | 1 + apps/desktop/src/board.rs | 257 +++++++++++++++++++++++++++- apps/desktop/src/board_search.rs | 1 + apps/desktop/src/game_view.rs | 20 ++- apps/desktop/src/large_db.rs | 1 + apps/desktop/src/opening_layout.rs | 1 + apps/desktop/src/opening_session.rs | 1 + apps/desktop/src/play.rs | 1 + apps/desktop/src/prep_ui.rs | 1 + docs/decisions.md | 1 + 11 files changed, 283 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d9ac46..187a897 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +- Desktop play and opening training support multiple temporary right-button arrows and circles + until the position changes. They are never written to PGN; shapes drawn in ordinary game + analysis remain PGN annotations and are saved only with the game. - Desktop opening training rewritten to be simpler: one screen with repertoires and a clear daily session (reviews plus up to 10 new moves), new moves are shown before they are asked, mistakes show the right move and return in the same session, PGN comments and opening names are shown. Review all, train a branch and a lines view remain; modes, context parameters, the statistics dashboard and the both-colours mode are gone. Two example repertoires (Spanish for White, Najdorf for Black) are added on first use. Saved progress is kept. ## [2.3.0] — 2026-11-06 diff --git a/apps/desktop/src/adjourned.rs b/apps/desktop/src/adjourned.rs index 718df2d..dfa318d 100644 --- a/apps/desktop/src/adjourned.rs +++ b/apps/desktop/src/adjourned.rs @@ -124,6 +124,7 @@ impl Card { circles: &[], badge: None, interactive: false, + temporary_shapes: false, show_coords: false, theme: settings.board_theme.theme(), pieces: settings.piece_set, diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs index 3efad34..9629a34 100644 --- a/apps/desktop/src/board.rs +++ b/apps/desktop/src/board.rs @@ -44,6 +44,9 @@ pub struct BoardState { shape_from: Option, /// A shape drawn this frame, for the game to take (`take_shape`). shape: Option, + /// Temporary shapes in play and training; never written to the PGN. + temporary_shapes: Vec, + temporary_position: Option, /// The position drawn last: a different one next frame is animated from it. shown: Option, anim: Option, @@ -92,6 +95,32 @@ impl BoardState { self.shape.take() } + pub fn draw_temporary(&mut self, drawn: Drawn, pos: &Chess) { + self.shape = None; + self.sync_temporary_position(pos); + let same = |shape: &Drawn| match (*shape, drawn) { + (Drawn::Arrow(_, af, at), Drawn::Arrow(_, bf, bt)) => af == bf && at == bt, + (Drawn::Circle(_, a), Drawn::Circle(_, b)) => a == b, + _ => false, + }; + if let Some(index) = self.temporary_shapes.iter().position(same) { + if self.temporary_shapes[index] == drawn { + self.temporary_shapes.remove(index); + } else { + self.temporary_shapes[index] = drawn; + } + } else { + self.temporary_shapes.push(drawn); + } + } + + fn sync_temporary_position(&mut self, pos: &Chess) { + if self.temporary_position.as_ref() != Some(pos) { + self.temporary_shapes.clear(); + self.temporary_position = Some(pos.clone()); + } + } + /// A piece is selected or dragged, or a promotion is being chosen. pub fn is_busy(&self) -> bool { self.selected.is_some() || self.drag.is_some() || self.promotion.is_some() @@ -176,6 +205,8 @@ pub struct BoardView<'a> { /// Move assessment shown on the destination square of the last move ("??" in red, …). pub badge: Option, pub interactive: bool, + /// Right-button shapes stay until the position changes instead of becoming PGN comments. + pub temporary_shapes: bool, pub show_coords: bool, pub theme: BoardTheme, pub pieces: PieceSet, @@ -216,6 +247,11 @@ impl BoardView<'_> { state.selected = None; state.drag = None; } + if self.temporary_shapes { + state.sync_temporary_position(self.pos); + } else { + state.temporary_shapes.clear(); + } // --- input ----------------------------------------------------------------------- if (self.interactive || premoving) && state.promotion.is_none() { @@ -274,10 +310,11 @@ impl BoardView<'_> { .and_then(|p| geo.square_at(p)); let color = shape_color_for(ui.input(|i| i.modifiers)); if let Some(from) = state.shape_from.take() { - state.shape = Some(match to { + let drawn = match to { Some(to) if to != from => Drawn::Arrow(color, from, to), _ => Drawn::Circle(color, from), - }); + }; + self.record_shape(state, drawn); } } if response.secondary_clicked() { @@ -285,7 +322,7 @@ impl BoardView<'_> { state.premove = None; if let Some(sq) = pointer.and_then(|p| geo.square_at(p)) { let color = shape_color_for(ui.input(|i| i.modifiers)); - state.shape = Some(Drawn::Circle(color, sq)); + self.record_shape(state, Drawn::Circle(color, sq)); } } } @@ -439,6 +476,31 @@ impl BoardView<'_> { for a in self.arrows { draw_arrow(&painter, &geo, a); } + for drawn in &state.temporary_shapes { + let color = shape_preview_color(match *drawn { + Drawn::Arrow(color, _, _) | Drawn::Circle(color, _) => color, + }); + match *drawn { + Drawn::Arrow(_, from, to) => draw_arrow( + &painter, + &geo, + &Arrow { + from, + to, + color, + weight: 0.9, + }, + ), + Drawn::Circle(_, square) => { + let r = geo.square_rect(square); + painter.circle_stroke( + r.center(), + sq_size * 0.46, + Stroke::new(sq_size * 0.07, color), + ); + } + } + } if let Some(from) = state.shape_from && response.dragged_by(egui::PointerButton::Secondary) { @@ -551,6 +613,14 @@ impl BoardView<'_> { result } + fn record_shape(&self, state: &mut BoardState, drawn: Drawn) { + if self.temporary_shapes { + state.draw_temporary(drawn, self.pos); + } else { + state.shape = Some(drawn); + } + } + /// The side that moves on this board now: the side to move, or the premoving one. fn mover(&self) -> Color { match self.premove { @@ -944,4 +1014,185 @@ mod tests { ); assert!(fadings.is_empty()); } + + fn board_frame( + ctx: &egui::Context, + state: &mut BoardState, + pos: &Chess, + time: f64, + events: Vec, + temporary_shapes: bool, + ) { + let mut view = Some(BoardView { + pos, + orientation: Color::White, + last_move: None, + arrows: &[], + circles: &[], + badge: None, + interactive: true, + temporary_shapes, + show_coords: false, + theme: crate::assets::BoardThemeId::Brown.theme(), + pieces: PieceSet::Cburnett, + animation: 0.0, + premove: None, + auto_queen: false, + alert: None, + }); + ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(400.0, 400.0), + )), + time: Some(time), + events, + ..Default::default() + }, + |ui| { + view.take().unwrap().show(ui, state); + }, + ) + .drop_without_applying_deltas(); + } + + fn right_click(at: egui::Pos2, modifiers: egui::Modifiers) -> Vec { + vec![ + egui::Event::ModifiersChanged(modifiers), + egui::Event::PointerMoved(at), + egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers, + }, + egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers, + }, + ] + } + + #[test] + fn temporary_shapes_accept_mouse_input_toggle_and_clear() { + let ctx = egui::Context::default(); + let pos = Chess::default(); + let mut state = BoardState::default(); + let sq = |s: &str| s.parse::().unwrap(); + let from = egui::pos2(225.0, 325.0); + let to = egui::pos2(225.0, 225.0); + board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), true); + board_frame( + &ctx, + &mut state, + &pos, + 0.1, + vec![ + egui::Event::PointerMoved(from), + egui::Event::PointerButton { + pos: from, + button: egui::PointerButton::Secondary, + pressed: true, + modifiers: egui::Modifiers::NONE, + }, + ], + true, + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.2, + vec![egui::Event::PointerMoved(to)], + true, + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.3, + vec![egui::Event::PointerButton { + pos: to, + button: egui::PointerButton::Secondary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }], + true, + ); + assert_eq!( + state.temporary_shapes, + vec![Drawn::Arrow( + chess_core::ShapeColor::Green, + sq("e2"), + sq("e4") + )] + ); + assert!(state.shape.is_none()); + + let d5 = egui::pos2(175.0, 175.0); + board_frame( + &ctx, + &mut state, + &pos, + 0.4, + right_click(d5, egui::Modifiers::NONE), + true, + ); + assert_eq!(state.temporary_shapes.len(), 2); + board_frame( + &ctx, + &mut state, + &pos, + 0.5, + right_click(d5, egui::Modifiers::SHIFT), + true, + ); + assert_eq!( + state.temporary_shapes[1], + Drawn::Circle(chess_core::ShapeColor::Red, sq("d5")) + ); + board_frame( + &ctx, + &mut state, + &pos, + 0.6, + right_click(d5, egui::Modifiers::SHIFT), + true, + ); + assert_eq!(state.temporary_shapes.len(), 1); + + let mut next = pos.clone(); + next.play_unchecked("e4".parse::().unwrap().to_move(&pos).unwrap()); + board_frame(&ctx, &mut state, &next, 0.7, Vec::new(), true); + assert!(state.temporary_shapes.is_empty()); + } + + #[test] + fn analysis_shapes_remain_one_shot_events() { + let ctx = egui::Context::default(); + let pos = Chess::default(); + let mut state = BoardState::default(); + let at = egui::pos2(175.0, 175.0); + board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false); + board_frame( + &ctx, + &mut state, + &pos, + 0.1, + right_click(at, egui::Modifiers::NONE), + false, + ); + assert!(state.temporary_shapes.is_empty()); + assert_eq!( + state.take_shape(), + Some(Drawn::Circle( + chess_core::ShapeColor::Green, + "d5".parse().unwrap() + )) + ); + assert!(state.take_shape().is_none()); + } } diff --git a/apps/desktop/src/board_search.rs b/apps/desktop/src/board_search.rs index eeeb618..26b0514 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -519,6 +519,7 @@ impl SearchBoard { circles: &[], badge: None, interactive: true, + temporary_shapes: false, show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index c002191..500e9dc 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -1425,6 +1425,7 @@ impl GameView { && t.flash.is_none() && self.cursor == self.game.line_end(NodeId::ROOT) }), + temporary_shapes: self.play.is_some() || self.train.is_some(), show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, @@ -3881,6 +3882,21 @@ impl GameView { /// Dev hook (`CP_SHAPE=Ge2e4,Rd5`): shapes drawn on the board at the current move. pub fn debug_shapes(&mut self, spec: &str) { + let temporary = self.play.is_some() || self.train.is_some(); + let position = if temporary { + self.game.position(self.cursor).cloned() + } else { + None + }; + let mut record = |drawn| { + if temporary { + if let Some(pos) = &position { + self.board.draw_temporary(drawn, pos); + } + } else { + self.apply_shape(drawn); + } + }; for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) { let parsed = chess_core::parse_comment(&if item.len() > 3 { format!("[%cal {item}]") @@ -3891,12 +3907,12 @@ impl GameView { match p { CommentPart::Annotation(Annotation::Arrows(list)) => { for (c, a, b) in list { - self.apply_shape(board::Drawn::Arrow(c, a, b)); + record(board::Drawn::Arrow(c, a, b)); } } CommentPart::Annotation(Annotation::Squares(list)) => { for (c, sq) in list { - self.apply_shape(board::Drawn::Circle(c, sq)); + record(board::Drawn::Circle(c, sq)); } } _ => {} diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 9dc7bd0..e6ddc68 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -2503,6 +2503,7 @@ fn chip(ui: &mut Ui, c: &Condition) -> (bool, bool) { circles: &[], badge: None, interactive: false, + temporary_shapes: false, show_coords: false, theme: theme.theme(), pieces: *pieces, diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs index c7da68b..71898cd 100644 --- a/apps/desktop/src/opening_layout.rs +++ b/apps/desktop/src/opening_layout.rs @@ -440,6 +440,7 @@ pub(crate) fn still_board( circles: &annotations.circles, badge: annotations.badge, interactive: false, + temporary_shapes: false, show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index 43f165e..e1da76c 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -1652,6 +1652,7 @@ impl OpeningSessionUi { circles: &annotations.circles, badge: annotations.badge, interactive, + temporary_shapes: true, show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 1c8e8fc..1d566c9 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -1854,6 +1854,7 @@ fn position_block( circles: &[], badge: None, interactive: false, + temporary_shapes: false, show_coords: false, theme: settings.board_theme.theme(), pieces: settings.piece_set, diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs index d64443e..2c3c337 100644 --- a/apps/desktop/src/prep_ui.rs +++ b/apps/desktop/src/prep_ui.rs @@ -3577,6 +3577,7 @@ impl PrepScreen { circles: &[], badge: None, interactive: false, + temporary_shapes: false, show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, diff --git a/docs/decisions.md b/docs/decisions.md index ce4789a..4bd8d3f 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -71,6 +71,7 @@ - Enter на ходе открывает, Enter — готово, Esc — отмена (черновик выбрасывается); переход к другому ходу записывает; Shift+Enter — абзац; - значки: мышью в меню хода и в редакторе (обе группы — ход и позиция), дополнительно Ctrl+1…6 для `! ? !! ?? !? ?!`; - стрелки и цветные поля правой кнопкой на доске — в первой версии (цвет: без модификатора зелёный, Shift красный, Alt синий, Shift+Alt жёлтый; повтор снимает); + - 2026-11-26: в игре и тренировках можно держать несколько временных стрелок и кругов до смены позиции; они не записываются в PGN. В обычном анализе фигуры остаются комментариями `[%cal]`/`[%csl]` и сохраняются только вместе с партией обычным действием сохранения. Модификаторы цвета и отказ от рисования пальцем на Android не меняются; - книжные комментарии: нетронутые байты не меняются, команды `[%cal]`, `[%clk]`, `[%eval]` сохраняются. ## Игра с компьютером (Maia), 2026-10-25 From 7cb0291e4899c3f629949e85b50009b7c8ba8523 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:22:02 +0300 Subject: [PATCH 23/31] =?UTF-8?q?opening=20trainer:=20the=20=C2=ABLearned?= =?UTF-8?q?=C2=BB=20column=20has=20the=20card's=20two-segment=20bar=20and?= =?UTF-8?q?=20a=20hint=20on=20what=20=C2=ABlearned=C2=BB=20takes;=20=C2=AB?= =?UTF-8?q?no=20moves=C2=BB=20for=20an=20empty=20repertoire;=20the=20summa?= =?UTF-8?q?ry=20shows=20=C2=ABLearning=20+N=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/i18n.rs | 44 ++++++++++++++++++ apps/desktop/src/opening_session.rs | 32 ++++++++++++- apps/desktop/src/opening_session_tests.rs | 20 ++++++++ apps/desktop/src/repertoire_ui.rs | 56 ++++++++++++++++++++--- 4 files changed, 145 insertions(+), 7 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index c2ad246..19b6c24 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -810,6 +810,50 @@ const ROWS: &[[&str; 9]] = &[ "Shox: {path}", "Тармақ: {path}", ], + [ + "Learning", + "Учится", + "En cours", + "In Arbeit", + "En curso", + "In corso", + "Em andamento", + "O‘rganilmoqda", + "Үйренілуде", + ], + [ + "no moves", + "нет ходов", + "aucun coup", + "keine Züge", + "sin jugadas", + "nessuna mossa", + "sem lances", + "yurish yo‘q", + "жүріс жоқ", + ], + [ + "The repertoire has no moves yet: import a PGN or add a line from a game", + "В репертуаре пока нет ходов: импортируйте PGN или добавьте линию из партии", + "Le répertoire n’a pas encore de coups : importez un PGN ou ajoutez une ligne depuis une partie", + "Das Repertoire hat noch keine Züge: PGN importieren oder eine Linie aus einer Partie hinzufügen", + "El repertorio aún no tiene jugadas: importe un PGN o añada una línea desde una partida", + "Il repertorio non ha ancora mosse: importa un PGN o aggiungi una linea da una partita", + "O repertório ainda não tem lances: importe um PGN ou adicione uma linha de uma partida", + "Repertuarda hali yurishlar yo‘q: PGN import qiling yoki partiyadan liniya qo‘shing", + "Репертуарда әзірге жүріс жоқ: PGN импорттаңыз немесе партиядан желі қосыңыз", + ], + [ + "Learned {x}, learning {z}, {y} moves in all. A move counts as learned after three correct answers in a row without a hint — usually over several days of reviews.", + "Выучено {x}, учится {z}, всего {y} ходов. Ход считается выученным после трёх верных ответов подряд без подсказки — обычно за несколько дней повторений.", + "Appris {x}, en cours {z}, {y} coups au total. Un coup est appris après trois bonnes réponses d’affilée sans indice — en général sur plusieurs jours de révisions.", + "Gelernt {x}, in Arbeit {z}, insgesamt {y} Züge. Ein Zug gilt als gelernt nach drei richtigen Antworten in Folge ohne Hinweis — meist über mehrere Tage Wiederholung.", + "Aprendidas {x}, en curso {z}, {y} jugadas en total. Una jugada se da por aprendida tras tres respuestas correctas seguidas sin pista; normalmente en varios días de repaso.", + "Imparate {x}, in corso {z}, {y} mosse in tutto. Una mossa è imparata dopo tre risposte giuste di fila senza suggerimento — di solito in alcuni giorni di ripasso.", + "Aprendidos {x}, em andamento {z}, {y} lances no total. Um lance conta como aprendido após três respostas certas seguidas sem dica — normalmente em vários dias de revisão.", + "O‘rganilgan {x}, o‘rganilmoqda {z}, jami {y} yurish. Yurish ketma-ket uchta to‘g‘ri javobdan keyin (yordamsiz) o‘rganilgan hisoblanadi — odatda bir necha kunlik takrorlashda.", + "Үйренілген {x}, үйренілуде {z}, барлығы {y} жүріс. Жүріс кеңессіз қатарынан үш дұрыс жауаптан кейін үйренілген саналады — әдетте бірнеше күндік қайталауда.", + ], [ "New moves left", "Новых ходов осталось", diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index e1da76c..ff0cfb5 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -19,7 +19,7 @@ use trainer::repertoire::{ LearningPresentation, LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, LearningSessionTarget, LearningSide, LearningStore, Library, PersistedSessionAttempt, RepertoireId, SrsSettings, StatsScope, TrainingAttempt, TrainingEventType, - active_learning_keys, fen4, + active_learning_keys, aggregate_scope, fen4, }; use web_time::{Instant, SystemTime, UNIX_EPOCH}; @@ -210,6 +210,9 @@ enum State { /// Computed once when the result is shown. struct Summary { next_review: String, + /// How many more moves are learned, and learning, than when the session began. + learnt_gain: usize, + learning_gain: usize, /// Moves never shown yet, all of them (the «more new» button takes up to 10). unseen: usize, more_new: usize, @@ -240,6 +243,10 @@ pub struct OpeningSessionUi { repertoire_answers: BTreeSet, /// Active answers of the whole repertoire, for the result. repertoire_keys: BTreeSet, + /// The whole repertoire's scope (a branch session counts the whole repertoire too). + whole_scope: StatsScope, + /// (learned, learning) when the session began: the summary shows what it changed. + start_progress: (usize, usize), /// The lines of a review, to count «line k of n». lines: Vec>, line: usize, @@ -363,6 +370,7 @@ impl OpeningSessionUi { } else { active_learning_keys(&library, &whole).map_err(|error| error.to_string())? }; + let start_progress = progress_counts(&library, &learning, &whole); let annotation_games: BTreeMap<_, _> = session .stats_scope .repertoire_ids @@ -407,6 +415,8 @@ impl OpeningSessionUi { annotation_games, repertoire_answers, repertoire_keys, + start_progress, + whole_scope: whole, lines, line: 0, next_line_banner: false, @@ -1616,8 +1626,11 @@ impl OpeningSessionUi { Some(at) => layout::when(at.max(now), now), None => tr("nothing scheduled").to_owned(), }; + let (learnt, learning) = progress_counts(&self.library, &self.learning, &self.whole_scope); self.summary = Some(Summary { next_review, + learnt_gain: learnt.saturating_sub(self.start_progress.0), + learning_gain: learning.saturating_sub(self.start_progress.1), unseen, more_new: unseen.min(layout::NEW_PER_SESSION), }); @@ -1902,6 +1915,12 @@ impl OpeningSessionUi { ui.separator(); ui.add_space(4.0); if let Some(summary) = &self.summary { + // Learned takes days: what the session did shows as «learning». + if summary.learnt_gain > 0 { + row(ui, tr("Learned"), format!("+{}", summary.learnt_gain)); + } else if summary.learning_gain > 0 { + row(ui, tr("Learning"), format!("+{}", summary.learning_gain)); + } if self.kind == SessionKind::Daily && summary.unseen > 0 { row(ui, tr("New moves left"), summary.unseen.to_string()); } @@ -2459,3 +2478,14 @@ fn unique_id(prefix: &str) -> String { #[cfg(test)] #[path = "opening_session_tests.rs"] mod tests; + +/// (learned, learning) in a scope, by the core's statuses; zeros if it cannot be counted. +fn progress_counts( + library: &Library, + learning: &LearningData, + scope: &StatsScope, +) -> (usize, usize) { + aggregate_scope(library, learning, scope, &SrsSettings::default()).map_or((0, 0), |scoped| { + (scoped.summary.learnt, scoped.summary.learning) + }) +} diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index e2f1b0a..aaf6b14 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -2211,3 +2211,23 @@ fn a_mistake_on_the_first_move_returns_it_once_and_keeps_the_count() { assert_eq!((summary.unseen, summary.more_new), (0, 0)); assert!(!summary.next_review.is_empty()); } + +#[test] +fn the_summary_shows_learning_growth_when_nothing_is_learned_yet() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 *", + LearningSide::White, + &[], + &["e2e4", "g1f3"], + "summary-learning", + SessionKind::Daily, + ); + for _ in 0..2 { + f.ui.debug_moves("answer"); + f.ui.debug_settle(); + } + assert!(f.ui.is_finished()); + f.ui.compute_summary(); + let summary = f.ui.summary.as_ref().unwrap(); + assert_eq!((summary.learnt_gain, summary.learning_gain), (0, 2)); +} diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 4a7e945..fa58570 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -52,6 +52,9 @@ const BOTTOM_W: f32 = 150.0; const MAIN_W: f32 = 170.0; const LINES_W: f32 = 110.0; const THIRD_W: f32 = 150.0; +/// The «Learned» column: a small bar and «X/Y». +const LEARNED_W: f32 = 104.0; +const MINI_BAR_W: f32 = 44.0; const DIALOG_W: f32 = 460.0; /// A session appears at once when it is ready this fast; otherwise «Preparing…». const PREPARING_SHOWN_AFTER: Duration = Duration::from_millis(300); @@ -1677,7 +1680,7 @@ impl RepertoireUi { .column(egui_extras::Column::remainder().at_least(80.0).clip(true)) .column(egui_extras::Column::exact(22.0)) .column(egui_extras::Column::exact(58.0)) - .column(egui_extras::Column::exact(70.0)) + .column(egui_extras::Column::exact(LEARNED_W)) .column(egui_extras::Column::exact(26.0)); if let Some(index) = scroll_row { table = table.scroll_to_row(index, None); @@ -1713,9 +1716,12 @@ impl RepertoireUi { ui.label(layout::king(side)) .on_hover_text(layout::you_play(side)); }); + let has_moves = self.index.get(id).is_none_or(|row| row.has_moves); row.col(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { match stats { + // An empty repertoire: «no moves» under «Learned» says it. + Some(Ok(_)) if !has_moves => {} Some(Ok(stats)) if stats.today() > 0 => { ui.label(stats.today().to_string()).on_hover_text(trf( "{n} to review, {m} new", @@ -1734,8 +1740,26 @@ impl RepertoireUi { row.col(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { match stats { + Some(Ok(_)) if !has_moves => { + ui.add( + egui::Label::new(RichText::new(tr("no moves")).weak()) + .truncate(), + ) + .on_hover_text(tr("The repertoire has no moves yet: import a PGN or add a line from a game")); + } Some(Ok(stats)) if stats.total > 0 => { - ui.label(format!("{}/{}", stats.learnt, stats.total)); + let hint = learned_hint(stats); + ui.label(format!("{}/{}", stats.learnt, stats.total)) + .on_hover_text(&hint); + let room = ui.available_width() - ui.spacing().item_spacing.x; + if room >= 16.0 { + let (bar, response) = ui.allocate_exact_size( + vec2(room.min(MINI_BAR_W), 6.0), + egui::Sense::hover(), + ); + progress_bar(ui, bar, Some(stats)); + response.on_hover_text(hint); + } } Some(_) => { ui.label(RichText::new("—").weak()); @@ -2449,9 +2473,20 @@ fn main_button(state: &CardState, side: LearningSide) -> (String, bool, Option) { - let width = ui.available_width(); - let (bar, _) = ui.allocate_exact_size(vec2(width, 8.0), egui::Sense::hover()); +/// «Learned 3, learning 10, 75 moves in all» and what «learned» takes. +fn learned_hint(stats: &RowStats) -> String { + trf( + "Learned {x}, learning {z}, {y} moves in all. A move counts as learned after three correct answers in a row without a hint — usually over several days of reviews.", + &[ + ("x", &stats.learnt), + ("z", &stats.learning), + ("y", &stats.total), + ], + ) +} + +/// The two segments: learned, then learning (paler). +fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>) { let painter = ui.painter(); painter.rect_filled(bar, 2.0, ui.visuals().extreme_bg_color); if let Some(stats) = stats.filter(|stats| stats.total > 0) { @@ -2470,6 +2505,12 @@ fn progress(ui: &mut Ui, stats: Option<&RowStats>) { fill.gamma_multiply(0.45), ); } +} + +fn progress(ui: &mut Ui, stats: Option<&RowStats>) { + let width = ui.available_width(); + let (bar, _) = ui.allocate_exact_size(vec2(width, 8.0), egui::Sense::hover()); + progress_bar(ui, bar, stats); ui.add_space(-2.0); ui.horizontal(|ui| { ui.set_height(20.0); @@ -2482,7 +2523,10 @@ fn progress(ui: &mut Ui, stats: Option<&RowStats>) { if learning > 0 { text = format!("{text} · {}", trf("learning {k}", &[("k", &learning)])); } - layout::line(ui, text); + if let Some(stats) = stats { + ui.add(egui::Label::new(text).truncate()) + .on_hover_text(learned_hint(stats)); + } } }); } From 3011bebd80d29f4ef6eb5ea247e1fa857afaf6a8 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:23:31 +0300 Subject: [PATCH 24/31] opening session: the line of moves to the board (block C) is back, by the owner's decision of 2026-11-27 --- apps/desktop/src/opening_session.rs | 21 +++++++++++++++++++++ apps/desktop/src/opening_session_tests.rs | 23 +++++++++++++++++++++++ docs/decisions.md | 4 ++-- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index ff0cfb5..a072ce6 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -1458,6 +1458,17 @@ impl OpeningSessionUi { } } + /// «1. e4 e5 2. Nf3» up to the position on the board; the asked move is not in it. + /// A wrong move on the board is not either: the line stays at the asked position. + fn path_text(&self) -> String { + let node = self.shown_node().or_else(|| { + let (game, asked) = self.expected_node()?; + Some((game, game.parent(asked)?)) + }); + node.map(|(game, node)| layout::path_text(game, node)) + .unwrap_or_default() + } + /// The asked move's node in the PGN. fn expected_node(&self) -> Option<(&Game, NodeId)> { let target = self.session.current_target()?; @@ -1976,6 +1987,7 @@ impl OpeningSessionUi { .shown_node() .map(|(game, node)| layout::opening_text(game, node)) .unwrap_or_default(); + let path = self.path_text(); let (left, right) = match state { State::Summary => { let more = self.more_new_count(); @@ -2015,6 +2027,7 @@ impl OpeningSessionUi { ui, |ui| self.state_card(ui, state), &opening, + &path, |ui| { if *state == State::Summary { self.summary_body(ui); @@ -2238,6 +2251,7 @@ pub fn show_preparing( ) }, "", + "", |_| {}, Some((tr("Hint (H)").to_owned(), false)), None, @@ -2338,6 +2352,7 @@ fn side_panel( ui: &mut Ui, card: impl FnOnce(&mut Ui), opening: &str, + path: &str, body: impl FnOnce(&mut Ui), left: Option<(String, bool)>, right: Option<(String, bool)>, @@ -2360,6 +2375,12 @@ fn side_panel( layout::fixed_block(ui, LINE_H, |ui| { layout::line(ui, RichText::new(opening).weak()); }); + // C: the moves to the position on the board, cut on the left. + layout::fixed_block(ui, LINE_H, |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let shown = layout::cut_left(ui, path, &font, ui.available_width()); + ui.add(egui::Label::new(RichText::new(shown).weak()).truncate()); + }); let rest = (ui.available_height() - ROW_H - GAP).max(0.0); layout::fixed_block(ui, rest, body); layout::fixed_block(ui, ROW_H, |ui| { diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index aaf6b14..f6753eb 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -2231,3 +2231,26 @@ fn the_summary_shows_learning_growth_when_nothing_is_learned_yet() { let summary = f.ui.summary.as_ref().unwrap(); assert_eq!((summary.learnt_gain, summary.learning_gain), (0, 2)); } + +#[test] +fn the_line_shows_the_moves_to_the_board_without_the_asked_or_a_wrong_move() { + let mut f = Fixture::with( + "1. e4 e5 2. Nf3 Nc6 3. Bb5 *", + LearningSide::White, + &["e2e4", "g1f3", "f1b5"], + &[], + "path-line", + SessionKind::Daily, + ); + let at = Instant::now(); + tick_with_prime(&mut f.ui, at, Duration::ZERO, NOW); + assert_eq!(f.ui.path_text(), ""); + answer_current(&mut f, at, NOW, "e4"); + f.ui.debug_settle(); + assert_eq!(f.ui.session.current_expected_uci(), Some("g1f3")); + assert_eq!(f.ui.path_text(), "1. e4 e5"); + assert!(f.ui.play_uci_with_id_at("d2d4", "nf3-wrong".into(), at, NOW)); + assert_eq!(f.ui.path_text(), "1. e4 e5"); + tick_with_prime(&mut f.ui, at + WRONG_SHOWN, Duration::ZERO, NOW); + assert_eq!(f.ui.path_text(), "1. e4 e5"); +} diff --git a/docs/decisions.md b/docs/decisions.md index 4bd8d3f..304e0c2 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -517,9 +517,9 @@ PGN для точного выбора пометок, минимальная г - Ядро сохраняется: LearningItem `(профиль, FEN4, UCI)`, SRS, несколько собственных ответов (2.3.0), формат файлов и типы Settings без изменений. - Занятие = все ходы к повторению + до 10 новых, «Ещё 10 новых». Подача линией от начала; спрашиваются только ходы к повторению и новые; новый ход сначала показывается стрелкой; ошибка показывает правильный ход и возвращается в том же занятии. Только что показанные ходы по расписанию возвращаются через минуту, поэтому следующее занятие в тот же день включает их. -- Прогресс — в ходах: «Выучено X из Y · учится Z». +- Прогресс — в ходах: «Выучено X из Y · учится Z». «Выучено» по ядру — три верных самостоятельных ответа подряд, обычно за несколько дней; поэтому таблица показывает и «учится» (двухсегментная полоса, подсказка), а итог занятия — «Учится: +N» (2026-11-27). - Из UI удалены выбор режима и порядка, шесть параметров контекста, дашборд с вкладками и графиками, отчёт Branches/Lines, режим «за оба цвета». Сохранённые значения остаются на диске, но не действуют; лимит `max_plies` снимается при загрузке; незавершённые сессии 2.x не возобновляются. Это заменяет UI-части решений 2026-11-04/05. -- Вторичные действия: «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты». Редактирования ходов на доске в этом этапе нет. Строка ходов линии в занятии не показывается (решение владельца 03.11). +- Вторичные действия: «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты». Редактирования ходов на доске в этом этапе нет. Строка ходов линии в занятии показывается по решению владельца 2026-11-27 (заменяет решение 03.11): одна бледная строка SAN с номерами до позиции на доске, без спрашиваемого хода и без отметок ошибок, обрезка слева, постоянная высота; место — между строкой дебюта и комментарием (блок C спецификации). - Цвет задаётся при импорте/создании. При первом открытии раздела (файла библиотеки ещё нет) создаются два примера: Испанская партия (белые) и Найдорф (чёрные); удалённые примеры не возвращаются. - Неверный ход на только что показанном новом ходе ошибкой не считается: «Не тот ход» ~0,4 с, затем снова показ. From adf89181d5cf652bd9db0d6c7be99cc322548179 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:24:52 +0300 Subject: [PATCH 25/31] =?UTF-8?q?docs:=20task=2040=20=E2=80=94=20owner's?= =?UTF-8?q?=202026-11-27=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/dev/tasks.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index 0d7f72f..e5e87d5 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -286,7 +286,8 @@ - **Сделано:** один экран «Репертуары» (таблица + карточка: «Сегодня: N повторить · M новых», «Выучено X из Y · учится Z», «Тренироваться», «Варианты…», «Повторить всё»); занятие — линия от начала, новый ход показывается стрелкой, на ошибке — правильный ход, ошибка возвращается в том же занятии, комментарии и название дебюта; итог; «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты»; цвет при импорте; два стартовых репертуара (Испанская за белых, Найдорф за чёрных). Удалены режимы/порядки, окно параметров, дашборд с графиками, Branches/Lines, режим «за оба цвета», скрытый лимит глубины; ~13 тыс. строк старого UI. - **Проверено:** fmt, clippy `-D warnings`; trainer 200 passed, desktop 161 passed / 3 ignored (перепроверено оркестратором); mobile-api check. Дизайн-ревью `docs/qa/opening-trainer-v2-design-review.md`: скачков нет (0 px в серии состояний), шапка и доска совпадают с экраном партии после исправлений. - **Не проверено:** wasm (на ноутбуке нет цели `wasm32-unknown-unknown`), английский интерфейс, клавиатура, масштаб 1, длинные имена/большой список, 960×600 для экранов занятия; клавиатурное подтверждение удаления, клики мышью, X11. Независимый tester: 4/4 PASS, `docs/qa/opening-trainer-v2-functional.md`; данные 2.2/2.3 читаются без изменений — `docs/qa/opening-trainer-v2-migration.md`. -- **Осталось:** перенести незакоммиченные временные стрелки из основной папки; удалить мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) отдельной задачей. +- **2026-11-27 (владелец):** не сливать пока; временные стрелки перенесены (`8ca7f43`); колонка «Выучено» с полосой выучено/учится и подсказкой о критерии, «нет ходов» для пустого, «Учится +N» в итоге (`7cb0291`); строка ходов линии в занятии возвращена (`3011beb`). Цвет старых репертуаров владелец меняет вручную. +- **Осталось:** на выделенной строке таблицы сегмент «учится» плохо виден; подсказки при наведении на снимках не проверены; удалить мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) отдельной задачей. ## Сделано From 87e8a6d794ac294b8898a3d19021157020e77586 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:42:18 +0300 Subject: [PATCH 26/31] opening trainer: the mini-bar on a selected row takes the selection's text colour; a grey track in the light theme --- apps/desktop/src/repertoire_ui.rs | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index fa58570..c4f6ae8 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -1708,7 +1708,8 @@ impl RepertoireUi { }; let side = layout::side_of(settings, id); let stats = self.stats.get(id); - row.set_selected(self.selected.as_ref() == Some(id)); + let selected = self.selected.as_ref() == Some(id); + row.set_selected(selected); row.col(|ui| { layout::line(ui, repertoire.name.as_str()); }); @@ -1757,7 +1758,7 @@ impl RepertoireUi { vec2(room.min(MINI_BAR_W), 6.0), egui::Sense::hover(), ); - progress_bar(ui, bar, Some(stats)); + progress_bar(ui, bar, Some(stats), selected); response.on_hover_text(hint); } } @@ -2486,14 +2487,26 @@ fn learned_hint(stats: &RowStats) -> String { } /// The two segments: learned, then learning (paler). -fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>) { +/// On a selected table row the selection colour is the row's own: the segments take +/// the colour of the text on the selection instead. +fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>, selected: bool) { let painter = ui.painter(); - painter.rect_filled(bar, 2.0, ui.visuals().extreme_bg_color); + // In the light theme the extreme colour is the rows' white: the track is a button's grey. + let track = if ui.visuals().dark_mode { + ui.visuals().extreme_bg_color + } else { + ui.visuals().widgets.inactive.bg_fill + }; + painter.rect_filled(bar, 2.0, track); if let Some(stats) = stats.filter(|stats| stats.total > 0) { let total = stats.total as f32; let learnt = bar.width() * stats.learnt as f32 / total; let learning = bar.width() * stats.learning as f32 / total; - let fill = ui.visuals().selection.bg_fill; + let fill = if selected { + ui.visuals().selection.stroke.color + } else { + ui.visuals().selection.bg_fill + }; painter.rect_filled( egui::Rect::from_min_size(bar.min, vec2(learnt, bar.height())), 2.0, @@ -2510,7 +2523,7 @@ fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>) { fn progress(ui: &mut Ui, stats: Option<&RowStats>) { let width = ui.available_width(); let (bar, _) = ui.allocate_exact_size(vec2(width, 8.0), egui::Sense::hover()); - progress_bar(ui, bar, stats); + progress_bar(ui, bar, stats, false); ui.add_space(-2.0); ui.horizontal(|ui| { ui.set_height(20.0); From 07c6d0cda3b24c242f817ccfccb7b391d5d56ec6 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:49:13 +0300 Subject: [PATCH 27/31] trainer: drop the dead v2 tree session (session.rs), its queues and paths in stats.rs/tree.rs/scope.rs and their tests; v2/legacy formats, StatsStore and the store/migration tests stay --- .../trainer/src/repertoire/advanced_tests.rs | 1527 ----------------- crates/trainer/src/repertoire/mod.rs | 12 +- crates/trainer/src/repertoire/scope.rs | 27 - crates/trainer/src/repertoire/session.rs | 1162 ------------- crates/trainer/src/repertoire/stats.rs | 803 +-------- crates/trainer/src/repertoire/tests.rs | 548 +----- crates/trainer/src/repertoire/tree.rs | 174 +- 7 files changed, 24 insertions(+), 4229 deletions(-) delete mode 100644 crates/trainer/src/repertoire/session.rs diff --git a/crates/trainer/src/repertoire/advanced_tests.rs b/crates/trainer/src/repertoire/advanced_tests.rs index 83c58ab..cdc0c40 100644 --- a/crates/trainer/src/repertoire/advanced_tests.rs +++ b/crates/trainer/src/repertoire/advanced_tests.rs @@ -1,4 +1,3 @@ -use chess_core::shakmaty::{Color, Position}; use chess_core::{Game, NodeId}; use super::*; @@ -11,721 +10,6 @@ fn repertoire(pgn: &str) -> Repertoire { library.repertoire(&id).unwrap().clone() } -fn repertoire_from_lines(lines: &[&str]) -> Repertoire { - let mut game = Game::new(); - for line in lines { - game.add_uci_line(NodeId::ROOT, &[*line]).unwrap(); - } - let mut library = Library::default(); - let id = library.create("Many", &game).unwrap(); - library.repertoire(&id).unwrap().clone() -} - -fn strings(moves: &[&str]) -> Vec { - moves.iter().map(|mv| (*mv).to_owned()).collect() -} - -fn random_session(rep: &Repertoire, mode: TrainingMode, seed: u64) -> TrainingSession { - TrainingSession::scoped_random_with_seed( - rep, - TrainingScope::whole(), - mode, - StatsData::default(), - 0, - seed, - ) - .unwrap() -} - -fn random_route(session: &TrainingSession) -> Vec { - let mut route = session.scope().parent_prefix().to_vec(); - route.extend(session.suggested_path().unwrap().iter().cloned()); - route -} - -fn path_key(rep: &Repertoire, scope: &TrainingScope, path: &[String]) -> PathKey { - PathKey { - repertoire_id: rep.id.clone(), - scope: scope.key(), - path: path.to_vec(), - } -} - -#[test] -fn scope_starts_at_black_move_with_context_and_stops_at_early_boundary() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 (2... Nf6) 3. Bb5 a6 4. Ba4 Nf6 *"); - let prefix = strings(&["e2e4", "e7e5", "g1f3", "b8c6"]); - let end = strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6"]); - let scope = TrainingScope::between(prefix, end); - let mut session = TrainingSession::scoped( - &rep, - scope.clone(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - - assert_eq!(session.position().turn(), Color::Black); - assert_eq!( - session - .path() - .iter() - .map(|mv| mv.uci.as_str()) - .collect::>(), - ["e2e4", "e7e5", "g1f3"] - ); - assert!(session.path().iter().all(|mv| mv.automatic)); - assert!(session.attempts().is_empty()); - assert_eq!( - session - .candidates() - .iter() - .map(|c| c.uci.as_str()) - .collect::>(), - ["b8c6"] - ); - - assert_eq!(session.play_uci("g8f6", 1).unwrap(), TrainingVerdict::Wrong); - assert_eq!(session.play_uci("b8c6", 2).unwrap(), TrainingVerdict::Right); - assert_eq!(session.play_uci("f1b5", 3).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("a7a6", 4).unwrap(), - TrainingVerdict::Finished - ); - assert!(session.is_done()); - let actual = strings(&["b8c6", "f1b5", "a7a6"]); - let stats = session - .stats() - .path_stats(&path_key(&rep, &scope, &actual)) - .unwrap(); - assert_eq!(stats.completions, 1); - assert_eq!(stats.mistakes, 1); - assert_eq!(stats.recent[0].path, actual); - assert_eq!(stats.recent[0].scope, scope.key()); - assert_eq!(stats.recent[0].automatic_moves, 3); - - let mut without_context = TrainingSession::scoped( - &rep, - scope.with_context(false), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert!(without_context.path().is_empty()); - assert_eq!(without_context.position().turn(), Color::Black); - assert_eq!( - without_context.play_uci("b8c6", 10).unwrap(), - TrainingVerdict::Right - ); -} - -#[test] -fn scope_honours_disabled_depth_and_selected_move_as_its_only_early_end() { - let mut rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 (3. Bc4) a6 4. Ba4 *"); - rep.set_prefix_disabled(&strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]), true) - .unwrap(); - let scope = TrainingScope::from_prefix(strings(&["e2e4", "e7e5", "g1f3", "b8c6"])); - let mut session = TrainingSession::scoped( - &rep, - scope.clone(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - session.play_uci("b8c6", 1).unwrap(); - assert_eq!(session.play_uci("f1b5", 2).unwrap(), TrainingVerdict::Wrong); - assert_eq!( - session.play_uci("f1c4", 3).unwrap(), - TrainingVerdict::Finished - ); - - rep.set_max_plies(4); - let mut depth = TrainingSession::scoped( - &rep, - scope.clone(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert_eq!( - depth.play_uci("b8c6", 10).unwrap(), - TrainingVerdict::Finished - ); - - let only = TrainingScope::between(scope.prefix.clone(), scope.prefix.clone()); - let mut one_move = TrainingSession::scoped( - &rep, - only, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 20, - ) - .unwrap(); - assert_eq!( - one_move.play_uci("b8c6", 20).unwrap(), - TrainingVerdict::Finished - ); -} - -#[test] -fn scoped_one_side_black_targets_use_context_but_never_count_it() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - let scope = TrainingScope::from_prefix(strings(&["e2e4", "e7e5", "g1f3", "b8c6"])); - let mut session = TrainingSession::scoped( - &rep, - scope, - TrainingMode::Black, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.target().unwrap().expected_uci, "b8c6"); - assert_eq!(session.path().len(), 3); - assert!(session.path().iter().all(|mv| mv.automatic)); - assert!(session.attempts().is_empty()); - assert_eq!(session.play_uci("b8c6", 1).unwrap(), TrainingVerdict::Right); - assert!( - session - .path() - .iter() - .any(|mv| mv.uci == "f1b5" && mv.automatic) - ); - assert_eq!(session.attempts().len(), 1); - assert_eq!( - session.play_uci("a7a6", 2).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.attempts().len(), 2); - assert!(session.path().iter().filter(|mv| mv.automatic).count() >= 2); - - let mut no_context = TrainingSession::scoped( - &rep, - TrainingScope::from_prefix(strings(&["e2e4", "e7e5", "g1f3", "b8c6"])).with_context(false), - TrainingMode::Black, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert!(no_context.path().is_empty()); - assert_eq!(no_context.target().unwrap().expected_uci, "b8c6"); - assert_eq!( - no_context.play_uci("b8c6", 10).unwrap(), - TrainingVerdict::Right - ); - assert_eq!(no_context.attempts().len(), 1); -} - -#[test] -fn scoped_transpositions_do_not_import_continuations_from_outside_scope() { - let mut library = Library::default(); - let id = library.create_empty("Transpositions").unwrap(); - library - .add_game( - &id, - &chess_core::parse_str("1. d4 d5 2. Nf3 Nf6 3. g3 *").game, - ) - .unwrap(); - library - .add_game(&id, &chess_core::parse_str("1. Nf3 d5 2. d4 Nf6 *").game) - .unwrap(); - let rep = library.repertoire(&id).unwrap().clone(); - let scope = TrainingScope::from_prefix(strings(&["g1f3"])); - let mut session = TrainingSession::scoped( - &rep, - scope, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.play_uci("g1f3", 1).unwrap(), TrainingVerdict::Right); - assert_eq!(session.play_uci("d7d5", 2).unwrap(), TrainingVerdict::Right); - assert_eq!(session.play_uci("d2d4", 3).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("g8f6", 4).unwrap(), - TrainingVerdict::Finished - ); - assert!(session.candidates().is_empty()); - - let mut whole = TrainingSession::scoped( - &rep, - TrainingScope::whole(), - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - for (now, mv) in ["g1f3", "d7d5", "d2d4", "g8f6", "g2g3"] - .into_iter() - .enumerate() - { - whole.play_uci(mv, 10 + now as i64).unwrap(); - } - assert!(whole.is_done()); -} - -#[test] -fn both_review_queue_advances_proposals_but_repeat_keeps_the_same_route() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *"); - let main = strings(&["e2e4", "e7e5", "g1f3"]); - let second = strings(&["e2e4", "e7e5", "c2c4"]); - let deviation = strings(&["e2e4", "c7c5"]); - let scope = TrainingScope::whole(); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.suggested_path().unwrap(), main); - session.play_uci("e2e4", 1).unwrap(); - assert_eq!( - session.play_uci("c7c5", 2).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!( - session - .stats() - .path_stats(&path_key(&rep, &scope, &deviation)) - .unwrap() - .completions, - 1 - ); - assert!( - session - .stats() - .path_stats(&path_key(&rep, &scope, &main)) - .is_none() - ); - - session.next_path(3).unwrap(); - assert_eq!(session.suggested_path().unwrap(), second); - session.restart(4).unwrap(); - assert_eq!(session.suggested_path().unwrap(), second); -} - -#[test] -fn path_history_records_hints_mistakes_and_last_seen() { - let rep = repertoire("1. e4 e5 *"); - let scope = TrainingScope::whole(); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for now in 1..=3 { - session.play_uci("d2d4", now).unwrap(); - } - session.hint(4).unwrap(); - session.play_uci("e2e4", 5).unwrap(); - session.play_uci("e7e5", 6).unwrap(); - let path = strings(&["e2e4", "e7e5"]); - let stats = session - .stats() - .path_stats(&path_key(&rep, &scope, &path)) - .unwrap(); - assert_eq!(stats.completions, 1); - assert_eq!(stats.mistakes, 3); - assert_eq!(stats.hints, 1); - assert_eq!(stats.last_seen, Some(6)); - assert!(stats.recent[0].hinted); -} - -#[test] -fn both_least_recent_uses_completions_then_oldest_actual_path() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *"); - let paths = [ - strings(&["e2e4", "e7e5", "g1f3"]), - strings(&["e2e4", "e7e5", "c2c4"]), - strings(&["e2e4", "c7c5"]), - ]; - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::LeastRecent, - StatsData::default(), - 0, - ) - .unwrap(); - for (index, expected) in paths.iter().enumerate() { - assert_eq!(session.suggested_path().unwrap(), expected); - for (ply, mv) in expected.iter().enumerate() { - session.play_uci(mv, (index * 10 + ply) as i64).unwrap(); - } - assert!(session.is_done()); - session.next_path((index * 10 + 8) as i64).unwrap(); - } - assert_eq!(session.suggested_path().unwrap(), paths[0]); -} - -#[test] -fn repeated_position_is_a_terminal_path_not_a_hang() { - let rep = repertoire("1. Nf3 Nf6 2. Ng1 Ng8 3. Nf3 Nf6 4. Ng1 Ng8 *"); - let scope = TrainingScope::whole(); - let paths = RepertoireTree::new(&rep).training_paths(&scope).unwrap(); - assert_eq!(paths.len(), 1); - assert_eq!(paths[0].moves, strings(&["g1f3", "g8f6", "f3g1", "f6g8"])); - - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (now, mv) in ["g1f3", "g8f6", "f3g1", "f6g8"].into_iter().enumerate() { - session.play_uci(mv, now as i64).unwrap(); - } - assert!(session.is_done()); - let stats = session - .stats() - .path_stats(&path_key(&rep, &scope, &paths[0].moves)) - .unwrap(); - assert_eq!(stats.completions, 1); -} - -#[test] -fn introduction_is_explicit_batches_of_ten_then_unscheduled() { - let rep = repertoire_from_lines(&[ - "e2e4", "d2d4", "c2c4", "g1f3", "g2g3", "b2b3", "b1c3", "e2e3", "d2d3", "c2c3", "f2f4", - "a2a3", - ]); - let mut first = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - let mut played = 0; - while !first.is_done() { - let target = first.target().unwrap().expected_uci.clone(); - first.play_uci(&target, played as i64).unwrap(); - played += 1; - } - assert_eq!(played, INTRODUCTION_BATCH_SIZE); - assert_eq!(first.stats().move_stats.len(), INTRODUCTION_BATCH_SIZE); - - first.restart_with_policy(20, SrsPolicy::Introduce).unwrap(); - let mut remaining = 0; - while !first.is_done() { - let target = first.target().unwrap().expected_uci.clone(); - first.play_uci(&target, 20 + remaining).unwrap(); - remaining += 1; - } - assert_eq!(remaining, 2); - assert_eq!(first.stats().move_stats.len(), 12); - - first.restart_with_policy(30, SrsPolicy::Introduce).unwrap(); - assert!(first.is_done()); -} - -#[test] -fn introduction_takes_unseen_before_previously_reviewed_unscheduled() { - let rep = repertoire_from_lines(&["e2e4", "d2d4"]); - let mut review = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - review.play_uci("e2e4", 10).unwrap(); - assert!(review.stats().move_stats[0].due.is_none()); - - let mut introduction = TrainingSession::new_srs( - &rep, - TrainingMode::White, - review.into_stats(), - 20, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!(introduction.target().unwrap().expected_uci, "d2d4"); - introduction.play_uci("d2d4", 21).unwrap(); - assert_eq!(introduction.target().unwrap().expected_uci, "e2e4"); - introduction.play_uci("e2e4", 22).unwrap(); - assert!(introduction.is_done()); - assert!( - introduction - .stats() - .move_stats - .iter() - .all(|stats| stats.due.is_some()) - ); -} - -#[test] -fn due_policy_does_not_fall_through_to_unseen_and_early_review_preserves_due() { - let rep = repertoire_from_lines(&["e2e4", "d2d4"]); - let mut initial = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - initial.play_uci("e2e4", 100).unwrap(); - initial.restart_with_policy(200, SrsPolicy::Due).unwrap(); - assert!(initial.is_done()); - assert_eq!(initial.stats().move_stats.len(), 1); - - initial - .restart_with_policy(200, SrsPolicy::Introduce) - .unwrap(); - assert_eq!(initial.target().unwrap().expected_uci, "d2d4"); - initial.play_uci("d2d4", 201).unwrap(); - let original_due: Vec> = initial - .stats() - .move_stats - .iter() - .map(|stats| stats.due) - .collect(); - - initial - .restart_with_policy(300, SrsPolicy::EarlyReview) - .unwrap(); - assert_eq!(initial.srs_policy(), SrsPolicy::EarlyReview); - let target = initial.target().unwrap().expected_uci.clone(); - let key = MoveKey { - repertoire_id: rep.id.clone(), - mode: TrainingMode::White, - position_fen4: initial.target().unwrap().position_fen4.clone(), - expected_uci: target.clone(), - }; - let before_attempts = initial.stats().get(&key).unwrap().attempts; - assert_eq!( - initial.play_uci("h2h3", 301).unwrap(), - TrainingVerdict::Wrong - ); - initial.play_uci(&target, 302).unwrap(); - let stats = initial.stats().get(&key).unwrap(); - assert_eq!(stats.attempts, before_attempts + 2); - assert_eq!(stats.last_seen, Some(302)); - let after_due: Vec> = initial - .stats() - .move_stats - .iter() - .map(|stats| stats.due) - .collect(); - assert_eq!(after_due, original_due); -} - -#[test] -fn path_history_and_scope_cursor_survive_stats_store_roundtrip() { - let dir = std::env::temp_dir().join(format!("cp-path-store-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let store = StatsStore::new(dir.join("stats.json")); - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - store.load().unwrap(), - 0, - ) - .unwrap(); - let completed = session.suggested_path().unwrap().to_vec(); - for (now, mv) in completed.clone().into_iter().enumerate() { - session.play_uci(&mv, now as i64).unwrap(); - } - store.save(session.stats_mut()).unwrap(); - - let loaded = store.load().unwrap(); - assert_eq!( - loaded - .path_stats(&path_key(&rep, &TrainingScope::whole(), &completed)) - .unwrap() - .completions, - 1 - ); - let next = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - loaded, - 10, - ) - .unwrap(); - assert_ne!(next.suggested_path().unwrap(), completed); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn default_srs_never_introduces_new_targets_or_records_empty_completion() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::SpacedRepetition, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.is_done()); - assert_eq!(session.srs_policy(), SrsPolicy::Due); - assert!(session.stats().runs.is_empty()); - session.restart(1).unwrap(); - assert!(session.is_done()); - assert!(session.stats().move_stats.is_empty()); -} - -#[test] -fn repeated_hint_requests_do_not_inflate_hint_statistics() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for now in 1..=3 { - session.play_uci("d2d4", now).unwrap(); - } - assert!(session.hint(4).is_some()); - assert!(session.hint(5).is_some()); - session.play_uci("e2e4", 6).unwrap(); - let stats = &session.stats().move_stats[0]; - assert!(stats.key.expected_uci.is_empty()); - assert_eq!((stats.attempts, stats.hints, stats.wrong), (4, 1, 3)); - assert!(session.attempts().iter().all(|a| a.expected_uci.is_empty())); -} - -#[test] -fn transposition_continuation_preserves_actual_depth_and_position_counters() { - let mut library = Library::default(); - let id = library.create_empty("Depth").unwrap(); - for line in [ - "1. d4 d5 2. Nf3 Nf6 3. g3 g6 4. Bg2 *", - "1. Nh3 Nh6 2. Ng5 Ng4 3. Nf3 Nf6 4. d4 d5 *", - ] { - library - .add_game(&id, &chess_core::parse_str(line).game) - .unwrap(); - } - let rep = library.repertoire_mut(&id).unwrap(); - rep.set_max_plies(9); - let paths = RepertoireTree::new(rep) - .training_paths(&TrainingScope::whole()) - .unwrap(); - assert!(paths.iter().all(|path| path.moves.len() <= 9)); - let mut session = TrainingSession::new( - rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (i, mv) in [ - "g1h3", "g8h6", "h3g5", "h6g4", "g5f3", "g4f6", "d2d4", "d7d5", - ] - .iter() - .enumerate() - { - assert_eq!( - session.play_uci(mv, i as i64).unwrap(), - TrainingVerdict::Right - ); - } - assert_eq!( - session.play_uci("g2g3", 9).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.position().fullmoves().get(), 5); - assert_eq!(session.path().len(), 9); - assert!(session.candidates().is_empty()); -} - -#[test] -fn scoped_target_context_cannot_be_borrowed_from_an_outside_transposition() { - let mut library = Library::default(); - let id = library.create_empty("Scope").unwrap(); - for pgn in ["1. d4 d5 2. Nf3 Nf6 *", "1. Nf3 d5 2. d4 Nf6 3. g3 *"] { - library - .add_game(&id, &chess_core::parse_str(pgn).game) - .unwrap(); - } - let rep = library.repertoire(&id).unwrap(); - let scope = TrainingScope::from_prefix(strings(&["g1f3"])); - let targets = RepertoireTree::new(rep).scoped_targets(Color::White, &scope); - assert!( - targets - .iter() - .all(|t| t.path.is_empty() || t.path[0] == "g1f3") - ); -} - -#[test] -fn early_review_preserves_the_next_scheduled_interval() { - let rep = repertoire("1. e4 *"); - let mut stats = StatsData::default(); - let mut due = 0; - for interval in [INITIAL_INTERVAL_SECONDS, 2 * INITIAL_INTERVAL_SECONDS] { - let policy = if due == 0 { - SrsPolicy::Introduce - } else { - SrsPolicy::Due - }; - let mut session = - TrainingSession::new_srs(&rep, TrainingMode::White, stats, due, policy).unwrap(); - session.play_uci("e2e4", due).unwrap(); - due += interval; - stats = session.into_stats(); - } - let mut review = TrainingSession::new_srs( - &rep, - TrainingMode::White, - stats, - due - 100, - SrsPolicy::EarlyReview, - ) - .unwrap(); - review.play_uci("e2e4", due - 100).unwrap(); - assert_eq!( - review.stats().move_stats[0].interval_seconds, - Some(2 * INITIAL_INTERVAL_SECONDS) - ); - let mut next = TrainingSession::new_srs( - &rep, - TrainingMode::White, - review.into_stats(), - due, - SrsPolicy::Due, - ) - .unwrap(); - next.play_uci("e2e4", due).unwrap(); - assert_eq!( - next.stats().move_stats[0].due, - Some(due + 4 * INITIAL_INTERVAL_SECONDS) - ); -} - #[test] fn simultaneous_writers_cannot_overwrite_the_same_revision() { let path = std::env::temp_dir().join(format!("cp-trainer-race-{}.json", std::process::id())); @@ -798,207 +82,6 @@ fn previous_both_move_keys_migrate_to_position_statistics_without_data_loss() { std::fs::remove_file(path).unwrap(); } -#[test] -fn removing_repertoire_cleans_all_modern_statistics_and_cursors_but_keeps_others() { - let first = repertoire("1. e4 (1. d4) *"); - let second = repertoire("1. Nf3 (1. c4) *"); - let mut data = StatsData::default(); - data.legacy_lines - .insert("original".into(), serde_json::json!({"runs": 3})); - for rep in [&first, &second] { - for mode in [TrainingMode::White, TrainingMode::Both] { - let mut session = - TrainingSession::new(rep, mode, QueueMode::ReviewInOrder, data, 0).unwrap(); - while !session.is_done() { - let mv = session - .target() - .map(|t| t.expected_uci.clone()) - .unwrap_or_else(|| session.candidates()[0].uci.clone()); - session.play_uci(&mv, 1).unwrap(); - } - data = session.into_stats(); - } - } - let before = serde_json::to_value(&data).unwrap(); - for field in [ - "move_stats", - "runs", - "path_stats", - "review_cursors", - "path_review_cursors", - ] { - assert!( - before[field].as_array().unwrap().iter().any(|entry| { - entry - .get("repertoire_id") - .or_else(|| entry.get("key").and_then(|key| key.get("repertoire_id"))) - == Some(&serde_json::json!(first.id)) - }), - "missing fixture for {field}" - ); - } - data.remove_repertoire(&first.id); - let after = serde_json::to_value(&data).unwrap(); - for field in [ - "move_stats", - "runs", - "path_stats", - "review_cursors", - "path_review_cursors", - ] { - let expected: Vec<_> = before[field] - .as_array() - .unwrap() - .iter() - .filter(|entry| { - entry - .get("repertoire_id") - .or_else(|| entry.get("key").and_then(|key| key.get("repertoire_id"))) - == Some(&serde_json::json!(second.id)) - }) - .cloned() - .collect(); - assert_eq!( - after[field], - serde_json::json!(expected), - "incorrect cleanup of {field}" - ); - } - assert_eq!(after["legacy_lines"], before["legacy_lines"]); - data.remove_repertoire(&first.id); - assert_eq!(serde_json::to_value(&data).unwrap(), after); -} - -#[test] -fn resetting_one_mode_preserves_other_modes_and_repertoires() { - let first = repertoire("1. e4 (1. d4) *"); - let second = repertoire("1. Nf3 (1. c4) *"); - let mut data = StatsData::default(); - data.legacy_lines - .insert("original".into(), serde_json::json!({"runs": 3})); - for (rep, mode) in [ - (&first, TrainingMode::White), - (&first, TrainingMode::Both), - (&second, TrainingMode::White), - ] { - let mut session = TrainingSession::new_random(rep, mode, data, 0).unwrap(); - while !session.is_done() { - let mv = session.candidates()[0].uci.clone(); - session.play_uci(&mv, 1).unwrap(); - } - data = session.into_stats(); - } - - data.remove_repertoire_mode(&first.id, TrainingMode::White); - - assert!(data.runs(&first.id, TrainingMode::White).is_none()); - assert!(data.runs(&first.id, TrainingMode::Both).is_some()); - assert!(data.runs(&second.id, TrainingMode::White).is_some()); - assert!( - data.move_stats - .iter() - .all(|entry| entry.key.repertoire_id != first.id - || entry.key.mode != TrainingMode::White) - ); - assert!( - data.move_stats.iter().any( - |entry| entry.key.repertoire_id == first.id && entry.key.mode == TrainingMode::Both - ) - ); - assert!( - data.path_stats - .iter() - .any(|entry| entry.key.repertoire_id == first.id) - ); - let after = serde_json::to_value(&data).unwrap(); - let cursors = after["random_practice_cursors"].as_array().unwrap(); - assert!(cursors.iter().all( - |entry| entry["repertoire_id"] != serde_json::json!(first.id) - || entry["mode"] != serde_json::json!("White") - )); - assert!(cursors.iter().any( - |entry| entry["repertoire_id"] == serde_json::json!(first.id) - && entry["mode"] == serde_json::json!("Both") - )); - assert_eq!( - after["legacy_lines"], - serde_json::json!({"original": {"runs": 3}}) - ); -} - -#[test] -fn streaming_paths_stop_early_and_match_full_queue_across_wraps_and_history() { - use std::ops::ControlFlow; - let rep = repertoire( - "1. d4 d5 2. Nf3 Nf6 (2... Nc6) (1... Nf6 2. Nf3 d5 3. c4) (1. Nf3 d5 2. d4 Nf6 3. c4) *", - ); - let tree = RepertoireTree::new(&rep); - let scopes = [ - TrainingScope::whole(), - TrainingScope::from_prefix(strings(&["d2d4"])), - ]; - for scope in scopes { - let paths = tree.training_paths(&scope).unwrap(); - assert!(!paths.is_empty()); - assert_eq!(tree.training_path_count(&scope).unwrap(), paths.len()); - let mut visited = 0; - tree.visit_training_paths(&scope, |moves| { - visited += 1; - assert_eq!(moves, paths[0].moves); - ControlFlow::Break(()) - }) - .unwrap(); - assert_eq!(visited, 1); - let mut stats = StatsData::default(); - for step in 0..paths.len() * 3 { - for mode in [ - QueueMode::ReviewInOrder, - QueueMode::LeastRecent, - QueueMode::SpacedRepetition, - ] { - let full = stats.path_queue(&tree, &rep.id, &scope, mode).unwrap(); - assert_eq!( - stats - .next_training_path(&tree, &rep.id, &scope, mode) - .unwrap(), - full.first().cloned() - ); - } - let path = &paths[step % paths.len()]; - stats.record_path_run( - path_key(&rep, &scope, &path.moves), - RunRecord { - at: step as i64, - mistakes: 0, - hints: 0, - hinted: false, - path: path.moves.clone(), - user_attempts: path.moves.len() as u32, - automatic_moves: 0, - scope: scope.key(), - }, - ); - stats.path_presented(&rep.id, &scope, QueueMode::ReviewInOrder); - } - } - let empty = RepertoireTree::new(&repertoire("*")); - assert_eq!( - empty.training_path_count(&TrainingScope::whole()).unwrap(), - 0 - ); - assert_eq!( - StatsData::default() - .next_training_path( - &empty, - &rep.id, - &TrainingScope::whole(), - QueueMode::ReviewInOrder - ) - .unwrap(), - None - ); -} - #[test] fn null_subtree_grafts_under_the_exact_path_instead_of_an_earlier_transposition() { let base = chess_core::parse_str("1. d4 (1. Nf3 d5 2. d4) d5 2. Nf3 *").game; @@ -1057,613 +140,3 @@ fn null_subtree_grafts_under_the_exact_path_instead_of_an_earlier_transposition( canonical ); } - -#[test] -fn practice_follows_the_users_branch_without_hidden_targets_or_automatic_attempts() { - let rep = repertoire("1. e4 (1. d4 d5 2. c4) e5 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.target().is_none()); - assert!(session.may_hint()); - assert_eq!(session.play_uci("d2d4", 1).unwrap(), TrainingVerdict::Right); - assert_eq!( - session - .path() - .iter() - .map(|m| m.uci.as_str()) - .collect::>(), - vec!["d2d4", "d7d5"] - ); - assert_eq!(session.attempts().len(), 1); - assert_eq!( - session.play_uci("c2c4", 2).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.play_uci("a2a3", 3).unwrap(), TrainingVerdict::Done); - let stats = session.stats(); - assert_eq!(stats.move_stats.len(), 2); - assert!( - stats - .move_stats - .iter() - .all(|m| m.correct == 1 && m.due.is_none()) - ); - assert_eq!( - stats - .runs(&rep.id, TrainingMode::White) - .unwrap() - .completions, - 1 - ); -} - -#[test] -fn practice_black_starts_with_an_automatic_white_move_and_rotates_opponent_branches() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.play_uci("e2e4", 1).unwrap(), TrainingVerdict::Right); - assert_eq!(session.path()[1].uci, "e7e5"); - session.next_path(2).unwrap(); - assert_eq!( - session.play_uci("e2e4", 3).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.path()[1].uci, "c7c5"); - session.restart(4).unwrap(); - session.play_uci("e2e4", 5).unwrap(); - assert_eq!(session.path()[1].uci, "c7c5"); - let saved = serde_json::to_vec(session.stats()).unwrap(); - let stats: StatsData = serde_json::from_slice(&saved).unwrap(); - let mut black = - TrainingSession::new(&rep, TrainingMode::Black, QueueMode::Practice, stats, 6).unwrap(); - assert_eq!(black.path()[0].uci, "e2e4"); - assert!(black.path()[0].automatic); - assert!(black.attempts().is_empty()); - assert_eq!( - black.play_uci("c7c5", 7).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(black.attempts().len(), 1); -} - -#[test] -fn practice_wrong_move_stays_put_and_hint_is_available_before_any_error() { - let rep = repertoire("1. e4 e5 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.hint(1).is_some()); - let position = session.position_key(); - assert_eq!(session.play_uci("d2d4", 2).unwrap(), TrainingVerdict::Wrong); - assert_eq!(session.position_key(), position); - assert_eq!(session.total_mistakes(), 1); - assert_eq!( - session.play_uci("e2e4", 3).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.stats().move_stats[0].hints, 1); - assert_eq!(session.stats().move_stats[0].wrong, 1); - assert_eq!(session.stats().move_stats[0].correct, 1); - assert!(session.stats().move_stats[0].due.is_none()); -} - -#[test] -fn practice_obeys_depth_disabled_repetition_and_both_never_answers_automatically() { - let mut rep = repertoire("1. Nf3 (1. d4 d5) Nf6 2. Ng1 Ng8 3. e4 *"); - rep.set_prefix_disabled(&strings(&["d2d4"]), true).unwrap(); - let mut both = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(both.play_uci("d2d4", 1).unwrap(), TrainingVerdict::Wrong); - for uci in ["g1f3", "g8f6", "f3g1"] { - assert_eq!(both.play_uci(uci, 2).unwrap(), TrainingVerdict::Right); - } - assert_eq!(both.play_uci("f6g8", 3).unwrap(), TrainingVerdict::Finished); - assert!(both.path().iter().all(|m| !m.automatic)); - assert_eq!(both.path().len(), 4); - rep.max_plies = 1; - let mut white = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - StatsData::default(), - 4, - ) - .unwrap(); - assert_eq!( - white.play_uci("g1f3", 5).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(white.path().len(), 1); -} - -#[test] -fn scheduled_alternative_is_credited_only_to_actual_move_and_hidden_target_stays_unseen() { - let rep = repertoire("1. e4 (1. d4) *"); - let mut session = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!(session.target().unwrap().expected_uci, "e2e4"); - assert_eq!( - session.play_uci("d2d4", 1).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.total_mistakes(), 0); - assert_eq!(session.stats().move_stats.len(), 1); - assert_eq!(session.stats().move_stats[0].key.expected_uci, "d2d4"); - assert_eq!(session.stats().move_stats[0].correct, 1); - let next = TrainingSession::new_srs( - &rep, - TrainingMode::White, - session.into_stats(), - 2, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!(next.target().unwrap().expected_uci, "e2e4"); -} - -#[test] -fn practice_preserves_existing_srs_due_and_interval() { - let rep = repertoire("1. e4 *"); - let mut srs = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - srs.play_uci("e2e4", 1).unwrap(); - let due = srs.stats().move_stats[0].due; - let interval = srs.stats().move_stats[0].interval_seconds; - let mut practice = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::Practice, - srs.into_stats(), - 2, - ) - .unwrap(); - practice.play_uci("e2e4", 3).unwrap(); - assert_eq!(practice.stats().move_stats[0].due, due); - assert_eq!(practice.stats().move_stats[0].interval_seconds, interval); -} - -#[test] -fn practice_scope_replay_origin_precedes_automatic_moves_and_preserves_counters() { - let rep = repertoire( - "[SetUp \"1\"]\n[FEN \"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 7 42\"]\n\n42. e4 e5 *", - ); - let session = TrainingSession::scoped( - &rep, - TrainingScope::whole().with_context(false), - TrainingMode::Black, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.scope_start_position().turn(), Color::White); - assert_eq!(session.position().turn(), Color::Black); - assert_eq!(session.path().len(), 1); - assert_eq!(session.scope_start_position().fullmoves().get(), 42); - assert_eq!(session.scope_start_position().halfmoves(), 7); -} - -#[test] -fn practice_next_branch_hint_follows_proposal_and_both_path_completion_is_once() { - let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::Practice, - StatsData::default(), - 0, - ) - .unwrap(); - assert_eq!(session.hint(1).unwrap().uci, "e2e4"); - session.next_path(2).unwrap(); - assert_eq!(session.hint(3).unwrap().uci, "e2e4"); - session.next_path(4).unwrap(); - assert_eq!(session.hint(5).unwrap().uci, "d2d4"); - assert_eq!(session.play_uci("d2d4", 6).unwrap(), TrainingVerdict::Right); - assert_eq!(session.hint(7).unwrap().uci, "d7d5"); - assert_eq!( - session.play_uci("d7d5", 8).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.play_uci("c2c4", 9).unwrap(), TrainingVerdict::Done); - let paths = &session.stats().path_stats; - assert_eq!(paths.len(), 1); - assert_eq!(paths[0].key.path, strings(&["d2d4", "d7d5"])); - assert_eq!(paths[0].completions, 1); - assert_eq!( - session - .stats() - .runs(&rep.id, TrainingMode::Both) - .unwrap() - .completions, - 1 - ); - session.next_path(10).unwrap(); - assert_eq!(session.hint(11).unwrap().uci, "e2e4"); - // Deviating to another valid branch makes the hint follow that actual branch. - session.play_uci("d2d4", 12).unwrap(); - assert_eq!(session.hint(13).unwrap().uci, "d7d5"); -} - -#[test] -fn source_paths_and_random_cycle_do_not_multiply_transpositions() { - let mut rep = repertoire( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O (7... d6 8. c3 O-O 9. h3 Nb8 (9... Bb7 10. d4 Re8 11. Nbd2 Bf8) (9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 cxd4) 10. d4 Nbd7) 8. c3 d6 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 Bd7 13. Nf1 *", - ); - rep.max_plies = u32::MAX; - let tree = RepertoireTree::new(&rep); - let source: std::collections::BTreeSet> = { - let mut paths = std::collections::BTreeSet::new(); - tree.visit_source_paths(&TrainingScope::whole(), |moves| { - paths.insert(moves.to_vec()); - std::ops::ControlFlow::Continue(()) - }) - .unwrap(); - paths - }; - assert_eq!(source.len(), 4); - assert!(tree.training_paths(&TrainingScope::whole()).unwrap().len() > source.len()); - - let mut session = random_session(&rep, TrainingMode::Both, 42); - for step in 0..source.len() { - let route = random_route(&session); - assert!( - source.contains(&route), - "route={route:?}\nsource={source:?}" - ); - if step + 1 < source.len() { - session.next_path(step as i64).unwrap(); - } - } - let saved = serde_json::to_value(session.stats()).unwrap(); - assert_eq!(saved["random_practice_cursors"][0]["count"], 4); -} - -#[test] -fn random_practice_is_deterministic_and_covers_every_route_before_a_new_cycle() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) *"); - let expected: std::collections::BTreeSet> = RepertoireTree::new(&rep) - .training_paths(&TrainingScope::whole()) - .unwrap() - .into_iter() - .map(|path| path.moves) - .collect(); - assert_eq!(expected.len(), 3); - let mut left = random_session(&rep, TrainingMode::Both, 42); - let mut right = random_session(&rep, TrainingMode::Both, 42); - let mut routes = Vec::new(); - for step in 0..6 { - assert_eq!(left.scope(), right.scope()); - assert_eq!(random_route(&left), random_route(&right)); - routes.push(random_route(&left)); - if step < 5 { - left.next_path(step).unwrap(); - right.next_path(step).unwrap(); - } - } - for cycle in routes.chunks(3) { - let actual: std::collections::BTreeSet> = cycle.iter().cloned().collect(); - assert_eq!(actual.len(), 3); - assert_eq!(actual, expected); - } -} - -#[test] -fn random_practice_mid_path_context_has_the_correct_side_for_every_mode() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 *"); - for mode in [TrainingMode::White, TrainingMode::Black, TrainingMode::Both] { - let mut session = None; - for seed in 0..64 { - let candidate = random_session(&rep, mode, seed); - if !candidate.path().is_empty() { - session = Some(candidate); - break; - } - } - let mut session = session.expect("a deterministic mid-path start"); - let start = session.path().len(); - assert!(start > 0); - assert!(session.path().iter().all(|played| played.automatic)); - assert!(session.attempts().is_empty()); - assert_eq!(session.scope().prefix.len(), start + 1); - assert_eq!( - session.scope().prefix.last().unwrap(), - &session.suggested_path().unwrap()[0] - ); - assert_eq!(random_route(&session).len(), 12); - assert!(session.suggested_path().unwrap().len() >= stats::MIN_RANDOM_CONTINUATION_PLIES); - assert_eq!( - session.position_key(), - session.path().last().unwrap().position_after - ); - if let Some(color) = mode.user_color() { - assert_eq!(session.position().turn(), color); - } - let target = session.suggested_path().unwrap()[0].clone(); - assert!(matches!( - session.play_uci(&target, 1).unwrap(), - TrainingVerdict::Right | TrainingVerdict::Finished - )); - assert!(!session.path()[start].automatic); - } -} - -#[test] -fn random_repeat_preserves_actual_route_start_and_the_next_cursor() { - let rep = repertoire("1. e4 e5 (1... c5) 2. Nf3 (2. c4) Nc6 3. Bb5 a6 4. Ba4 Nf6 *"); - let mut session = (0..64) - .map(|seed| random_session(&rep, TrainingMode::Both, seed)) - .find(|session| !session.path().is_empty()) - .expect("a deterministic mid-path start"); - let initial_scope = session.scope().clone(); - let initial_context = session.path().to_vec(); - let selected = session.suggested_path().unwrap().to_vec(); - for (index, mv) in selected.iter().enumerate() { - session.play_uci(mv, index as i64).unwrap(); - } - assert!(session.is_done()); - let completed_path = session.path().to_vec(); - let completed_route = random_route(&session); - let before_repeat = serde_json::to_vec(session.stats()).unwrap(); - - session.restart(10).unwrap(); - assert_eq!(session.scope(), &initial_scope); - assert_eq!(session.path(), initial_context); - assert_eq!(serde_json::to_vec(session.stats()).unwrap(), before_repeat); - for (index, mv) in selected.iter().enumerate() { - session.play_uci(mv, 10 + index as i64).unwrap(); - } - assert_eq!(session.path(), completed_path); - - session.next_path(20).unwrap(); - let next = random_route(&session); - assert_ne!(next, completed_route); - assert!( - RepertoireTree::new(&rep) - .training_paths(&TrainingScope::whole()) - .unwrap() - .iter() - .any(|path| path.moves == next) - ); -} - -#[test] -fn random_practice_path_count_change_starts_a_fresh_complete_cycle() { - let rep = repertoire("1. e4 (1. d4 d5) e5 *"); - let mut initial = random_session(&rep, TrainingMode::Both, 7); - initial.next_path(1).unwrap(); - let before = serde_json::to_value(initial.stats()).unwrap(); - let old_seed = before["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(); - let stats = initial.into_stats(); - let mut expanded = rep.clone(); - expanded.pgn = chess_core::parse_str("1. e4 (1. d4 d5) (1. c4 e5) (1. Nf3 Nf6) e5 (1... c5) *") - .game - .to_pgn(); - let mut session = TrainingSession::scoped_random_with_seed( - &expanded, - TrainingScope::whole(), - TrainingMode::Both, - stats, - 2, - 7, - ) - .unwrap(); - let after = serde_json::to_value(session.stats()).unwrap(); - assert_ne!( - after["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(), - old_seed - ); - assert_eq!(after["random_practice_cursors"][0]["position"], 1); - assert_eq!(after["random_practice_cursors"][0]["count"], 5); - - let mut routes = vec![random_route(&session)]; - for now in 3..7 { - session.next_path(now).unwrap(); - routes.push(random_route(&session)); - } - let unique: std::collections::BTreeSet> = routes.into_iter().collect(); - assert_eq!(unique.len(), 5); -} - -#[test] -fn random_practice_reads_old_stats_without_the_random_cursor_field() { - let rep = repertoire("1. e4 e5 (1... c5) *"); - let mut old = serde_json::to_value(StatsData::default()).unwrap(); - assert!( - old.as_object_mut() - .unwrap() - .remove("random_practice_cursors") - .is_some() - ); - let stats: StatsData = serde_json::from_value(old).unwrap(); - let session = TrainingSession::scoped_random_with_seed( - &rep, - TrainingScope::whole(), - TrainingMode::Both, - stats, - 0, - 11, - ) - .unwrap(); - assert!(session.suggested_path().is_some()); - let saved = serde_json::to_value(session.stats()).unwrap(); - assert_eq!(saved["random_practice_cursors"][0]["position"], 1); -} - -#[test] -fn random_start_keeps_seven_plies_and_finishes_on_the_actual_last_move() { - let mut long = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 *"); - long.max_plies = 1; - for seed in 0..64 { - let session = random_session(&long, TrainingMode::Both, seed); - assert_eq!(random_route(&session).len(), 12); - assert!(session.suggested_path().unwrap().len() >= stats::MIN_RANDOM_CONTINUATION_PLIES); - } - - let short = repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - for seed in 0..64 { - let session = random_session(&short, TrainingMode::Both, seed); - assert!(session.path().is_empty()); - assert_eq!(session.suggested_path().unwrap().len(), 6); - } - - let mut session = random_session(&long, TrainingMode::Both, 42); - let selected = session.suggested_path().unwrap().to_vec(); - let automatic = session.path().len(); - for (index, mv) in selected.iter().enumerate() { - session.play_uci(mv, index as i64).unwrap(); - } - assert!(session.is_done()); - let record = session - .stats() - .runs(&long.id, TrainingMode::Both) - .unwrap() - .recent - .last() - .unwrap(); - assert_eq!(record.path, selected); - assert_eq!(record.automatic_moves, automatic as u32); - assert_eq!(record.user_attempts, selected.len() as u32); -} - -#[test] -fn random_scoped_start_never_escapes_the_base_end_or_creates_an_invalid_scope() { - let rep = repertoire("1. e4 e5 2. Nf3 Nc6 (2... Nf6) 3. Bb5 a6 *"); - let prefix = strings(&["e2e4", "e7e5", "g1f3"]); - let end = strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]); - let base = TrainingScope::between(prefix.clone(), end.clone()); - let mut saw_short = false; - let mut saw_end = false; - for seed in 0..64 { - let session = TrainingSession::scoped_random_with_seed( - &rep, - base.clone(), - TrainingMode::Both, - StatsData::default(), - 0, - seed, - ) - .unwrap(); - let route = random_route(&session); - assert!(route.starts_with(&prefix)); - assert!(route.len() <= end.len()); - assert_eq!(session.scope().end_prefix.as_ref(), Some(&route)); - saw_short |= route.len() < end.len(); - saw_end |= route == end; - } - assert!(saw_short && saw_end); -} - -#[test] -fn random_practice_pgn_fingerprint_change_restarts_the_cycle_at_the_same_count() { - let rep = repertoire("1. e4 (1. d4 d5) e5 *"); - let initial = random_session(&rep, TrainingMode::Both, 19); - let before = serde_json::to_value(initial.stats()).unwrap(); - let old_seed = before["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(); - let old_fingerprint = before["random_practice_cursors"][0]["fingerprint"].clone(); - assert_eq!(before["random_practice_cursors"][0]["position"], 1); - assert_eq!(before["random_practice_cursors"][0]["count"], 2); - - let mut changed = rep.clone(); - changed.pgn = chess_core::parse_str("1. c4 (1. Nf3 Nf6) e5 *") - .game - .to_pgn(); - let mut session = TrainingSession::scoped_random_with_seed( - &changed, - TrainingScope::whole(), - TrainingMode::Both, - initial.into_stats(), - 1, - 19, - ) - .unwrap(); - let after = serde_json::to_value(session.stats()).unwrap(); - assert_eq!(after["random_practice_cursors"][0]["count"], 2); - assert_eq!(after["random_practice_cursors"][0]["position"], 1); - assert_ne!( - after["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(), - old_seed - ); - assert_ne!( - after["random_practice_cursors"][0]["fingerprint"], - old_fingerprint - ); - let first = random_route(&session); - session.next_path(2).unwrap(); - assert_ne!(random_route(&session), first); -} - -#[test] -fn random_practice_cursor_without_fingerprint_safely_starts_a_new_cycle() { - let rep = repertoire("1. e4 (1. d4 d5) e5 *"); - let initial = random_session(&rep, TrainingMode::Both, 23); - let mut old = serde_json::to_value(initial.stats()).unwrap(); - let cursor = old["random_practice_cursors"][0].as_object_mut().unwrap(); - assert!(cursor.remove("fingerprint").is_some()); - let old_seed = cursor["seed"].as_u64().unwrap(); - assert_eq!(cursor["position"], 1); - let stats: StatsData = serde_json::from_value(old).unwrap(); - - let session = TrainingSession::scoped_random_with_seed( - &rep, - TrainingScope::whole(), - TrainingMode::Both, - stats, - 1, - 23, - ) - .unwrap(); - let after = serde_json::to_value(session.stats()).unwrap(); - assert!(after["random_practice_cursors"][0]["fingerprint"].is_number()); - assert_eq!(after["random_practice_cursors"][0]["position"], 1); - assert_ne!( - after["random_practice_cursors"][0]["seed"] - .as_u64() - .unwrap(), - old_seed - ); -} diff --git a/crates/trainer/src/repertoire/mod.rs b/crates/trainer/src/repertoire/mod.rs index 7c4bfaa..183f091 100644 --- a/crates/trainer/src/repertoire/mod.rs +++ b/crates/trainer/src/repertoire/mod.rs @@ -12,7 +12,6 @@ mod learning_session; mod line_analytics; mod model; mod scope; -mod session; mod srs; mod stats; mod store; @@ -51,10 +50,6 @@ pub use model::{ Repertoire, RepertoireError, RepertoireId, }; pub use scope::{TrainingScope, TrainingScopeKey}; -pub use session::{ - FirstMoveChooser, MoveChooser, PlayedMove, PreparedNextPath, SessionAttempt, SessionError, - TrainingSession, TrainingVerdict, -}; pub use srs::{ DEFAULT_GROWTH_FACTOR, FIRST_CORRECT_DELAY_SECONDS, MIN_PRACTICAL_INTERVAL_SECONDS, MISTAKE_DELAY_SECONDS, PREVIEW_DELAY_SECONDS, SRS_MAX_INTERVAL_SECONDS, SrsSettings, @@ -62,16 +57,15 @@ pub use srs::{ apply_independent_correct, apply_independent_wrong, apply_preview, }; pub use stats::{ - AttemptRecord, INITIAL_INTERVAL_SECONDS, INTRODUCTION_BATCH_SIZE, MAX_INTERVAL_SECONDS, - MISTAKE_INTERVAL_SECONDS, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, - RunStats, STATS_VERSION, SrsPolicy, StatsData, TrainingMode, + AttemptRecord, MoveKey, MoveStats, PathKey, PathStats, QueueMode, RunRecord, RunStats, + STATS_VERSION, StatsData, TrainingMode, }; pub use store::{ LEARNING_STORE_VERSION, LearningSession, LearningStore, LearningStoreData, LibraryStore, MigrationReport, PersistedAttempt, PersistedLearningReset, PersistedLearningSnapshot, PersistedSessionAttempt, StatsStore, StoreError, }; -pub use tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4}; +pub use tree::{Candidate, RepertoireTree, fen4}; #[cfg(test)] mod acceptance_tests; diff --git a/crates/trainer/src/repertoire/scope.rs b/crates/trainer/src/repertoire/scope.rs index 353505e..38e788d 100644 --- a/crates/trainer/src/repertoire/scope.rs +++ b/crates/trainer/src/repertoire/scope.rs @@ -16,33 +16,6 @@ impl TrainingScope { Self::default() } - pub fn from_prefix(prefix: Vec) -> Self { - Self { - prefix, - ..Self::default() - } - } - - pub fn between(prefix: Vec, end_prefix: Vec) -> Self { - Self { - prefix, - end_prefix: Some(end_prefix), - ..Self::default() - } - } - - pub fn with_context(mut self, include_context: bool) -> Self { - self.include_context = include_context; - self - } - - pub fn key(&self) -> TrainingScopeKey { - TrainingScopeKey { - prefix: self.prefix.clone(), - end_prefix: self.end_prefix.clone(), - } - } - pub(crate) fn parent_prefix(&self) -> &[String] { self.prefix .get(..self.prefix.len().saturating_sub(1)) diff --git a/crates/trainer/src/repertoire/session.rs b/crates/trainer/src/repertoire/session.rs deleted file mode 100644 index 490c5e0..0000000 --- a/crates/trainer/src/repertoire/session.rs +++ /dev/null @@ -1,1162 +0,0 @@ -use std::collections::BTreeSet; - -use chess_core::shakmaty::{CastlingMode, Chess, Move, Position, uci::UciMove}; -use chess_core::{Game, NodeId}; - -use super::model::{Repertoire, RepertoireId}; -use super::scope::TrainingScope; -use super::stats::{MoveKey, PathKey, QueueMode, RunRecord, SrsPolicy, StatsData, TrainingMode}; -use super::tree::{Candidate, RepertoireTree, TrainingPath, TrainingTarget, fen4}; - -pub trait MoveChooser: Send { - fn choose(&mut self, candidates: &[Candidate]) -> Option; -} - -#[derive(Clone, Copy, Debug, Default)] -pub struct FirstMoveChooser; - -impl MoveChooser for FirstMoveChooser { - fn choose(&mut self, candidates: &[Candidate]) -> Option { - (!candidates.is_empty()).then_some(0) - } -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PlayedMove { - pub uci: String, - pub san: String, - pub automatic: bool, - pub position_before: String, - pub position_after: String, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SessionAttempt { - pub position_fen4: String, - pub expected_uci: String, - pub actual_uci: String, - pub correct: bool, - pub hinted: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum TrainingVerdict { - Right, - Finished, - Wrong, - TryAgain, - Done, -} - -#[derive(Debug)] -pub enum SessionError { - InvalidUci(String), - IllegalMove(String), - Chooser, - MissingTargetPath, - InvalidScope(String), - InvalidSrsPolicy, - InvalidQueueMode(&'static str), -} - -impl std::fmt::Display for SessionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::InvalidUci(uci) => write!(f, "invalid UCI move: {uci}"), - Self::IllegalMove(uci) => write!(f, "illegal move in the current position: {uci}"), - Self::Chooser => f.write_str("the continuation chooser returned no valid candidate"), - Self::MissingTargetPath => { - f.write_str("the target path is no longer present in the repertoire") - } - Self::InvalidScope(message) => write!(f, "invalid training scope: {message}"), - Self::InvalidSrsPolicy => { - f.write_str("SRS policies apply only to White/Black spaced repetition") - } - Self::InvalidQueueMode(message) => f.write_str(message), - } - } -} - -impl std::error::Error for SessionError {} - -/// A live tree-training state machine. Statistics are owned by the session so callers -/// can persist them after each accepted event or at a lifecycle boundary they choose. -pub struct TrainingSession { - repertoire_id: RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - scope: TrainingScope, - base_scope: TrainingScope, - random_practice_seed: Option, - repertoire_fingerprint: u64, - srs_policy: SrsPolicy, - tree: RepertoireTree, - stats: StatsData, - chooser: Box, - current: NodeId, - position: Chess, - target: Option, - suggested_path: Option, - seen_positions: BTreeSet, - actual_path: Vec, - done: bool, - completion_recorded: bool, - current_wrong: u32, - current_hinted: bool, - hint_visible: bool, - run_hinted: bool, - mistakes: u32, - hints: u32, - path: Vec, - attempts: Vec, - completed_targets: BTreeSet, - deferred_targets: BTreeSet, -} - -pub struct PreparedNextPath { - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - random_practice_seed: Option, -} - -impl PreparedNextPath { - pub fn run(self, repertoire: &Repertoire, now: i64) -> Result { - let Self { - scope, - mode, - queue_mode, - stats, - random_practice_seed, - } = self; - if let Some(seed) = random_practice_seed { - TrainingSession::scoped_random_seeded(repertoire, scope, mode, stats, now, seed) - } else { - TrainingSession::scoped_with_chooser( - repertoire, - scope, - mode, - queue_mode, - stats, - now, - Box::::default(), - ) - } - } -} - -impl TrainingSession { - pub fn new( - repertoire: &Repertoire, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::with_chooser( - repertoire, - mode, - queue_mode, - stats, - now, - Box::::default(), - ) - } - - pub fn new_random( - repertoire: &Repertoire, - mode: TrainingMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::scoped_random(repertoire, TrainingScope::whole(), mode, stats, now) - } - - pub fn scoped_random( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::scoped_random_seeded(repertoire, scope, mode, stats, now, random_seed()) - } - - #[cfg(test)] - pub(crate) fn scoped_random_with_seed( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - seed: u64, - ) -> Result { - Self::scoped_random_seeded(repertoire, scope, mode, stats, now, seed) - } - - fn scoped_random_seeded( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - seed: u64, - ) -> Result { - Self::build( - repertoire, - scope, - mode, - QueueMode::Practice, - stats, - now, - (None, Box::::default(), Some(seed)), - ) - } - - pub fn with_chooser( - repertoire: &Repertoire, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - chooser: Box, - ) -> Result { - Self::scoped_with_chooser( - repertoire, - TrainingScope::whole(), - mode, - queue_mode, - stats, - now, - chooser, - ) - } - - pub fn scoped( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - ) -> Result { - Self::scoped_with_chooser( - repertoire, - scope, - mode, - queue_mode, - stats, - now, - Box::::default(), - ) - } - - pub fn new_srs( - repertoire: &Repertoire, - mode: TrainingMode, - stats: StatsData, - now: i64, - policy: SrsPolicy, - ) -> Result { - Self::scoped_srs(repertoire, TrainingScope::whole(), mode, stats, now, policy) - } - - pub fn scoped_srs( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - policy: SrsPolicy, - ) -> Result { - Self::scoped_srs_with_chooser( - repertoire, - scope, - mode, - stats, - now, - policy, - Box::::default(), - ) - } - - pub fn scoped_with_chooser( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - chooser: Box, - ) -> Result { - Self::build( - repertoire, - scope, - mode, - queue_mode, - stats, - now, - (None, chooser, None), - ) - } - - pub fn scoped_srs_with_chooser( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - stats: StatsData, - now: i64, - policy: SrsPolicy, - chooser: Box, - ) -> Result { - Self::build( - repertoire, - scope, - mode, - QueueMode::SpacedRepetition, - stats, - now, - (Some(policy), chooser, None), - ) - } - - fn build( - repertoire: &Repertoire, - scope: TrainingScope, - mode: TrainingMode, - queue_mode: QueueMode, - stats: StatsData, - now: i64, - options: (Option, Box, Option), - ) -> Result { - let (policy, chooser, random_practice_seed) = options; - if policy.is_some() - && (mode == TrainingMode::Both || queue_mode != QueueMode::SpacedRepetition) - { - return Err(SessionError::InvalidSrsPolicy); - } - let tree = if random_practice_seed.is_some() { - let mut full = repertoire.clone(); - full.max_plies = u32::MAX; - RepertoireTree::new(&full) - } else { - RepertoireTree::new(repertoire) - }; - let current = tree - .scope_anchor(&scope) - .map_err(SessionError::InvalidScope)?; - let srs_policy = policy.unwrap_or(SrsPolicy::Due); - let mut session = Self { - repertoire_id: repertoire.id.clone(), - mode, - queue_mode, - base_scope: scope.clone(), - scope, - random_practice_seed, - repertoire_fingerprint: super::model::stable_hash(repertoire.pgn.as_bytes()), - srs_policy, - stats, - chooser, - position: tree - .position(current) - .cloned() - .unwrap_or_else(|| tree.game().start().position().clone()), - current, - tree, - target: None, - suggested_path: None, - seen_positions: BTreeSet::new(), - actual_path: Vec::new(), - done: false, - completion_recorded: false, - current_wrong: 0, - current_hinted: false, - hint_visible: false, - run_hinted: false, - mistakes: 0, - hints: 0, - path: Vec::new(), - attempts: Vec::new(), - completed_targets: BTreeSet::new(), - deferred_targets: BTreeSet::new(), - }; - session.initialize(now, true)?; - Ok(session) - } - - pub fn game(&self) -> &Game { - self.tree.game() - } - - pub fn stats(&self) -> &StatsData { - &self.stats - } - - pub fn stats_mut(&mut self) -> &mut StatsData { - &mut self.stats - } - - pub fn into_stats(self) -> StatsData { - self.stats - } - - pub fn mode(&self) -> TrainingMode { - self.mode - } - - pub fn queue_mode(&self) -> QueueMode { - self.queue_mode - } - - pub fn scope(&self) -> &TrainingScope { - &self.scope - } - - pub fn srs_policy(&self) -> SrsPolicy { - self.srs_policy - } - - pub fn suggested_path(&self) -> Option<&[String]> { - self.suggested_path - .as_ref() - .map(|path| path.moves.as_slice()) - } - - pub fn current_node(&self) -> NodeId { - self.current - } - - pub fn position(&self) -> &Chess { - &self.position - } - - /// Full position at the scope anchor, before any automatic opponent move. - /// Unlike FEN4 this retains the counters needed for faithful UI replay. - pub fn scope_start_position(&self) -> &Chess { - self.tree - .scope_anchor(&self.scope) - .ok() - .and_then(|anchor| self.tree.position(anchor)) - .unwrap_or_else(|| self.tree.game().start().position()) - } - - pub fn position_key(&self) -> String { - fen4(self.position()) - } - - pub fn target(&self) -> Option<&TrainingTarget> { - self.target.as_ref() - } - - pub fn candidates(&self) -> Vec { - if self.done || self.at_depth_boundary() { - Vec::new() - } else { - self.tree.scoped_candidates(self.current, &self.scope) - } - } - - pub fn path(&self) -> &[PlayedMove] { - &self.path - } - - pub fn attempts(&self) -> &[SessionAttempt] { - &self.attempts - } - - pub fn errors(&self) -> impl Iterator { - self.attempts.iter().filter(|attempt| !attempt.correct) - } - - pub fn total_mistakes(&self) -> u32 { - self.mistakes - } - - pub fn hinted(&self) -> bool { - self.run_hinted - } - - pub fn is_done(&self) -> bool { - self.done - } - - pub fn may_hint(&self) -> bool { - !self.done && (self.queue_mode == QueueMode::Practice || self.current_wrong >= 3) - } - - /// Practice offers a hint immediately; scheduled repetition unlocks it after three - /// wrong attempts. Practice follows its proposed branch while the actual path - /// matches it, then falls back to the first enabled continuation. Every enabled - /// move remains a valid answer. - pub fn hint(&mut self, now: i64) -> Option { - if !self.may_hint() { - return None; - } - let candidate = match &self.target { - Some(target) => { - self.tree - .scoped_candidate(self.current, &target.expected_uci, &self.scope) - } - None => { - let candidates = self.tree.scoped_candidates(self.current, &self.scope); - let proposed = self - .suggested_path - .as_ref() - .filter(|path| { - self.queue_mode == QueueMode::Practice - && path.moves.starts_with(&self.actual_path) - }) - .and_then(|path| path.moves.get(self.actual_path.len())); - proposed - .and_then(|uci| candidates.iter().find(|candidate| &candidate.uci == uci)) - .cloned() - .or_else(|| candidates.into_iter().next()) - } - }?; - if self.hint_visible { - return Some(candidate); - } - let key = self.key_for(&candidate.uci); - self.stats.record_hint(key, now); - self.hints = self.hints.saturating_add(1); - self.current_hinted = true; - self.run_hinted = true; - self.hint_visible = true; - Some(candidate) - } - - pub fn play_uci(&mut self, uci: &str, now: i64) -> Result { - if self.done { - return Ok(TrainingVerdict::Done); - } - let parsed = uci - .parse::() - .map_err(|_| SessionError::InvalidUci(uci.to_owned()))?; - let mv = parsed - .to_move(self.position()) - .map_err(|_| SessionError::IllegalMove(uci.to_owned()))?; - self.play(mv, now) - } - - pub fn play(&mut self, mv: Move, now: i64) -> Result { - if self.done { - return Ok(TrainingVerdict::Done); - } - if !self.position().is_legal(mv) { - return Err(SessionError::IllegalMove( - mv.to_uci(CastlingMode::Standard).to_string(), - )); - } - let actual_uci = mv.to_uci(CastlingMode::Standard).to_string(); - let candidates = self.candidates(); - if self.queue_mode == QueueMode::Practice { - if let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.mv == mv) - .cloned() - { - return self.accept_practice(candidate, now); - } - if let Some(expected) = candidates.first() { - self.reject(expected, &actual_uci, now); - } - return Ok(TrainingVerdict::Wrong); - } - if self.mode == TrainingMode::Both { - if let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.mv == mv) - .cloned() - { - return Ok(self.accept_both(candidate, now)); - } - if let Some(expected) = candidates.first() { - self.reject(expected, &actual_uci, now); - } - return Ok(TrainingVerdict::Wrong); - } - - let Some(target) = self.target.clone() else { - return Ok(TrainingVerdict::Done); - }; - if target.expected_uci == actual_uci { - let candidate = candidates - .iter() - .find(|candidate| candidate.uci == actual_uci) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - return self.accept_one_side(candidate, now); - } - if let Some(candidate) = candidates - .iter() - .find(|candidate| candidate.mv == mv) - .cloned() - { - return self.accept_one_side(candidate, now); - } - let expected = candidates - .iter() - .find(|candidate| candidate.uci == target.expected_uci) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - self.reject(&expected, &actual_uci, now); - Ok(TrainingVerdict::Wrong) - } - - /// Repeats the same proposed path (or restarts the current one-side queue). It does - /// not advance a path cursor and never counts an unfinished run as complete. - pub fn restart(&mut self, now: i64) -> Result<(), SessionError> { - if self.queue_mode == QueueMode::Practice && !self.actual_path.is_empty() { - self.suggested_path = Some(TrainingPath { - moves: self.actual_path.clone(), - }); - } - self.reset_run()?; - self.initialize(now, false) - } - - /// Captures the inputs for a next-path run without changing this session. The - /// expensive tree traversal happens only when `PreparedNextPath::run` is called. - pub fn prepare_next_path(&self) -> Result { - if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice { - return Err(SessionError::InvalidQueueMode( - "next_path is available in branch practice or Both mode", - )); - } - let scope = if self.random_practice_seed.is_some() { - &self.base_scope - } else { - &self.scope - }; - Ok(PreparedNextPath { - scope: scope.clone(), - mode: self.mode, - queue_mode: self.queue_mode, - stats: self.stats.clone(), - random_practice_seed: self.random_practice_seed, - }) - } - - /// Selects the next proposed root/scope-to-boundary path. Enabled deviations remain - /// free; the actual path, rather than this proposal, receives completion statistics. - pub fn next_path(&mut self, now: i64) -> Result<(), SessionError> { - if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice { - return Err(SessionError::InvalidQueueMode( - "next_path is available in branch practice or Both mode", - )); - } - if self.random_practice_seed.is_some() { - self.scope = self.base_scope.clone(); - } - self.reset_run()?; - self.suggested_path = None; - self.initialize(now, true) - } - - pub fn restart_with_policy(&mut self, now: i64, policy: SrsPolicy) -> Result<(), SessionError> { - if self.mode == TrainingMode::Both { - return Err(SessionError::InvalidSrsPolicy); - } - self.queue_mode = QueueMode::SpacedRepetition; - self.srs_policy = policy; - self.reset_run()?; - self.initialize(now, true) - } - - fn reset_run(&mut self) -> Result<(), SessionError> { - self.current = self - .tree - .scope_anchor(&self.scope) - .map_err(SessionError::InvalidScope)?; - self.target = None; - self.done = false; - self.completion_recorded = false; - self.current_wrong = 0; - self.current_hinted = false; - self.hint_visible = false; - self.run_hinted = false; - self.mistakes = 0; - self.hints = 0; - self.path.clear(); - self.attempts.clear(); - self.actual_path.clear(); - self.seen_positions.clear(); - self.completed_targets.clear(); - self.deferred_targets.clear(); - Ok(()) - } - - fn initialize(&mut self, now: i64, select_path: bool) -> Result<(), SessionError> { - if self.queue_mode == QueueMode::Practice { - if select_path { - if self.random_practice_seed.is_some() { - self.select_random_path()?; - } else { - self.suggested_path = self - .stats - .next_practice_path(&self.tree, &self.repertoire_id, self.mode, &self.scope) - .map_err(SessionError::InvalidScope)?; - } - } - self.prepare_scope_start()?; - if self.suggested_path.is_none() { - self.done = true; - return Ok(()); - } - self.advance_practice_opponent(now)?; - return Ok(()); - } - if self.mode == TrainingMode::Both { - if select_path { - self.suggested_path = self - .stats - .next_training_path( - &self.tree, - &self.repertoire_id, - &self.scope, - self.queue_mode, - ) - .map_err(SessionError::InvalidScope)?; - if self.suggested_path.is_some() { - self.stats - .path_presented(&self.repertoire_id, &self.scope, self.queue_mode); - } - } - self.prepare_scope_start()?; - if self.suggested_path.is_none() - || self - .tree - .scoped_candidates(self.current, &self.scope) - .is_empty() - { - self.done = true; - } - Ok(()) - } else { - self.prepare_next_target(now).map(|_| ()) - } - } - - fn select_random_path(&mut self) -> Result<(), SessionError> { - let seed = self - .random_practice_seed - .ok_or(SessionError::InvalidQueueMode( - "random practice seed is missing", - ))?; - let selected = self - .stats - .next_random_practice_path( - &self.tree, - &self.repertoire_id, - self.mode, - &self.base_scope, - self.repertoire_fingerprint, - seed, - ) - .map_err(SessionError::InvalidScope)?; - let Some(selected) = selected else { - self.scope = self.base_scope.clone(); - self.suggested_path = None; - return Ok(()); - }; - let prefix_moves = selected - .path - .moves - .get(..=selected.start) - .ok_or(SessionError::MissingTargetPath)?; - let suggested = selected - .path - .moves - .get(selected.start..) - .ok_or(SessionError::MissingTargetPath)? - .to_vec(); - let mut prefix = self.base_scope.parent_prefix().to_vec(); - prefix.extend(prefix_moves.iter().cloned()); - let end_prefix = self.base_scope.end_prefix.as_ref().map(|_| { - let mut end = self.base_scope.parent_prefix().to_vec(); - end.extend(selected.path.moves.iter().cloned()); - end - }); - self.scope = TrainingScope { - prefix, - end_prefix, - include_context: true, - }; - self.suggested_path = Some(TrainingPath { moves: suggested }); - Ok(()) - } - - fn prepare_scope_start(&mut self) -> Result<(), SessionError> { - let anchor = self - .tree - .scope_anchor(&self.scope) - .map_err(SessionError::InvalidScope)?; - if self.scope.include_context { - let context = self - .tree - .path(anchor) - .map(<[String]>::to_vec) - .ok_or(SessionError::MissingTargetPath)?; - self.current = self.tree.root(); - self.position = self.tree.game().start().position().clone(); - for uci in context { - let candidate = self - .tree - .candidate(self.current, &uci) - .ok_or(SessionError::MissingTargetPath)?; - self.advance(candidate, true); - } - } else { - self.current = anchor; - self.position = self - .tree - .position(anchor) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - } - self.seen_positions.insert(self.position_key()); - Ok(()) - } - - fn at_depth_boundary(&self) -> bool { - if self.mode != TrainingMode::Both && self.queue_mode != QueueMode::Practice { - return false; - } - let start = self.scope.parent_prefix().len(); - start.saturating_add(self.actual_path.len()) >= self.tree.max_plies() as usize - } - - fn practice_boundary(&self) -> bool { - self.at_depth_boundary() - || self - .tree - .scoped_candidates(self.current, &self.scope) - .is_empty() - } - - fn advance_practice_opponent(&mut self, now: i64) -> Result<(), SessionError> { - if self.practice_boundary() { - self.finish(now); - return Ok(()); - } - while self - .mode - .user_color() - .is_some_and(|color| self.position.turn() != color) - { - let candidates = self.candidates(); - let suggested = self - .suggested_path - .as_ref() - .filter(|path| path.moves.starts_with(&self.actual_path)) - .and_then(|path| path.moves.get(self.actual_path.len())); - let selected = suggested - .and_then(|uci| candidates.iter().find(|c| &c.uci == uci)) - .cloned(); - let selected = match selected { - Some(selected) => selected, - None => { - let index = self - .chooser - .choose(&candidates) - .filter(|index| *index < candidates.len()) - .ok_or(SessionError::Chooser)?; - candidates[index].clone() - } - }; - self.actual_path.push(selected.uci.clone()); - self.advance(selected, true); - let repeated = !self.seen_positions.insert(self.position_key()); - if repeated || self.practice_boundary() { - self.finish(now); - return Ok(()); - } - } - Ok(()) - } - - fn accept_practice( - &mut self, - candidate: Candidate, - now: i64, - ) -> Result { - let key = self.key_for(&candidate.uci); - self.stats - .record_correct(key, now, &candidate.uci, self.current_hinted, false); - self.push_attempt(candidate.uci.clone(), candidate.uci.clone(), true); - self.actual_path.push(candidate.uci.clone()); - self.advance(candidate, false); - self.reset_target_state(); - if !self.seen_positions.insert(self.position_key()) || self.practice_boundary() { - self.finish(now); - } else { - self.advance_practice_opponent(now)?; - } - Ok(if self.done { - TrainingVerdict::Finished - } else { - TrainingVerdict::Right - }) - } - - fn accept_both(&mut self, candidate: Candidate, now: i64) -> TrainingVerdict { - let hinted = self.current_hinted; - let key = self.key_for(&candidate.uci); - self.stats - .record_correct(key, now, &candidate.uci, hinted, false); - self.push_attempt(candidate.uci.clone(), candidate.uci.clone(), true); - self.actual_path.push(candidate.uci.clone()); - self.advance(candidate, false); - self.reset_target_state(); - let repeated = !self.seen_positions.insert(self.position_key()); - if repeated - || self.at_depth_boundary() - || self - .tree - .scoped_candidates(self.current, &self.scope) - .is_empty() - { - self.finish(now); - TrainingVerdict::Finished - } else { - TrainingVerdict::Right - } - } - - fn accept_one_side( - &mut self, - candidate: Candidate, - now: i64, - ) -> Result { - let hinted = self.current_hinted; - let key = self.key_for(&candidate.uci); - if let Some(target) = &self.target - && target.expected_uci != candidate.uci - { - self.deferred_targets.insert(self.target_key(target)); - } - self.stats.record_correct( - key.clone(), - now, - &candidate.uci, - hinted, - self.queue_mode == QueueMode::SpacedRepetition - && self.srs_policy != SrsPolicy::EarlyReview, - ); - if self - .target - .as_ref() - .is_some_and(|target| target.expected_uci == candidate.uci) - { - self.stats.target_completed( - &self.repertoire_id, - self.mode, - self.queue_mode, - &self.scope, - ); - } - self.completed_targets.insert(key); - self.push_attempt(candidate.uci.clone(), candidate.uci.clone(), true); - self.advance(candidate, false); - - let user_color = self.mode.user_color(); - if self.tree.position(self.current).map(|p| p.turn()) != user_color { - let candidates = self.tree.scoped_candidates(self.current, &self.scope); - if !candidates.is_empty() { - let index = self - .chooser - .choose(&candidates) - .filter(|index| *index < candidates.len()) - .ok_or(SessionError::Chooser)?; - let selected = candidates[index].clone(); - self.advance(selected, true); - } - } - - if self.prepare_next_target(now)? { - Ok(TrainingVerdict::Right) - } else { - self.finish(now); - Ok(TrainingVerdict::Finished) - } - } - - fn reject(&mut self, expected: &Candidate, actual_uci: &str, now: i64) { - let key = self.key_for(&expected.uci); - self.stats.record_wrong( - key, - now, - actual_uci, - self.mode != TrainingMode::Both - && self.queue_mode == QueueMode::SpacedRepetition - && self.srs_policy != SrsPolicy::EarlyReview, - ); - self.mistakes = self.mistakes.saturating_add(1); - self.current_wrong = self.current_wrong.saturating_add(1); - self.push_attempt(expected.uci.clone(), actual_uci.to_owned(), false); - } - - fn key_for(&self, expected_uci: &str) -> MoveKey { - MoveKey { - repertoire_id: self.repertoire_id.clone(), - mode: self.mode, - position_fen4: self.position_key(), - expected_uci: if self.mode == TrainingMode::Both { - String::new() - } else { - expected_uci.to_owned() - }, - } - } - - fn push_attempt(&mut self, expected_uci: String, actual_uci: String, correct: bool) { - self.attempts.push(SessionAttempt { - position_fen4: self.position_key(), - expected_uci: if self.mode == TrainingMode::Both { - String::new() - } else { - expected_uci - }, - actual_uci, - correct, - hinted: self.current_hinted, - }); - } - - fn advance(&mut self, candidate: Candidate, automatic: bool) { - let before = self.position_key(); - self.position.play_unchecked(candidate.mv); - self.current = candidate.node; - let after = self.position_key(); - self.path.push(PlayedMove { - uci: candidate.uci, - san: candidate.san, - automatic, - position_before: before, - position_after: after, - }); - } - - fn prepare_next_target(&mut self, now: i64) -> Result { - if self.queue_mode == QueueMode::SpacedRepetition - && self.srs_policy == SrsPolicy::Introduce - && self.completed_targets.len() >= super::stats::INTRODUCTION_BATCH_SIZE - { - self.done = true; - self.target = None; - return Ok(false); - } - let queued = if self.queue_mode == QueueMode::SpacedRepetition { - self.stats.srs_queue( - &self.tree, - &self.repertoire_id, - self.mode, - now, - &self.scope, - self.srs_policy, - ) - } else { - self.stats.scoped_queue( - &self.tree, - &self.repertoire_id, - self.mode, - self.queue_mode, - now, - &self.scope, - ) - }; - let next = queued.into_iter().find(|target| { - !self.completed_targets.contains(&self.target_key(target)) - && !self.deferred_targets.contains(&self.target_key(target)) - }); - let Some(target) = next else { - self.done = true; - self.target = None; - return Ok(false); - }; - if self.scope.include_context { - self.current = self.tree.root(); - self.position = self.tree.game().start().position().clone(); - for uci in &target.path { - let candidate = self - .tree - .candidate(self.current, uci) - .ok_or(SessionError::MissingTargetPath)?; - self.advance(candidate, true); - } - } else { - self.current = self - .tree - .node_at_path(&target.path) - .ok_or(SessionError::MissingTargetPath)?; - self.position = self - .tree - .position(self.current) - .cloned() - .ok_or(SessionError::MissingTargetPath)?; - } - self.target = Some(target); - self.reset_target_state(); - Ok(true) - } - - fn target_key(&self, target: &TrainingTarget) -> MoveKey { - MoveKey { - repertoire_id: self.repertoire_id.clone(), - mode: self.mode, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - } - } - - fn reset_target_state(&mut self) { - self.current_wrong = 0; - self.current_hinted = false; - self.hint_visible = false; - } - - fn finish(&mut self, now: i64) { - self.done = true; - self.target = None; - self.hint_visible = false; - if self.completion_recorded || self.attempts.is_empty() { - return; - } - self.completion_recorded = true; - let path = if self.mode == TrainingMode::Both || self.queue_mode == QueueMode::Practice { - self.actual_path.clone() - } else { - self.path.iter().map(|mv| mv.uci.clone()).collect() - }; - let record = RunRecord { - at: now, - mistakes: self.mistakes, - hints: self.hints, - hinted: self.run_hinted, - path, - user_attempts: u32::try_from(self.attempts.len()).unwrap_or(u32::MAX), - automatic_moves: u32::try_from(self.path.iter().filter(|mv| mv.automatic).count()) - .unwrap_or(u32::MAX), - scope: self.scope.key(), - }; - self.stats - .record_run(&self.repertoire_id, self.mode, record.clone()); - if self.mode == TrainingMode::Both && !self.actual_path.is_empty() { - self.stats.record_path_run( - PathKey { - repertoire_id: self.repertoire_id.clone(), - scope: self.scope.key(), - path: self.actual_path.clone(), - }, - record, - ); - } - } -} - -fn random_seed() -> u64 { - use std::hash::BuildHasher; - - std::collections::hash_map::RandomState::new().hash_one(0u8) -} diff --git a/crates/trainer/src/repertoire/stats.rs b/crates/trainer/src/repertoire/stats.rs index 737c691..68ca588 100644 --- a/crates/trainer/src/repertoire/stats.rs +++ b/crates/trainer/src/repertoire/stats.rs @@ -1,14 +1,11 @@ -use chess_core::shakmaty::{Color, Position}; +use chess_core::shakmaty::Color; use serde::{Deserialize, Serialize}; use super::model::RepertoireId; -use super::scope::{TrainingScope, TrainingScopeKey}; -use super::tree::{RepertoireTree, TrainingPath, TrainingTarget}; +use super::scope::TrainingScopeKey; pub const STATS_VERSION: u32 = 2; -pub const INITIAL_INTERVAL_SECONDS: i64 = 24 * 60 * 60; -pub const MISTAKE_INTERVAL_SECONDS: i64 = 10 * 60; -pub const MAX_INTERVAL_SECONDS: i64 = 365 * 24 * 60 * 60; +/// Recent attempts kept per move in a v2 file. const RECENT: usize = 10; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] @@ -36,15 +33,6 @@ pub enum QueueMode { LeastRecent, } -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum SrsPolicy { - Due, - Introduce, - EarlyReview, -} - -pub const INTRODUCTION_BATCH_SIZE: usize = 10; - #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] pub struct MoveKey { pub repertoire_id: RepertoireId, @@ -103,6 +91,7 @@ impl Default for MoveStats { } } +#[cfg(test)] impl MoveStats { pub fn new(key: MoveKey) -> Self { Self { @@ -110,88 +99,6 @@ impl MoveStats { ..Self::default() } } - - pub fn unseen(&self) -> bool { - self.attempts == 0 - } - - pub fn is_due(&self, now: i64) -> bool { - self.due.is_some_and(|due| due <= now) - } - - fn push_recent(&mut self, attempt: AttemptRecord) { - self.recent.push(attempt); - if self.recent.len() > RECENT { - self.recent.remove(0); - } - } - - fn wrong(&mut self, now: i64, actual_uci: &str, schedule: bool) { - self.attempts = self.attempts.saturating_add(1); - self.wrong = self.wrong.saturating_add(1); - self.streak = if self.streak < 0 { - self.streak.saturating_sub(1) - } else { - -1 - }; - self.last_attempt = Some(now); - self.last_seen = Some(now); - if schedule { - self.due = Some(now.saturating_add(MISTAKE_INTERVAL_SECONDS)); - self.interval_seconds = Some(MISTAKE_INTERVAL_SECONDS); - } - self.push_recent(AttemptRecord { - at: now, - correct: false, - hinted: false, - actual_uci: actual_uci.to_owned(), - }); - } - - fn correct(&mut self, now: i64, actual_uci: &str, hinted: bool, schedule: bool) { - let previous_interval = - self.interval_seconds - .unwrap_or_else(|| match (self.due, self.last_seen) { - (Some(due), Some(last)) if due > last => due.saturating_sub(last), - _ => INITIAL_INTERVAL_SECONDS, - }); - let clean_streak = self.streak; - let retry = hinted || clean_streak < 0; - self.attempts = self.attempts.saturating_add(1); - self.correct = self.correct.saturating_add(1); - self.streak = if retry { - 0 - } else { - clean_streak.saturating_add(1).max(1) - }; - if schedule { - let interval = if retry { - MISTAKE_INTERVAL_SECONDS - } else if clean_streak > 0 { - previous_interval - .saturating_mul(2) - .clamp(INITIAL_INTERVAL_SECONDS, MAX_INTERVAL_SECONDS) - } else { - INITIAL_INTERVAL_SECONDS - }; - self.due = Some(now.saturating_add(interval)); - self.interval_seconds = Some(interval); - } - self.last_attempt = Some(now); - self.last_seen = Some(now); - self.push_recent(AttemptRecord { - at: now, - correct: true, - hinted, - actual_uci: actual_uci.to_owned(), - }); - } - - fn hint(&mut self, now: i64) { - self.streak = 0; - self.hints = self.hints.saturating_add(1); - self.last_seen = Some(now); - } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -275,11 +182,6 @@ struct RandomPracticeCursor { fingerprint: Option, } -pub(crate) struct RandomPracticePath { - pub path: TrainingPath, - pub start: usize, -} - #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(default)] pub struct StatsData { @@ -314,616 +216,6 @@ impl Default for StatsData { } impl StatsData { - /// Removes modern statistics and queue positions for one repertoire. Legacy line - /// aggregates have independent identities and remain untouched. - pub fn remove_repertoire(&mut self, repertoire_id: &RepertoireId) { - self.move_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id); - self.runs - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.path_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id); - self.review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.path_review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.practice_path_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - self.random_practice_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - } - - pub fn remove_repertoire_mode(&mut self, repertoire_id: &RepertoireId, mode: TrainingMode) { - self.move_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id || entry.key.mode != mode); - self.runs - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - self.review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - self.practice_path_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - self.random_practice_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id || entry.mode != mode); - if mode == TrainingMode::Both { - self.path_stats - .retain(|entry| &entry.key.repertoire_id != repertoire_id); - self.path_review_cursors - .retain(|entry| &entry.repertoire_id != repertoire_id); - } - } - - pub fn get(&self, key: &MoveKey) -> Option<&MoveStats> { - self.move_stats.iter().find(|stats| &stats.key == key) - } - - pub fn runs(&self, repertoire_id: &RepertoireId, mode: TrainingMode) -> Option<&RunStats> { - self.runs - .iter() - .find(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode) - } - - /// Compatibility queue used by the existing desktop summary. SRS sessions use the - /// more specific `srs_queue` policies below and never automatically exhaust this list. - pub fn queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - now: i64, - ) -> Vec { - self.scoped_queue( - tree, - repertoire_id, - mode, - queue_mode, - now, - &TrainingScope::whole(), - ) - } - - pub fn scoped_queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - now: i64, - scope: &TrainingScope, - ) -> Vec { - let Some(color) = mode.user_color() else { - return Vec::new(); - }; - let targets = tree.scoped_targets(color, scope); - let key = |target: &TrainingTarget| MoveKey { - repertoire_id: repertoire_id.clone(), - mode, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - }; - let mut indexed: Vec<(usize, TrainingTarget)> = targets.into_iter().enumerate().collect(); - match queue_mode { - QueueMode::SpacedRepetition => { - let mut due = Vec::new(); - let mut unseen = Vec::new(); - let mut unscheduled = Vec::new(); - for (order, target) in indexed { - match self.get(&key(&target)) { - Some(stats) if stats.is_due(now) => due.push((stats.due, order, target)), - Some(stats) if stats.due.is_none() => { - unscheduled.push((order, target)); - } - Some(_) => {} - None => unseen.push((order, target)), - } - } - due.sort_by_key(|(due, order, _)| (*due, *order)); - due.into_iter() - .map(|(_, _, target)| target) - .chain(unseen.into_iter().map(|(_, target)| target)) - .chain(unscheduled.into_iter().map(|(_, target)| target)) - .collect() - } - QueueMode::LeastRecent => { - indexed.sort_by_key(|(order, target)| { - let stats = self.get(&key(target)); - ( - !stats.is_none_or(MoveStats::unseen), - stats.and_then(|stats| stats.last_seen).unwrap_or(i64::MIN), - *order, - ) - }); - indexed.into_iter().map(|(_, target)| target).collect() - } - QueueMode::Practice | QueueMode::ReviewInOrder => { - let scope_key = scope.key(); - let cursor = self - .review_cursors - .iter() - .find(|cursor| { - &cursor.repertoire_id == repertoire_id - && cursor.mode == mode - && cursor.scope == scope_key - }) - .map_or(0, |cursor| cursor.next); - if indexed.is_empty() { - return Vec::new(); - } - let offset = cursor % indexed.len(); - indexed.rotate_left(offset); - indexed.into_iter().map(|(_, target)| target).collect() - } - } - } - - pub fn srs_queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - now: i64, - scope: &TrainingScope, - policy: SrsPolicy, - ) -> Vec { - let Some(color) = mode.user_color() else { - return Vec::new(); - }; - let key = |target: &TrainingTarget| MoveKey { - repertoire_id: repertoire_id.clone(), - mode, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - }; - let mut due = Vec::new(); - let mut future = Vec::new(); - let mut unseen = Vec::new(); - let mut unscheduled = Vec::new(); - for (order, target) in tree.scoped_targets(color, scope).into_iter().enumerate() { - match self.get(&key(&target)) { - Some(stats) if stats.is_due(now) => due.push((stats.due, order, target)), - Some(stats) if stats.due.is_some() => future.push((stats.due, order, target)), - Some(stats) if stats.unseen() => unseen.push((order, target)), - Some(_) => unscheduled.push((order, target)), - None => unseen.push((order, target)), - } - } - due.sort_by_key(|(due, order, _)| (*due, *order)); - future.sort_by_key(|(due, order, _)| (*due, *order)); - match policy { - SrsPolicy::Due => due.into_iter().map(|(_, _, target)| target).collect(), - SrsPolicy::Introduce => unseen - .into_iter() - .chain(unscheduled) - .take(INTRODUCTION_BATCH_SIZE) - .map(|(_, target)| target) - .collect(), - SrsPolicy::EarlyReview => future.into_iter().map(|(_, _, target)| target).collect(), - } - } - - pub fn path_stats(&self, key: &PathKey) -> Option<&PathStats> { - self.path_stats.iter().find(|stats| &stats.key == key) - } - - pub fn path_queue( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - scope: &TrainingScope, - queue_mode: QueueMode, - ) -> Result, String> { - let scope_key = scope.key(); - let mut paths = tree.training_paths(scope)?; - if queue_mode == QueueMode::LeastRecent { - paths.sort_by_key(|path| { - let key = PathKey { - repertoire_id: repertoire_id.clone(), - scope: scope_key.clone(), - path: path.moves.clone(), - }; - let stats = self.path_stats(&key); - ( - stats.is_some_and(|stats| stats.completions > 0), - stats - .and_then(|stats| stats.last_completion) - .unwrap_or(i64::MIN), - ) - }); - return Ok(paths); - } - if paths.is_empty() { - return Ok(paths); - } - let cursor = self - .path_review_cursors - .iter() - .find(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope_key) - .map_or(0, |cursor| cursor.next); - let offset = cursor % paths.len(); - paths.rotate_left(offset); - Ok(paths) - } - - pub(crate) fn next_practice_path( - &mut self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - scope: &TrainingScope, - ) -> Result, String> { - use std::ops::ControlFlow; - let scope_key = scope.key(); - let index = match self.practice_path_cursors.iter().position(|c| { - &c.repertoire_id == repertoire_id && c.mode == mode && c.scope == scope_key - }) { - Some(index) => index, - None => { - self.practice_path_cursors.push(ReviewCursor { - repertoire_id: repertoire_id.clone(), - mode, - scope: scope_key, - next: 0, - }); - self.practice_path_cursors.len() - 1 - } - }; - let cursor = self.practice_path_cursors[index].next; - let mut count = 0usize; - let mut chosen = None; - tree.visit_training_paths(scope, |moves| { - if count == cursor { - chosen = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - count += 1; - ControlFlow::Continue(()) - })?; - if chosen.is_none() && count > 0 { - let offset = cursor % count; - let mut order = 0; - tree.visit_training_paths(scope, |moves| { - if order == offset { - chosen = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - order += 1; - ControlFlow::Continue(()) - })?; - self.practice_path_cursors[index].next = offset; - } - if chosen.is_some() { - self.practice_path_cursors[index].next = - self.practice_path_cursors[index].next.saturating_add(1); - } - Ok(chosen) - } - - pub(crate) fn next_random_practice_path( - &mut self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - mode: TrainingMode, - scope: &TrainingScope, - repertoire_fingerprint: u64, - initial_seed: u64, - ) -> Result, String> { - use std::ops::ControlFlow; - - let anchor = tree.scope_anchor(scope)?; - let start_turn = tree - .position(anchor) - .map(|position| position.turn()) - .ok_or_else(|| "scope start position is missing".to_owned())?; - let mut count = Some(0usize); - tree.visit_source_paths(scope, |moves| { - if eligible_target_count(mode, start_turn, moves.len()) == 0 { - return ControlFlow::Continue(()); - } - count = count.and_then(|count| count.checked_add(1)); - if count.is_none() { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - })?; - let count = - count.ok_or_else(|| "training path count exceeds the platform limit".to_owned())?; - let scope_key = scope.key(); - let existing = self.random_practice_cursors.iter().position(|cursor| { - &cursor.repertoire_id == repertoire_id - && cursor.mode == mode - && cursor.scope == scope_key - }); - let is_new = existing.is_none(); - let index = existing.unwrap_or_else(|| { - self.random_practice_cursors.push(RandomPracticeCursor { - repertoire_id: repertoire_id.clone(), - mode, - scope: scope_key, - seed: initial_seed, - position: 0, - count: 0, - fingerprint: Some(repertoire_fingerprint), - }); - self.random_practice_cursors.len() - 1 - }); - let cursor = &mut self.random_practice_cursors[index]; - if !is_new - && (cursor.fingerprint != Some(repertoire_fingerprint) - || cursor.count != count - || cursor.position >= count) - { - cursor.seed = next_cycle_seed(cursor.seed); - cursor.position = 0; - } - cursor.fingerprint = Some(repertoire_fingerprint); - cursor.count = count; - if count == 0 { - cursor.position = 0; - return Ok(None); - } - if cursor.position >= count { - cursor.position = 0; - } - - let position = cursor.position; - let seed = cursor.seed; - let step = coprime_step(seed ^ 0xa076_1d64_78bd_642f, count); - let offset = (mix64(seed ^ 0xe703_7ed1_a0b4_28db) as u128 % count as u128) as usize; - let selected_index = - ((step as u128 * position as u128 + offset as u128) % count as u128) as usize; - let start_seed = mix64(seed ^ (position as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15)); - let mut order = 0usize; - let mut chosen = None; - tree.visit_source_paths(scope, |moves| { - let eligible = eligible_target_count(mode, start_turn, moves.len()); - if eligible == 0 { - return ControlFlow::Continue(()); - } - if order == selected_index { - let start_order = (start_seed as usize) % eligible; - chosen = eligible_target_index(mode, start_turn, moves.len(), start_order).map( - |start| RandomPracticePath { - path: TrainingPath { - moves: moves.to_vec(), - }, - start, - }, - ); - return ControlFlow::Break(()); - } - order += 1; - ControlFlow::Continue(()) - })?; - if chosen.is_some() { - cursor.position = cursor.position.saturating_add(1); - Ok(chosen) - } else { - Err("random training path selection is inconsistent".to_owned()) - } - } - - /// Selects one route without materializing the complete path queue. Ordered - /// review stops as soon as its cursor is reached; only wrapping needs a second pass. - pub fn next_training_path( - &self, - tree: &RepertoireTree, - repertoire_id: &RepertoireId, - scope: &TrainingScope, - queue_mode: QueueMode, - ) -> Result, String> { - use std::ops::ControlFlow; - let scope_key = scope.key(); - if queue_mode == QueueMode::LeastRecent { - let mut best = None; - let mut best_rank = None; - tree.visit_training_paths(scope, |moves| { - let stats = self.path_stats.iter().find(|stats| { - &stats.key.repertoire_id == repertoire_id - && stats.key.scope == scope_key - && stats.key.path == moves - }); - let rank = ( - stats.is_some_and(|stats| stats.completions > 0), - stats - .and_then(|stats| stats.last_completion) - .unwrap_or(i64::MIN), - ); - if best_rank.is_none_or(|old| rank < old) { - best_rank = Some(rank); - best = Some(TrainingPath { - moves: moves.to_vec(), - }); - } - // This is the minimum possible rank. Keeping its first occurrence - // preserves the stable PGN order used by path_queue's sort. - if rank == (false, i64::MIN) { - ControlFlow::Break(()) - } else { - ControlFlow::Continue(()) - } - })?; - return Ok(best); - } - let cursor = self - .path_review_cursors - .iter() - .find(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope_key) - .map_or(0, |cursor| cursor.next); - let mut count = 0usize; - let mut selected = None; - tree.visit_training_paths(scope, |moves| { - if count == cursor { - selected = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - count += 1; - ControlFlow::Continue(()) - })?; - if selected.is_some() || count == 0 { - return Ok(selected); - } - let offset = cursor % count; - let mut index = 0; - tree.visit_training_paths(scope, |moves| { - if index == offset { - selected = Some(TrainingPath { - moves: moves.to_vec(), - }); - return ControlFlow::Break(()); - } - index += 1; - ControlFlow::Continue(()) - })?; - Ok(selected) - } - - pub(crate) fn record_wrong( - &mut self, - key: MoveKey, - now: i64, - actual_uci: &str, - schedule: bool, - ) { - self.entry(key).wrong(now, actual_uci, schedule); - } - - pub(crate) fn record_correct( - &mut self, - key: MoveKey, - now: i64, - actual_uci: &str, - hinted: bool, - schedule: bool, - ) { - self.entry(key).correct(now, actual_uci, hinted, schedule); - } - - pub(crate) fn record_hint(&mut self, key: MoveKey, now: i64) { - self.entry(key).hint(now); - } - - pub(crate) fn target_completed( - &mut self, - repertoire_id: &RepertoireId, - mode: TrainingMode, - queue_mode: QueueMode, - scope: &TrainingScope, - ) { - if queue_mode != QueueMode::ReviewInOrder { - return; - } - let scope = scope.key(); - let index = match self.review_cursors.iter().position(|cursor| { - &cursor.repertoire_id == repertoire_id && cursor.mode == mode && cursor.scope == scope - }) { - Some(index) => index, - None => { - self.review_cursors.push(ReviewCursor { - repertoire_id: repertoire_id.clone(), - mode, - scope, - next: 0, - }); - self.review_cursors.len() - 1 - } - }; - self.review_cursors[index].next = self.review_cursors[index].next.saturating_add(1); - } - - pub(crate) fn path_presented( - &mut self, - repertoire_id: &RepertoireId, - scope: &TrainingScope, - queue_mode: QueueMode, - ) { - if queue_mode == QueueMode::LeastRecent { - return; - } - let scope = scope.key(); - let index = match self - .path_review_cursors - .iter() - .position(|cursor| &cursor.repertoire_id == repertoire_id && cursor.scope == scope) - { - Some(index) => index, - None => { - self.path_review_cursors.push(PathReviewCursor { - repertoire_id: repertoire_id.clone(), - scope, - next: 0, - }); - self.path_review_cursors.len() - 1 - } - }; - self.path_review_cursors[index].next = - self.path_review_cursors[index].next.saturating_add(1); - } - - pub(crate) fn record_run( - &mut self, - repertoire_id: &RepertoireId, - mode: TrainingMode, - record: RunRecord, - ) { - let index = match self - .runs - .iter() - .position(|runs| &runs.repertoire_id == repertoire_id && runs.mode == mode) - { - Some(index) => index, - None => { - self.runs.push(RunStats { - repertoire_id: repertoire_id.clone(), - mode, - ..RunStats::default() - }); - self.runs.len() - 1 - } - }; - let runs = &mut self.runs[index]; - runs.completions = runs.completions.saturating_add(1); - runs.last = Some(record.at); - runs.recent.push(record); - if runs.recent.len() > RECENT { - runs.recent.remove(0); - } - } - - pub(crate) fn record_path_run(&mut self, key: PathKey, record: RunRecord) { - let index = match self.path_stats.iter().position(|stats| stats.key == key) { - Some(index) => index, - None => { - self.path_stats.push(PathStats { - key, - completions: 0, - mistakes: 0, - hints: 0, - last_seen: None, - last_completion: None, - recent: Vec::new(), - }); - self.path_stats.len() - 1 - } - }; - let stats = &mut self.path_stats[index]; - stats.completions = stats.completions.saturating_add(1); - stats.mistakes = stats.mistakes.saturating_add(record.mistakes); - stats.hints = stats.hints.saturating_add(record.hints); - stats.last_seen = Some(record.at); - stats.last_completion = Some(record.at); - stats.recent.push(record); - if stats.recent.len() > RECENT { - stats.recent.remove(0); - } - } - pub(crate) fn migrate_position_stats(&mut self) { let mut merged: Vec = Vec::new(); for mut entry in self.move_stats.drain(..) { @@ -980,91 +272,4 @@ impl StatsData { self.path_review_cursors .sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope))); } - - fn entry(&mut self, key: MoveKey) -> &mut MoveStats { - let index = match self.move_stats.iter().position(|stats| stats.key == key) { - Some(index) => index, - None => { - self.move_stats.push(MoveStats::new(key)); - self.move_stats.len() - 1 - } - }; - &mut self.move_stats[index] - } -} - -pub(crate) const MIN_RANDOM_CONTINUATION_PLIES: usize = 7; - -fn random_max_start(plies: usize) -> usize { - plies.saturating_sub(MIN_RANDOM_CONTINUATION_PLIES) -} - -fn eligible_target_count(mode: TrainingMode, start_turn: Color, plies: usize) -> usize { - if plies == 0 { - return 0; - } - let max_start = random_max_start(plies); - let Some(user_color) = mode.user_color() else { - return usize::from(plies > 0) * (max_start + 1); - }; - let first = usize::from(start_turn != user_color); - if max_start < first { - 0 - } else { - (max_start - first) / 2 + 1 - } -} - -fn eligible_target_index( - mode: TrainingMode, - start_turn: Color, - plies: usize, - order: usize, -) -> Option { - let mut remaining = order; - for index in 0..=random_max_start(plies) { - let turn = if index % 2 == 0 { - start_turn - } else { - start_turn.other() - }; - if mode.user_color().is_none_or(|color| color == turn) { - if remaining == 0 { - return Some(index); - } - remaining -= 1; - } - } - None -} - -fn coprime_step(seed: u64, count: usize) -> usize { - if count == 1 { - return 0; - } - let mut step = (mix64(seed) % count as u64) as usize; - while gcd(step, count) != 1 { - step = (step + 1) % count; - } - step -} - -fn gcd(mut left: usize, mut right: usize) -> usize { - while right != 0 { - let remainder = left % right; - left = right; - right = remainder; - } - left -} - -fn next_cycle_seed(seed: u64) -> u64 { - mix64(seed ^ 0x8ebc_6af0_9c88_c6e3) -} - -fn mix64(mut value: u64) -> u64 { - value = value.wrapping_add(0x9e37_79b9_7f4a_7c15); - value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); - value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); - value ^ (value >> 31) } diff --git a/crates/trainer/src/repertoire/tests.rs b/crates/trainer/src/repertoire/tests.rs index f64c7c2..2e2516e 100644 --- a/crates/trainer/src/repertoire/tests.rs +++ b/crates/trainer/src/repertoire/tests.rs @@ -13,12 +13,6 @@ fn game(pgn: &str) -> Game { chess_core::parse_str(pgn).game } -fn repertoire(pgn: &str) -> Repertoire { - let mut library = Library::default(); - let id = library.create("Test", &game(pgn)).unwrap(); - library.repertoire(&id).unwrap().clone() -} - fn play(game: &Game, line: &[&str]) -> Vec { let mut position = game.start().position().clone(); line.iter() @@ -258,348 +252,6 @@ fn library_crud_depth_and_disable_are_persistent_data() { assert!(library.repertoire(&id).is_none()); } -#[test] -fn both_accepts_every_enabled_branch_and_rejects_outside_disabled_and_depth() { - let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - assert!(session.play_uci("not-a-move", 0).is_err()); - assert!(session.play_uci("e2e5", 0).is_err()); - assert!(session.attempts().is_empty()); - assert_eq!(session.play_uci("c2c4", 1).unwrap(), TrainingVerdict::Wrong); - assert_eq!(session.current_node(), NodeId::ROOT); - assert_eq!(session.total_mistakes(), 1); - assert_eq!(session.play_uci("d2d4", 2).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("d7d5", 3).unwrap(), - TrainingVerdict::Finished - ); - let completions = session - .stats() - .runs(&rep.id, TrainingMode::Both) - .unwrap() - .completions; - assert_eq!(completions, 1); - assert_eq!(session.play_uci("d2d4", 4).unwrap(), TrainingVerdict::Done); - assert_eq!( - session - .stats() - .runs(&rep.id, TrainingMode::Both) - .unwrap() - .completions, - 1 - ); - - session.restart(10).unwrap(); - assert_eq!( - session.play_uci("e2e4", 10).unwrap(), - TrainingVerdict::Right - ); - assert_eq!( - session.play_uci("c7c5", 11).unwrap(), - TrainingVerdict::Finished - ); - - let mut disabled = rep.clone(); - disabled - .set_prefix_disabled(&["e2e4".into(), "e7e5".into()], true) - .unwrap(); - let mut session = TrainingSession::new( - &disabled, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 20, - ) - .unwrap(); - session.play_uci("e2e4", 20).unwrap(); - assert_eq!( - session.play_uci("e7e5", 21).unwrap(), - TrainingVerdict::Wrong - ); - assert_eq!( - session.play_uci("c7c5", 22).unwrap(), - TrainingVerdict::Finished - ); - - let mut shallow = rep.clone(); - shallow.set_max_plies(1); - let mut session = TrainingSession::new( - &shallow, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 30, - ) - .unwrap(); - assert_eq!( - session.play_uci("e2e4", 30).unwrap(), - TrainingVerdict::Finished - ); -} - -#[test] -fn both_hint_after_three_errors_and_completion_are_recorded_once() { - let rep = repertoire("1. e4 e5 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::SpacedRepetition, - StatsData::default(), - 0, - ) - .unwrap(); - for now in 1..=3 { - assert_eq!( - session.play_uci("d2d4", now).unwrap(), - TrainingVerdict::Wrong - ); - assert_eq!(session.current_node(), NodeId::ROOT); - } - assert!(session.may_hint()); - assert_eq!(session.hint(4).unwrap().uci, "e2e4"); - assert!(session.hinted()); - assert_eq!(session.play_uci("e2e4", 5).unwrap(), TrainingVerdict::Right); - assert_eq!( - session.play_uci("e7e5", 6).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(session.play_uci("e7e5", 7).unwrap(), TrainingVerdict::Done); - let stats = &session.stats().move_stats; - let e4 = stats - .iter() - .find(|entry| entry.key.position_fen4 == fen4(Game::new().start().position())) - .unwrap(); - assert_eq!((e4.attempts, e4.correct, e4.wrong, e4.hints), (4, 1, 3, 1)); - assert_eq!(e4.streak, 0); - assert_eq!(e4.recent.len(), 4); - assert_eq!(e4.recent[0].actual_uci, "d2d4"); - let runs = session.stats().runs(&rep.id, TrainingMode::Both).unwrap(); - assert_eq!(runs.completions, 1); - assert_eq!(runs.recent[0].mistakes, 3); - assert!(runs.recent[0].hinted); - assert_eq!(session.errors().count(), 3); -} - -#[test] -fn both_continues_through_a_canonical_transposition_and_shares_stats() { - let mut library = Library::default(); - let id = library.create_empty("Transpositions").unwrap(); - library - .add_game(&id, &game("1. d4 d5 2. Nf3 Nf6 3. g3 *")) - .unwrap(); - library - .add_game(&id, &game("1. Nf3 d5 2. d4 Nf6 *")) - .unwrap(); - let rep = library.repertoire(&id).unwrap().clone(); - let mut first = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (now, mv) in ["d2d4", "d7d5", "g1f3", "g8f6", "g2g3"] - .into_iter() - .enumerate() - { - first.play_uci(mv, now as i64).unwrap(); - } - let mut second = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - first.into_stats(), - 10, - ) - .unwrap(); - second.play_uci("g1f3", 10).unwrap(); - second.play_uci("d7d5", 11).unwrap(); - second.play_uci("d2d4", 12).unwrap(); - second.play_uci("g8f6", 13).unwrap(); - assert!(second.candidates().iter().any(|c| c.uci == "g2g3")); - assert_eq!( - second.play_uci("g2g3", 14).unwrap(), - TrainingVerdict::Finished - ); - let shared = second - .stats() - .move_stats - .iter() - .filter(|entry| { - entry - .recent - .iter() - .any(|attempt| attempt.actual_uci == "g2g3") - }) - .collect::>(); - assert_eq!(shared.len(), 1); - assert_eq!(shared[0].attempts, 2); - assert_eq!(shared[0].correct, 2); -} - -struct SecondChooser; - -impl MoveChooser for SecondChooser { - fn choose(&mut self, candidates: &[Candidate]) -> Option { - (candidates.len() > 1).then_some(1).or(Some(0)) - } -} - -#[test] -fn one_side_alternative_and_injectable_chooser_do_not_count_auto_moves() { - let rep = repertoire("1. e4 (1. d4 d5) e5 (1... c5) 2. Nf3 *"); - let mut session = TrainingSession::with_chooser( - &rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - Box::new(SecondChooser), - ) - .unwrap(); - assert_eq!(session.target().unwrap().expected_uci, "e2e4"); - assert_eq!(session.play_uci("e2e4", 2).unwrap(), TrainingVerdict::Right); - assert_eq!(session.path()[0].uci, "e2e4"); - assert!(!session.path()[0].automatic); - assert_eq!(session.path()[1].uci, "c7c5"); - assert!(session.path()[1].automatic); - assert_eq!(session.attempts().len(), 1); - assert_eq!(session.stats().move_stats.len(), 1); - - let black = repertoire("1. e4 e5 2. Nf3 *"); - let mut black_session = TrainingSession::new( - &black, - TrainingMode::Black, - QueueMode::ReviewInOrder, - StatsData::default(), - 10, - ) - .unwrap(); - assert_eq!(black_session.target().unwrap().expected_uci, "e7e5"); - assert_eq!(black_session.path()[0].uci, "e2e4"); - assert!(black_session.path()[0].automatic); - assert_eq!( - black_session.play_uci("e7e5", 11).unwrap(), - TrainingVerdict::Finished - ); - assert_eq!(black_session.attempts().len(), 1); - assert!( - black_session - .path() - .iter() - .any(|mv| mv.uci == "g1f3" && mv.automatic) - ); -} - -#[test] -fn srs_dates_unseen_review_order_and_least_recent_work() { - let rep = repertoire("1. e4 *"); - let mut first = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - assert_eq!( - first.play_uci("e2e4", 1_000).unwrap(), - TrainingVerdict::Finished - ); - let stats = &first.stats().move_stats[0]; - assert_eq!(stats.due, Some(1_000 + INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 1); - - let second_now = 1_000 + INITIAL_INTERVAL_SECONDS; - let mut second = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::SpacedRepetition, - first.into_stats(), - second_now, - ) - .unwrap(); - assert_eq!( - second.play_uci("e2e4", second_now).unwrap(), - TrainingVerdict::Finished - ); - let stats = &second.stats().move_stats[0]; - assert_eq!(stats.due, Some(1_000 + 3 * INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 2); - assert!( - second - .stats() - .queue( - &RepertoireTree::new(&rep), - &rep.id, - TrainingMode::White, - QueueMode::SpacedRepetition, - 3_000, - ) - .is_empty() - ); - - let wrong_rep = repertoire("1. e4 *"); - let mut wrong = TrainingSession::new_srs( - &wrong_rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - wrong.play_uci("d2d4", 100).unwrap(); - let key = wrong - .target() - .map(|target| MoveKey { - repertoire_id: wrong_rep.id.clone(), - mode: TrainingMode::White, - position_fen4: target.position_fen4.clone(), - expected_uci: target.expected_uci.clone(), - }) - .unwrap(); - assert_eq!(wrong.stats().get(&key).unwrap().due, Some(700)); - wrong.play_uci("e2e4", 101).unwrap(); - assert_eq!(wrong.stats().get(&key).unwrap().due, Some(701)); - assert_eq!(wrong.stats().get(&key).unwrap().streak, 0); - - let branches = repertoire("1. e4 (1. d4 d5) e5 2. Nf3 *"); - let mut training = TrainingSession::new( - &branches, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - training.play_uci("e2e4", 10).unwrap(); - let queue = training.stats().queue( - &RepertoireTree::new(&branches), - &branches.id, - TrainingMode::White, - QueueMode::LeastRecent, - 20, - ); - assert_eq!(queue[0].expected_uci, "d2d4"); - assert_eq!(queue.last().unwrap().expected_uci, "e2e4"); - let review = training.stats().queue( - &RepertoireTree::new(&branches), - &branches.id, - TrainingMode::White, - QueueMode::ReviewInOrder, - 20, - ); - assert_eq!(review[0].expected_uci, "d2d4"); -} - #[test] fn prefix_ignores_unparsed_tail_after_the_selected_node() { let source = game("1. e4 e4 2. d4 *"); @@ -617,146 +269,6 @@ fn prefix_ignores_unparsed_tail_after_the_selected_node() { assert_eq!(library.repertoire(&id).unwrap().pgn, before); } -#[test] -fn review_queues_record_attempts_without_changing_srs_due() { - let rep = repertoire("1. e4 *"); - let mut srs = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - srs.play_uci("e2e4", 100).unwrap(); - let original_due = srs.stats().move_stats[0].due; - assert_eq!(original_due, Some(100 + INITIAL_INTERVAL_SECONDS)); - - for queue_mode in [QueueMode::ReviewInOrder, QueueMode::LeastRecent] { - let mut review = TrainingSession::new( - &rep, - TrainingMode::White, - queue_mode, - srs.stats().clone(), - 0, - ) - .unwrap(); - review.play_uci("e2e4", 200).unwrap(); - let stats = &review.stats().move_stats[0]; - assert_eq!(stats.attempts, 2); - assert_eq!(stats.last_seen, Some(200)); - assert_eq!(stats.due, original_due); - - review.restart(201).unwrap(); - review.play_uci("d2d4", 201).unwrap(); - assert_eq!(review.stats().move_stats[0].due, original_due); - } -} - -#[test] -fn srs_retry_is_kept_until_the_next_clean_success() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new_srs( - &rep, - TrainingMode::White, - StatsData::default(), - 0, - SrsPolicy::Introduce, - ) - .unwrap(); - session.play_uci("d2d4", 100).unwrap(); - session.play_uci("e2e4", 101).unwrap(); - let stats = &session.stats().move_stats[0]; - assert_eq!(stats.due, Some(101 + MISTAKE_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 0); - - session.restart_with_policy(701, SrsPolicy::Due).unwrap(); - session.play_uci("e2e4", 701).unwrap(); - let stats = &session.stats().move_stats[0]; - assert_eq!(stats.due, Some(701 + INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 1); - - session.restart(701 + INITIAL_INTERVAL_SECONDS).unwrap(); - session - .play_uci("e2e4", 701 + INITIAL_INTERVAL_SECONDS) - .unwrap(); - let stats = &session.stats().move_stats[0]; - assert_eq!(stats.due, Some(701 + 3 * INITIAL_INTERVAL_SECONDS)); - assert_eq!(stats.streak, 2); -} - -#[test] -fn both_attempts_never_create_srs_due() { - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - session.play_uci("d2d4", 100).unwrap(); - session.play_uci("e2e4", 101).unwrap(); - assert!( - session - .stats() - .move_stats - .iter() - .all(|stats| stats.due.is_none()) - ); -} - -#[test] -fn stats_are_isolated_by_mode_and_repertoire() { - let first_rep = repertoire("1. e4 *"); - let second_rep = repertoire("1. e4 *"); - let mut white = TrainingSession::new( - &first_rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - white.play_uci("e2e4", 1).unwrap(); - let mut both = TrainingSession::new( - &first_rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - white.into_stats(), - 2, - ) - .unwrap(); - both.play_uci("e2e4", 2).unwrap(); - let mut other = TrainingSession::new( - &second_rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - both.into_stats(), - 3, - ) - .unwrap(); - other.play_uci("e2e4", 3).unwrap(); - assert_eq!(other.stats().move_stats.len(), 3); - assert!( - other - .stats() - .move_stats - .iter() - .any(|entry| entry.key.mode == TrainingMode::White) - ); - assert_eq!( - other - .stats() - .move_stats - .iter() - .filter(|entry| entry.key.mode == TrainingMode::Both) - .count(), - 2 - ); -} - #[test] fn library_store_roundtrip_errors_and_conflicts_are_visible() { let dir = temp_dir("library-store"); @@ -866,39 +378,7 @@ fn stats_store_write_failure_does_not_replace_legacy_or_report_success() { } #[test] -fn session_stats_can_be_saved_after_every_run() { - let dir = temp_dir("session-save"); - let store = StatsStore::new(dir.join("stats.json")); - let rep = repertoire("1. e4 *"); - let mut session = TrainingSession::new( - &rep, - TrainingMode::White, - QueueMode::ReviewInOrder, - store.load().unwrap(), - 0, - ) - .unwrap(); - session.play_uci("e2e4", 10).unwrap(); - store.save(session.stats_mut()).unwrap(); - assert_eq!(session.stats().revision, 1); - session.restart(20).unwrap(); - session.play_uci("e2e4", 20).unwrap(); - store.save(session.stats_mut()).unwrap(); - assert_eq!(session.stats().revision, 2); - assert_eq!( - store - .load() - .unwrap() - .runs(&rep.id, TrainingMode::White) - .unwrap() - .completions, - 2 - ); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn adding_training_and_deleting_never_touches_the_source_file() { +fn adding_and_deleting_never_touches_the_source_file() { let dir = temp_dir("source-file"); let source_path = dir.join("legacy.pgn"); let bytes = b"[Event \"Legacy\"]\n\n1. e4 c5 2. Nf3 d6 *\n\xff"; @@ -908,19 +388,21 @@ fn adding_training_and_deleting_never_touches_the_source_file() { let id = library.create_empty("Snapshot").unwrap(); let at = source.mainline()[3]; library.add_prefix(&id, &source, at).unwrap(); - let rep = library.repertoire(&id).unwrap().clone(); - let mut session = TrainingSession::new( - &rep, - TrainingMode::Both, - QueueMode::ReviewInOrder, - StatsData::default(), - 0, - ) - .unwrap(); - for (now, mv) in ["e2e4", "c7c5", "g1f3", "d7d6"].into_iter().enumerate() { - session.play_uci(mv, now as i64).unwrap(); - } library.delete(&id).unwrap(); assert_eq!(std::fs::read(&source_path).unwrap(), bytes); let _ = std::fs::remove_dir_all(dir); } + +#[test] +fn v2_stats_without_the_random_cursor_field_still_read_and_save() { + let mut old = serde_json::to_value(StatsData::default()).unwrap(); + assert!( + old.as_object_mut() + .unwrap() + .remove("random_practice_cursors") + .is_some() + ); + let stats: StatsData = serde_json::from_value(old).unwrap(); + let saved = serde_json::to_value(&stats).unwrap(); + assert!(saved["random_practice_cursors"].is_array()); +} diff --git a/crates/trainer/src/repertoire/tree.rs b/crates/trainer/src/repertoire/tree.rs index 70d25a0..ffeab12 100644 --- a/crates/trainer/src/repertoire/tree.rs +++ b/crates/trainer/src/repertoire/tree.rs @@ -1,7 +1,7 @@ use std::collections::{BTreeMap, BTreeSet}; use chess_core::shakmaty::fen::Fen; -use chess_core::shakmaty::{CastlingMode, Chess, Color, EnPassantMode, Move, Position}; +use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; use chess_core::{Game, MoveKind, NodeId}; use super::model::Repertoire; @@ -20,25 +20,7 @@ pub fn fen4(position: &Chess) -> String { #[derive(Clone, Debug)] pub struct Candidate { - pub mv: Move, pub uci: String, - pub san: String, - /// The selected PGN path. Other paths to the same move remain in the tree. - pub node: NodeId, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct TrainingTarget { - pub position_fen4: String, - pub expected_uci: String, - /// One deterministic PGN path used to reach the target as context. - pub path: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -pub struct TrainingPath { - /// Actual moves from the beginning of the scope through its boundary, inclusive. - pub moves: Vec, } #[derive(Clone, Debug)] @@ -88,10 +70,6 @@ impl RepertoireTree { } } - pub(crate) fn max_plies(&self) -> u32 { - self.max_plies - } - pub fn game(&self) -> &Game { &self.game } @@ -137,21 +115,6 @@ impl RepertoireTree { self.candidates_impl(at, None) } - pub fn scoped_candidates(&self, at: NodeId, scope: &TrainingScope) -> Vec { - self.candidates_impl(at, Some(scope)) - } - - pub fn scoped_candidate( - &self, - at: NodeId, - uci: &str, - scope: &TrainingScope, - ) -> Option { - self.scoped_candidates(at, scope) - .into_iter() - .find(|candidate| candidate.uci == uci) - } - fn candidates_impl(&self, at: NodeId, scope: Option<&TrainingScope>) -> Vec { if !self.is_trainable_path(at) || self @@ -193,12 +156,7 @@ impl RepertoireTree { } let uci = mv.to_uci(CastlingMode::Standard).to_string(); if seen.insert(uci.clone()) { - out.push(Candidate { - mv, - uci, - san: game_move.san.clone(), - node: *child, - }); + out.push(Candidate { uci }); } } } @@ -211,48 +169,6 @@ impl RepertoireTree { .find(|candidate| candidate.uci == uci) } - /// All one-side targets in deterministic PGN order, deduplicated by FEN4/UCI. - pub fn targets(&self, side: Color) -> Vec { - self.targets_impl(side, None) - } - - pub fn scoped_targets(&self, side: Color, scope: &TrainingScope) -> Vec { - self.targets_impl(side, Some(scope)) - } - - fn targets_impl(&self, side: Color, scope: Option<&TrainingScope>) -> Vec { - let mut seen = BTreeSet::new(); - let mut out = Vec::new(); - for node in self.game.attached_nodes() { - if !self.scope_allows_parent(node, scope) { - continue; - } - if self.game.position(node).is_none_or(|p| p.turn() != side) { - continue; - } - let Some(path) = self.path(node).map(<[String]>::to_vec) else { - continue; - }; - let Some(position_fen4) = self.position_key(node).map(str::to_owned) else { - continue; - }; - let candidates = match scope { - Some(scope) => self.scoped_candidates(node, scope), - None => self.candidates(node), - }; - for candidate in candidates { - if seen.insert((position_fen4.clone(), candidate.uci.clone())) { - out.push(TrainingTarget { - position_fen4: position_fen4.clone(), - expected_uci: candidate.uci, - path: path.clone(), - }); - } - } - } - out - } - /// Follows a normal UCI path on the actual PGN tree. No transposition jump is made /// while replaying context, so the selected target path remains exact. pub fn node_at_path(&self, path: &[String]) -> Option { @@ -295,35 +211,6 @@ impl RepertoireTree { Ok(anchor) } - /// Generates actual scope-to-boundary routes in PGN depth-first order. Repeated FEN4 - /// positions are included as the final move and never expanded again. - pub fn training_paths(&self, scope: &TrainingScope) -> Result, String> { - let mut paths = Vec::new(); - self.visit_training_paths(scope, |moves| { - paths.push(TrainingPath { - moves: moves.to_vec(), - }); - std::ops::ControlFlow::Continue(()) - })?; - Ok(paths) - } - - /// Streams routes in the same order as `training_paths`, retaining only the active - /// route and its position history. A visitor may stop without expanding the rest. - pub fn visit_training_paths( - &self, - scope: &TrainingScope, - mut visit: impl FnMut(&[String]) -> std::ops::ControlFlow<()>, - ) -> Result<(), String> { - let anchor = self.scope_anchor(scope)?; - let mut positions = BTreeSet::new(); - if let Some(key) = self.position_key(anchor) { - positions.insert(key.to_owned()); - } - let _ = self.visit_paths(anchor, scope, &mut Vec::new(), &mut positions, &mut visit); - Ok(()) - } - /// Streams the routes explicitly present in PGN, without importing continuations /// from other paths that reach the same position. pub fn visit_source_paths( @@ -370,63 +257,6 @@ impl RepertoireTree { } } - pub fn training_path_count(&self, scope: &TrainingScope) -> Result { - let mut count = Some(0usize); - self.visit_training_paths(scope, |_| { - count = count.and_then(|count| count.checked_add(1)); - if count.is_none() { - std::ops::ControlFlow::Break(()) - } else { - std::ops::ControlFlow::Continue(()) - } - })?; - count.ok_or_else(|| "training path count exceeds the platform limit".to_owned()) - } - - fn visit_paths( - &self, - at: NodeId, - scope: &TrainingScope, - current: &mut Vec, - positions: &mut BTreeSet, - visit: &mut impl FnMut(&[String]) -> std::ops::ControlFlow<()>, - ) -> std::ops::ControlFlow<()> { - let candidates = if scope.parent_prefix().len() + current.len() >= self.max_plies as usize { - Vec::new() - } else { - self.scoped_candidates(at, scope) - }; - if candidates.is_empty() { - return if current.is_empty() { - std::ops::ControlFlow::Continue(()) - } else { - visit(current) - }; - } - // Each position has distinct UCI candidates, so each complete UCI route is - // unique even when its continuation crosses a transposition. - for candidate in candidates { - current.push(candidate.uci.clone()); - let key = self.position_key(candidate.node); - let repeated = key.is_some_and(|key| positions.contains(key)); - let result = if repeated { - visit(current) - } else { - if let Some(key) = key { - positions.insert(key.to_owned()); - } - let result = self.visit_paths(candidate.node, scope, current, positions, visit); - if let Some(key) = key { - positions.remove(key); - } - result - }; - current.pop(); - result?; - } - std::ops::ControlFlow::Continue(()) - } - fn scope_allows_parent(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool { let Some(scope) = scope else { return true; From 5034527865ce69b93c3c6f951ad35ecfcb459d24 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 08:50:13 +0300 Subject: [PATCH 28/31] =?UTF-8?q?docs:=20task=2040=20=E2=80=94=20core=20cl?= =?UTF-8?q?eanup=20done?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/dev/tasks.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index e5e87d5..de4da45 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -287,7 +287,8 @@ - **Проверено:** fmt, clippy `-D warnings`; trainer 200 passed, desktop 161 passed / 3 ignored (перепроверено оркестратором); mobile-api check. Дизайн-ревью `docs/qa/opening-trainer-v2-design-review.md`: скачков нет (0 px в серии состояний), шапка и доска совпадают с экраном партии после исправлений. - **Не проверено:** wasm (на ноутбуке нет цели `wasm32-unknown-unknown`), английский интерфейс, клавиатура, масштаб 1, длинные имена/большой список, 960×600 для экранов занятия; клавиатурное подтверждение удаления, клики мышью, X11. Независимый tester: 4/4 PASS, `docs/qa/opening-trainer-v2-functional.md`; данные 2.2/2.3 читаются без изменений — `docs/qa/opening-trainer-v2-migration.md`. - **2026-11-27 (владелец):** не сливать пока; временные стрелки перенесены (`8ca7f43`); колонка «Выучено» с полосой выучено/учится и подсказкой о критерии, «нет ходов» для пустого, «Учится +N» в итоге (`7cb0291`); строка ходов линии в занятии возвращена (`3011beb`). Цвет старых репертуаров владелец меняет вручную. -- **Осталось:** на выделенной строке таблицы сегмент «учится» плохо виден; подсказки при наведении на снимках не проверены; удалить мёртвый код ядра (`session.rs`, `stats.rs`, `StatsStore`) отдельной задачей. +- **Сделано позже 27.11:** полоса на выделенной строке в обеих темах (`87e8a6d`); удалён мёртвый код ядра, −4229 строк (`07c6d0c`), данные владельца читаются без изменений (sha256). Оставлены типы чтения v2/legacy и `StatsStore` (тесты миграции); аналитические модули ядра (`*_analytics`, `aggregate`) новым UI не используются — можно удалить отдельно. +- **Осталось:** подсказки при наведении на снимках не проверены; Android-сборка Rust-части не проверена (нужен NDK); бледный сегмент «учится» на невыделенных строках в тёмной теме. ## Сделано From 613d14bfdd3a3839d07cb971d121686760916b01 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 09:23:54 +0300 Subject: [PATCH 29/31] =?UTF-8?q?opening=20trainer:=20the=20table's=20bar?= =?UTF-8?q?=20is=20green/blue=20on=20a=20visible=20track=20(white=20on=20a?= =?UTF-8?q?=20dark=20selection),=20=C2=ABlearning=20Z=C2=BB=20instead=20of?= =?UTF-8?q?=20=C2=AB0/Y=C2=BB,=20column=20=C2=ABProgress=C2=BB,=20the=20ne?= =?UTF-8?q?xt=20review=20under=20=C2=ABToday=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/i18n.rs | 11 ++++++ apps/desktop/src/repertoire_ui.rs | 66 ++++++++++++++++++++++--------- 2 files changed, 59 insertions(+), 18 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 19b6c24..9d3444d 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -854,6 +854,17 @@ const ROWS: &[[&str; 9]] = &[ "O‘rganilgan {x}, o‘rganilmoqda {z}, jami {y} yurish. Yurish ketma-ket uchta to‘g‘ri javobdan keyin (yordamsiz) o‘rganilgan hisoblanadi — odatda bir necha kunlik takrorlashda.", "Үйренілген {x}, үйренілуде {z}, барлығы {y} жүріс. Жүріс кеңессіз қатарынан үш дұрыс жауаптан кейін үйренілген саналады — әдетте бірнеше күндік қайталауда.", ], + [ + "Progress", + "Прогресс", + "Progression", + "Fortschritt", + "Progreso", + "Progressi", + "Progresso", + "Taraqqiyot", + "Ілгерілеу", + ], [ "New moves left", "Новых ходов осталось", diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index c4f6ae8..9efb969 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -12,7 +12,7 @@ use std::time::Duration; use chess_core::shakmaty::{Chess, Color, Position, Square}; use chess_core::{Game, NodeId, PgnDatabase, Severity}; -use egui::{Key, Modifiers, RichText, Ui, vec2}; +use egui::{Color32, Key, Modifiers, RichText, Ui, vec2}; use trainer::repertoire::{ LearningData, LearningItemKey, LearningSide, LearningStore, LearningStoreData, Library, LibraryStore, MergeReport, RepertoireId, ResetImpactProjection, SrsSettings, StatsScope, @@ -1691,7 +1691,7 @@ impl RepertoireUi { ui.add(egui::Label::new(RichText::new(tr("Name")).strong()).truncate()); }); header.col(|_| {}); - for key in ["Today", "Learned"] { + for key in ["Today", "Progress"] { header.col(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate()); @@ -1729,6 +1729,17 @@ impl RepertoireUi { &[("n", &stats.due), ("m", &stats.new_today())], )); } + // Nothing today: when the next review is. + Some(Ok(RowStats { + next: Some((at, _)), + .. + })) => { + let when = layout::when(*at, layout::now()); + ui.add( + egui::Label::new(RichText::new(&when).weak()).truncate(), + ) + .on_hover_text(format!("{}: {when}", tr("Next review"))); + } Some(_) => { ui.label(RichText::new("—").weak()); } @@ -1750,8 +1761,17 @@ impl RepertoireUi { } Some(Ok(stats)) if stats.total > 0 => { let hint = learned_hint(stats); - ui.label(format!("{}/{}", stats.learnt, stats.total)) - .on_hover_text(&hint); + // «0/17» reads as «nothing done»: name what is under way. + let text = if stats.learnt == 0 && stats.learning > 0 { + RichText::new(trf( + "learning {k}", + &[("k", &stats.learning)], + )) + .weak() + } else { + RichText::new(format!("{}/{}", stats.learnt, stats.total)) + }; + ui.label(text).on_hover_text(&hint); let room = ui.available_width() - ui.spacing().item_spacing.x; if room >= 16.0 { let (bar, response) = ui.allocate_exact_size( @@ -2487,35 +2507,45 @@ fn learned_hint(stats: &RowStats) -> String { } /// The two segments: learned, then learning (paler). -/// On a selected table row the selection colour is the row's own: the segments take -/// the colour of the text on the selection instead. +/// Learned — the green of a correct move; learning — the accent blue; the track stands +/// out from the row. On a selected dark row: white, half-white and a dark track. fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>, selected: bool) { - let painter = ui.painter(); - // In the light theme the extreme colour is the rows' white: the track is a button's grey. - let track = if ui.visuals().dark_mode { - ui.visuals().extreme_bg_color + let visuals = ui.visuals(); + let (track, learnt_fill, learning_fill) = if selected && visuals.dark_mode { + ( + Color32::from_black_alpha(90), + Color32::WHITE, + Color32::from_white_alpha(128), + ) + } else if selected { + // The light selection is pale: white would vanish, the selection's text colour shows. + let ink = visuals.selection.stroke.color; + (Color32::from_white_alpha(170), ink, ink.gamma_multiply(0.5)) } else { - ui.visuals().widgets.inactive.bg_fill + let green = crate::notation::assessment_text_color(chess_core::Nag(1), visuals.dark_mode) + .unwrap_or(visuals.selection.bg_fill); + let track = if visuals.dark_mode { + visuals.widgets.inactive.bg_fill + } else { + visuals.widgets.inactive.bg_fill.gamma_multiply(0.9) + }; + (track, green, visuals.hyperlink_color) }; + let painter = ui.painter(); painter.rect_filled(bar, 2.0, track); if let Some(stats) = stats.filter(|stats| stats.total > 0) { let total = stats.total as f32; let learnt = bar.width() * stats.learnt as f32 / total; let learning = bar.width() * stats.learning as f32 / total; - let fill = if selected { - ui.visuals().selection.stroke.color - } else { - ui.visuals().selection.bg_fill - }; painter.rect_filled( egui::Rect::from_min_size(bar.min, vec2(learnt, bar.height())), 2.0, - fill, + learnt_fill, ); painter.rect_filled( egui::Rect::from_min_size(bar.min + vec2(learnt, 0.0), vec2(learning, bar.height())), 0.0, - fill.gamma_multiply(0.45), + learning_fill, ); } } From 27217322edb7b7a111380a2a8bf32d4d739c3b48 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 09:38:35 +0300 Subject: [PATCH 30/31] =?UTF-8?q?opening=20trainer:=20table=20columns=20?= =?UTF-8?q?=C2=ABToday=C2=BB=20(review=20N=20/=20new:=20N=20/=20when)=20an?= =?UTF-8?q?d=20=C2=ABPassed=C2=BB=20(bar=20at=20a=20fixed=20place,=20A/Y);?= =?UTF-8?q?=20=C2=ABpassed=20/=20consolidated=C2=BB=20wording=20in=20the?= =?UTF-8?q?=20card,=20the=20summary=20and=20Lines?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/desktop/src/i18n.rs | 168 +++++++++++----------- apps/desktop/src/opening_lines.rs | 2 +- apps/desktop/src/opening_session.rs | 27 ++-- apps/desktop/src/opening_session_tests.rs | 2 +- apps/desktop/src/repertoire_ui.rs | 141 +++++++++--------- apps/desktop/src/repertoire_ui_tests.rs | 2 +- 6 files changed, 175 insertions(+), 167 deletions(-) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index 9d3444d..1c4a2ad 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -216,17 +216,6 @@ 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]] = &[ - [ - "Learned", - "Выучено", - "Appris", - "Gelernt", - "Aprendidas", - "Imparate", - "Aprendidas", - "O‘rganildi", - "Үйренілді", - ], [ "You play White", "Вы играете белыми", @@ -403,17 +392,6 @@ const ROWS: &[[&str; 9]] = &[ "⬅ Partiyaga", "⬅ Партияға", ], - [ - "Below: {n} lines · {y} your moves · learned {x}", - "Дальше: вариантов {n} · ваших ходов {y} · выучено {x}", - "En dessous : {n} lignes · {y} de vos coups · {x} appris", - "Darunter: {n} Varianten · {y} eigene Züge · {x} gelernt", - "Debajo: {n} líneas · {y} jugadas tuyas · {x} aprendidas", - "Sotto: {n} linee · {y} tue mosse · {x} imparate", - "Abaixo: {n} linhas · {y} lances seus · {x} aprendidos", - "Keyin: {n} ta variant · sizning {y} ta yurishingiz · {x} tasi o‘rganilgan", - "Әрі қарай: {n} нұсқа · сіздің {y} жүрісіңіз · {x} үйренілді", - ], [ "Lines · {n} lines · {y} your moves", "Варианты · вариантов: {n} · ваших ходов: {y}", @@ -810,17 +788,6 @@ const ROWS: &[[&str; 9]] = &[ "Shox: {path}", "Тармақ: {path}", ], - [ - "Learning", - "Учится", - "En cours", - "In Arbeit", - "En curso", - "In corso", - "Em andamento", - "O‘rganilmoqda", - "Үйренілуде", - ], [ "no moves", "нет ходов", @@ -844,26 +811,92 @@ const ROWS: &[[&str; 9]] = &[ "Репертуарда әзірге жүріс жоқ: PGN импорттаңыз немесе партиядан желі қосыңыз", ], [ - "Learned {x}, learning {z}, {y} moves in all. A move counts as learned after three correct answers in a row without a hint — usually over several days of reviews.", - "Выучено {x}, учится {z}, всего {y} ходов. Ход считается выученным после трёх верных ответов подряд без подсказки — обычно за несколько дней повторений.", - "Appris {x}, en cours {z}, {y} coups au total. Un coup est appris après trois bonnes réponses d’affilée sans indice — en général sur plusieurs jours de révisions.", - "Gelernt {x}, in Arbeit {z}, insgesamt {y} Züge. Ein Zug gilt als gelernt nach drei richtigen Antworten in Folge ohne Hinweis — meist über mehrere Tage Wiederholung.", - "Aprendidas {x}, en curso {z}, {y} jugadas en total. Una jugada se da por aprendida tras tres respuestas correctas seguidas sin pista; normalmente en varios días de repaso.", - "Imparate {x}, in corso {z}, {y} mosse in tutto. Una mossa è imparata dopo tre risposte giuste di fila senza suggerimento — di solito in alcuni giorni di ripasso.", - "Aprendidos {x}, em andamento {z}, {y} lances no total. Um lance conta como aprendido após três respostas certas seguidas sem dica — normalmente em vários dias de revisão.", - "O‘rganilgan {x}, o‘rganilmoqda {z}, jami {y} yurish. Yurish ketma-ket uchta to‘g‘ri javobdan keyin (yordamsiz) o‘rganilgan hisoblanadi — odatda bir necha kunlik takrorlashda.", - "Үйренілген {x}, үйренілуде {z}, барлығы {y} жүріс. Жүріс кеңессіз қатарынан үш дұрыс жауаптан кейін үйренілген саналады — әдетте бірнеше күндік қайталауда.", + "review {n}", + "повторить {n}", + "réviser {n}", + "{n} wiederholen", + "repasar {n}", + "ripassare {n}", + "revisar {n}", + "takrorlash {n}", + "қайталау {n}", ], [ - "Progress", - "Прогресс", - "Progression", - "Fortschritt", - "Progreso", - "Progressi", - "Progresso", - "Taraqqiyot", - "Ілгерілеу", + "new: {n}", + "новые: {n}", + "nouveaux : {n}", + "neu: {n}", + "nuevas: {n}", + "nuove: {n}", + "novos: {n}", + "yangi: {n}", + "жаңа: {n}", + ], + [ + "To review {n}, new in the session {m}", + "К повторению {n}, новых в занятие {m}", + "À réviser {n}, nouveaux dans la séance {m}", + "Zu wiederholen {n}, neu in der Einheit {m}", + "Por repasar {n}, nuevas en la sesión {m}", + "Da ripassare {n}, nuove nella sessione {m}", + "Para revisar {n}, novos na sessão {m}", + "Takrorlash uchun {n}, mashg‘ulotda yangi {m}", + "Қайталауға {n}, сабақта жаңа {m}", + ], + [ + "Passed", + "Пройдено", + "Vus", + "Durchgenommen", + "Vistas", + "Viste", + "Vistos", + "O‘tilgan", + "Өтілген", + ], + [ + "Consolidated", + "Закреплено", + "Consolidés", + "Gefestigt", + "Consolidadas", + "Consolidate", + "Consolidados", + "Mustahkamlangan", + "Бекітілген", + ], + [ + "Passed {a} of {y} moves · consolidated {l}", + "Пройдено {a} из {y} ходов · закреплено {l}", + "{a} coups vus sur {y} · {l} consolidés", + "{a} von {y} Zügen durchgenommen · {l} gefestigt", + "{a} de {y} jugadas vistas · {l} consolidadas", + "{a} mosse viste su {y} · {l} consolidate", + "{a} de {y} lances vistos · {l} consolidados", + "{y} ta yurishdan {a} tasi o‘tilgan · {l} tasi mustahkamlangan", + "{y} жүрістің {a} өтілген · {l} бекітілген", + ], + [ + "Passed {a} of {y} moves, {l} of them consolidated. A move is consolidated after three correct answers in a row without a hint — usually over several days of reviews.", + "Пройдено {a} из {y} ходов, из них закреплено {l}. Ход закреплён после трёх верных ответов подряд без подсказки — обычно за несколько дней повторений.", + "{a} coups vus sur {y}, dont {l} consolidés. Un coup est consolidé après trois bonnes réponses d’affilée sans indice — en général sur plusieurs jours de révisions.", + "{a} von {y} Zügen durchgenommen, davon {l} gefestigt. Ein Zug ist gefestigt nach drei richtigen Antworten in Folge ohne Hinweis — meist über mehrere Tage Wiederholung.", + "{a} de {y} jugadas vistas, {l} de ellas consolidadas. Una jugada queda consolidada tras tres respuestas correctas seguidas sin pista; normalmente en varios días de repaso.", + "{a} mosse viste su {y}, di cui {l} consolidate. Una mossa è consolidata dopo tre risposte giuste di fila senza suggerimento — di solito in alcuni giorni di ripasso.", + "{a} de {y} lances vistos, {l} deles consolidados. Um lance fica consolidado após três respostas certas seguidas sem dica — normalmente em vários dias de revisão.", + "{y} ta yurishdan {a} tasi o‘tilgan, ulardan {l} tasi mustahkamlangan. Yurish ketma-ket uchta to‘g‘ri javobdan keyin (yordamsiz) mustahkamlanadi — odatda bir necha kunlik takrorlashda.", + "{y} жүрістің {a} өтілген, оның {l} бекітілген. Жүріс кеңессіз қатарынан үш дұрыс жауаптан кейін бекітіледі — әдетте бірнеше күндік қайталауда.", + ], + [ + "Below: {n} lines · {y} your moves · consolidated {x}", + "Дальше: вариантов {n} · ваших ходов {y} · закреплено {x}", + "En dessous : {n} lignes · {y} de vos coups · {x} consolidés", + "Darunter: {n} Varianten · {y} eigene Züge · {x} gefestigt", + "Debajo: {n} líneas · {y} jugadas tuyas · {x} consolidadas", + "Sotto: {n} linee · {y} tue mosse · {x} consolidate", + "Abaixo: {n} linhas · {y} lances seus · {x} consolidados", + "Keyin: {n} ta variant · sizning {y} ta yurishingiz · {x} tasi mustahkamlangan", + "Әрі қарай: {n} нұсқа · сіздің {y} жүрісіңіз · {x} бекітілген", ], [ "New moves left", @@ -1360,17 +1393,6 @@ const ROWS: &[[&str; 9]] = &[ "Repertuarlarni o‘qib bo‘lmadi: {e}", "Репертуарларды оқу мүмкін болмады: {e}", ], - [ - "{n} to review, {m} new", - "Повторить: {n}, новых: {m}", - "{n} à réviser, {m} nouveaux", - "{n} zu wiederholen, {m} neu", - "{n} para repasar, {m} nuevas", - "{n} da ripassare, {m} nuove", - "{n} para revisar, {m} novos", - "Takrorlash: {n}, yangi: {m}", - "Қайталау: {n}, жаңа: {m}", - ], [ "Play “{name}” as Black?", "Играть «{name}» чёрными?", @@ -1525,28 +1547,6 @@ const ROWS: &[[&str; 9]] = &[ "{m} ta yangisini o‘rganish", "{m} жаңасын үйрену", ], - [ - "Learned {x} of {y} moves", - "Выучено {x} из {y} ходов", - "{x} coups appris sur {y}", - "{x} von {y} Zügen gelernt", - "{x} de {y} jugadas aprendidas", - "{x} mosse imparate su {y}", - "{x} de {y} lances aprendidos", - "{y} ta yurishdan {x} tasi o‘rganildi", - "{y} жүрістің {x} үйренілді", - ], - [ - "learning {k}", - "учится {k}", - "en cours {k}", - "in Arbeit {k}", - "en curso {k}", - "in corso {k}", - "em andamento {k}", - "o‘rganilmoqda {k}", - "үйренілуде {k}", - ], [ "Add PGN to “{name}”", "Добавить PGN в «{name}»", diff --git a/apps/desktop/src/opening_lines.rs b/apps/desktop/src/opening_lines.rs index 01fe24c..a6e09f0 100644 --- a/apps/desktop/src/opening_lines.rs +++ b/apps/desktop/src/opening_lines.rs @@ -296,7 +296,7 @@ impl OpeningLinesUi { } else { let text = match self.below(&path) { Some((lines, mine, learnt)) => trf( - "Below: {n} lines · {y} your moves · learned {x}", + "Below: {n} lines · {y} your moves · consolidated {x}", &[("n", &lines), ("y", &mine), ("x", &learnt)], ), None => tr("Counting moves…").to_owned(), diff --git a/apps/desktop/src/opening_session.rs b/apps/desktop/src/opening_session.rs index a072ce6..f75ea2b 100644 --- a/apps/desktop/src/opening_session.rs +++ b/apps/desktop/src/opening_session.rs @@ -210,9 +210,10 @@ enum State { /// Computed once when the result is shown. struct Summary { next_review: String, - /// How many more moves are learned, and learning, than when the session began. - learnt_gain: usize, - learning_gain: usize, + /// How many more moves are passed (met at least once) and consolidated than when + /// the session began. + passed_gain: usize, + consolidated_gain: usize, /// Moves never shown yet, all of them (the «more new» button takes up to 10). unseen: usize, more_new: usize, @@ -1640,8 +1641,9 @@ impl OpeningSessionUi { let (learnt, learning) = progress_counts(&self.library, &self.learning, &self.whole_scope); self.summary = Some(Summary { next_review, - learnt_gain: learnt.saturating_sub(self.start_progress.0), - learning_gain: learning.saturating_sub(self.start_progress.1), + passed_gain: (learnt + learning) + .saturating_sub(self.start_progress.0 + self.start_progress.1), + consolidated_gain: learnt.saturating_sub(self.start_progress.0), unseen, more_new: unseen.min(layout::NEW_PER_SESSION), }); @@ -1926,11 +1928,16 @@ impl OpeningSessionUi { ui.separator(); ui.add_space(4.0); if let Some(summary) = &self.summary { - // Learned takes days: what the session did shows as «learning». - if summary.learnt_gain > 0 { - row(ui, tr("Learned"), format!("+{}", summary.learnt_gain)); - } else if summary.learning_gain > 0 { - row(ui, tr("Learning"), format!("+{}", summary.learning_gain)); + // Consolidating takes days: what the session did shows as «passed». + if summary.passed_gain > 0 { + row(ui, tr("Passed"), format!("+{}", summary.passed_gain)); + } + if summary.consolidated_gain > 0 { + row( + ui, + tr("Consolidated"), + format!("+{}", summary.consolidated_gain), + ); } if self.kind == SessionKind::Daily && summary.unseen > 0 { row(ui, tr("New moves left"), summary.unseen.to_string()); diff --git a/apps/desktop/src/opening_session_tests.rs b/apps/desktop/src/opening_session_tests.rs index f6753eb..3a1a960 100644 --- a/apps/desktop/src/opening_session_tests.rs +++ b/apps/desktop/src/opening_session_tests.rs @@ -2229,7 +2229,7 @@ fn the_summary_shows_learning_growth_when_nothing_is_learned_yet() { assert!(f.ui.is_finished()); f.ui.compute_summary(); let summary = f.ui.summary.as_ref().unwrap(); - assert_eq!((summary.learnt_gain, summary.learning_gain), (0, 2)); + assert_eq!((summary.passed_gain, summary.consolidated_gain), (2, 0)); } #[test] diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs index 9efb969..9ec0aff 100644 --- a/apps/desktop/src/repertoire_ui.rs +++ b/apps/desktop/src/repertoire_ui.rs @@ -52,9 +52,10 @@ const BOTTOM_W: f32 = 150.0; const MAIN_W: f32 = 170.0; const LINES_W: f32 = 110.0; const THIRD_W: f32 = 150.0; -/// The «Learned» column: a small bar and «X/Y». -const LEARNED_W: f32 = 104.0; +/// The table's fixed columns: «Today» phrase, the bar, «A/Y» (room for «999/999»). +const TODAY_W: f32 = 90.0; const MINI_BAR_W: f32 = 44.0; +const PASSED_W: f32 = 64.0; const DIALOG_W: f32 = 460.0; /// A session appears at once when it is ready this fast; otherwise «Preparing…». const PREPARING_SHOWN_AFTER: Duration = Duration::from_millis(300); @@ -88,12 +89,13 @@ struct RowStats { } impl RowStats { - fn new_today(&self) -> usize { - self.unseen.min(NEW_PER_SESSION) + /// Moves met in training at least once: learning and learned. + fn passed(&self) -> usize { + self.learning + self.learnt } - fn today(&self) -> usize { - self.due + self.new_today() + fn new_today(&self) -> usize { + self.unseen.min(NEW_PER_SESSION) } } @@ -1679,8 +1681,9 @@ impl RepertoireUi { .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) .column(egui_extras::Column::remainder().at_least(80.0).clip(true)) .column(egui_extras::Column::exact(22.0)) - .column(egui_extras::Column::exact(58.0)) - .column(egui_extras::Column::exact(LEARNED_W)) + .column(egui_extras::Column::exact(TODAY_W)) + .column(egui_extras::Column::exact(MINI_BAR_W)) + .column(egui_extras::Column::exact(PASSED_W)) .column(egui_extras::Column::exact(26.0)); if let Some(index) = scroll_row { table = table.scroll_to_row(index, None); @@ -1691,13 +1694,18 @@ impl RepertoireUi { ui.add(egui::Label::new(RichText::new(tr("Name")).strong()).truncate()); }); header.col(|_| {}); - for key in ["Today", "Progress"] { - header.col(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add(egui::Label::new(RichText::new(tr(key)).strong()).truncate()); - }); + header.col(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(tr("Today")).strong()).truncate()); }); - } + }); + // «Passed» heads the bar and the number together. + header.col(|_| {}); + header.col(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(tr("Passed")).strong()).truncate()); + }); + }); header.col(|_| {}); }) .body(|body| { @@ -1721,26 +1729,25 @@ impl RepertoireUi { row.col(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { match stats { - // An empty repertoire: «no moves» under «Learned» says it. Some(Ok(_)) if !has_moves => {} - Some(Ok(stats)) if stats.today() > 0 => { - ui.label(stats.today().to_string()).on_hover_text(trf( - "{n} to review, {m} new", + Some(Ok(stats)) => { + // A call to action in the normal colour; the rest quiet. + let text = if stats.due > 0 { + RichText::new(trf("review {n}", &[("n", &stats.due)])) + } else if stats.new_today() > 0 { + RichText::new(trf("new: {n}", &[("n", &stats.new_today())])) + .weak() + } else if let Some((at, _)) = stats.next { + RichText::new(layout::when(at, layout::now())).weak() + } else { + RichText::new("—").weak() + }; + ui.add(egui::Label::new(text).truncate()).on_hover_text(trf( + "To review {n}, new in the session {m}", &[("n", &stats.due), ("m", &stats.new_today())], )); } - // Nothing today: when the next review is. - Some(Ok(RowStats { - next: Some((at, _)), - .. - })) => { - let when = layout::when(*at, layout::now()); - ui.add( - egui::Label::new(RichText::new(&when).weak()).truncate(), - ) - .on_hover_text(format!("{}: {when}", tr("Next review"))); - } - Some(_) => { + Some(Err(_)) => { ui.label(RichText::new("—").weak()); } None => { @@ -1749,6 +1756,21 @@ impl RepertoireUi { } }); }); + let passed = matches!(stats, Some(Ok(stats)) if has_moves && stats.total > 0); + row.col(|ui| { + if let Some(Ok(stats)) = stats + && passed + { + let room = ui.available_rect_before_wrap(); + let bar = egui::Rect::from_min_size( + egui::pos2(room.left(), room.center().y - 3.0), + vec2(MINI_BAR_W, 6.0), + ); + progress_bar(ui, bar, Some(stats), selected); + ui.allocate_rect(room, egui::Sense::hover()) + .on_hover_text(passed_hint(stats)); + } + }); row.col(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { match stats { @@ -1759,28 +1781,9 @@ impl RepertoireUi { ) .on_hover_text(tr("The repertoire has no moves yet: import a PGN or add a line from a game")); } - Some(Ok(stats)) if stats.total > 0 => { - let hint = learned_hint(stats); - // «0/17» reads as «nothing done»: name what is under way. - let text = if stats.learnt == 0 && stats.learning > 0 { - RichText::new(trf( - "learning {k}", - &[("k", &stats.learning)], - )) - .weak() - } else { - RichText::new(format!("{}/{}", stats.learnt, stats.total)) - }; - ui.label(text).on_hover_text(&hint); - let room = ui.available_width() - ui.spacing().item_spacing.x; - if room >= 16.0 { - let (bar, response) = ui.allocate_exact_size( - vec2(room.min(MINI_BAR_W), 6.0), - egui::Sense::hover(), - ); - progress_bar(ui, bar, Some(stats), selected); - response.on_hover_text(hint); - } + Some(Ok(stats)) if passed => { + ui.label(format!("{}/{}", stats.passed(), stats.total)) + .on_hover_text(passed_hint(stats)); } Some(_) => { ui.label(RichText::new("—").weak()); @@ -2495,18 +2498,18 @@ fn main_button(state: &CardState, side: LearningSide) -> (String, bool, Option String { +fn passed_hint(stats: &RowStats) -> String { trf( - "Learned {x}, learning {z}, {y} moves in all. A move counts as learned after three correct answers in a row without a hint — usually over several days of reviews.", + "Passed {a} of {y} moves, {l} of them consolidated. A move is consolidated after three correct answers in a row without a hint — usually over several days of reviews.", &[ - ("x", &stats.learnt), - ("z", &stats.learning), + ("a", &stats.passed()), ("y", &stats.total), + ("l", &stats.learnt), ], ) } -/// The two segments: learned, then learning (paler). +/// Blue — passed, green inside it — consolidated. /// Learned — the green of a correct move; learning — the accent blue; the track stands /// out from the row. On a selected dark row: white, half-white and a dark track. fn progress_bar(ui: &Ui, bar: egui::Rect, stats: Option<&RowStats>, selected: bool) { @@ -2557,19 +2560,17 @@ fn progress(ui: &mut Ui, stats: Option<&RowStats>) { ui.add_space(-2.0); ui.horizontal(|ui| { ui.set_height(20.0); - let (learnt, total, learning) = stats.map_or((0, 0, 0), |stats| { - (stats.learnt, stats.total, stats.learning) - }); - if stats.is_some() { - let mut text = trf("Learned {x} of {y} moves", &[("x", &learnt), ("y", &total)]); - // The bar's second segment, named where the bar is read. - if learning > 0 { - text = format!("{text} · {}", trf("learning {k}", &[("k", &learning)])); - } - if let Some(stats) = stats { - ui.add(egui::Label::new(text).truncate()) - .on_hover_text(learned_hint(stats)); - } + if let Some(stats) = stats { + let text = trf( + "Passed {a} of {y} moves · consolidated {l}", + &[ + ("a", &stats.passed()), + ("y", &stats.total), + ("l", &stats.learnt), + ], + ); + ui.add(egui::Label::new(text).truncate()) + .on_hover_text(passed_hint(stats)); } }); } diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs index f8613e8..f15da56 100644 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ b/apps/desktop/src/repertoire_ui_tests.rs @@ -223,7 +223,7 @@ fn today_counts_until_the_end_of_the_day_and_at_most_ten_new() { (12, 2, 9, 3) ); assert_eq!(stats.new_today(), 9); - assert_eq!(stats.today(), 11); + assert_eq!(stats.passed(), 3 + stats.learning); assert_eq!( card_state(Some(true), Some(&Ok(stats.clone()))), CardState::Review { due: 2, new: 9 } From 05514c661e915f61b482b0584961cef1d0bf5fcd Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Fri, 27 Nov 2026 09:57:49 +0300 Subject: [PATCH 31/31] release: prepare 2.4.0 with the rewritten opening training --- AGENTS.md | 2 +- CHANGELOG.md | 2 ++ Cargo.lock | 28 +++++++++---------- Cargo.toml | 2 +- docs/architecture.md | 11 ++++---- docs/decisions.md | 7 +++++ docs/dev/tasks.md | 2 +- docs/qa/release-2.4.0.md | 11 ++++++++ ...thub.vrubelroman.chessPenguin.metainfo.xml | 5 ++++ 9 files changed, 47 insertions(+), 23 deletions(-) create mode 100644 docs/qa/release-2.4.0.md diff --git a/AGENTS.md b/AGENTS.md index 5e67a22..1d5c2e0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ - Исходное ТЗ: `техническое задание.txt`. - Пользовательские материалы: `designExample/`, `pgnFilesforExample/`, `engines/`. - Рабочий язык обсуждений и проектных заметок — русский; идентификаторы кода — английский. -- Текущий этап: развитие выпускаемого продукта (релиз 2.3.0). Задачи и бэклог — `docs/dev/tasks.md`. +- Текущий этап: развитие выпускаемого продукта (релиз 2.4.0). Задачи и бэклог — `docs/dev/tasks.md`. - Архитектура реализованной системы: `docs/architecture.md`; архитектурное предложение этапа исследования — `docs/research/architecture-proposal-2026-10-17.md`; исследования: `docs/research/`. - Журнал решений: `docs/decisions.md`; подтверждённые пользователем решения имеют приоритет над предложениями исследований. diff --git a/CHANGELOG.md b/CHANGELOG.md index 187a897..3eb79cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] +## [2.4.0] — 2026-11-27 + - Desktop play and opening training support multiple temporary right-button arrows and circles until the position changes. They are never written to PGN; shapes drawn in ordinary game analysis remain PGN annotations and are saved only with the game. diff --git a/Cargo.lock b/Cargo.lock index b46ffbc..6e73411 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -774,7 +774,7 @@ dependencies = [ [[package]] name = "chess-core" -version = "2.3.0" +version = "2.4.0" dependencies = [ "encoding_rs", "pgn-reader", @@ -785,7 +785,7 @@ dependencies = [ [[package]] name = "chess-import" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "encoding_rs", @@ -798,7 +798,7 @@ dependencies = [ [[package]] name = "chess-openings" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-import", "serde", @@ -807,7 +807,7 @@ dependencies = [ [[package]] name = "chesspenguin" -version = "2.3.0" +version = "2.4.0" dependencies = [ "arboard", "base64 0.22.1", @@ -854,7 +854,7 @@ dependencies = [ [[package]] name = "chesspenguin-web" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chesspenguin", "eframe", @@ -1705,7 +1705,7 @@ dependencies = [ [[package]] name = "game-review" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "chess-openings", @@ -2426,7 +2426,7 @@ dependencies = [ [[package]] name = "maia" -version = "2.3.0" +version = "2.4.0" dependencies = [ "serde_json", "shakmaty", @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "mobile-api" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "chess-import", @@ -3121,7 +3121,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "online-games" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "serde", @@ -3394,7 +3394,7 @@ checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] name = "play" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "getrandom 0.3.4", @@ -3495,7 +3495,7 @@ checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1" [[package]] name = "prep" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "chess-import", @@ -3694,7 +3694,7 @@ dependencies = [ [[package]] name = "releases" -version = "2.3.0" +version = "2.4.0" dependencies = [ "serde_json", "ureq", @@ -4692,7 +4692,7 @@ dependencies = [ [[package]] name = "trainer" -version = "2.3.0" +version = "2.4.0" dependencies = [ "chess-core", "chrono", @@ -4735,7 +4735,7 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "uci" -version = "2.3.0" +version = "2.4.0" dependencies = [ "js-sys", "libc", diff --git a/Cargo.toml b/Cargo.toml index 645bdfb..5b086aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,7 +18,7 @@ members = [ ] [workspace.package] -version = "2.3.0" +version = "2.4.0" edition = "2024" rust-version = "1.97" license = "GPL-3.0-or-later" diff --git a/docs/architecture.md b/docs/architecture.md index fc000b7..42bbaa5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Архитектура ChessPenguin -Статус: описание реализованной системы для выпуска **2.3.0**, обновлено 2026-11-06. Тренажёр дебютов включён в настольное приложение с пометкой α. +Статус: описание реализованной системы для выпуска **2.4.0**, обновлено 2026-11-27. Тренажёр дебютов включён в настольное приложение с пометкой α. Первоначальный документ с этим именем — архитектурное предложение этапа исследования (2026-10-17) — сохранён в `docs/research/architecture-proposal-2026-10-17.md`. @@ -106,11 +106,10 @@ desktop (egui, apps/desktop) │ web (wasm, apps/web) │ android (Kotlin + mobi - Реализовано и выпущено: библиотека PGN/ChessBase, нотация с редактированием, анализ и обзор партии, подготовка к сопернику, игра (Maia/Rodent), онлайн-партии, свои базы, перевод комментариев, автоматическое обновление. История — `CHANGELOG.md`. -- Desktop-тренажёр дебютов выпущен с пометкой α: библиотека PGN-репертуаров, - общая SRS-модель, режимы обучения, контекст, редактор и аналитика. В 2.3.0 - изучаются все включённые варианты; PGN-пометки привязаны к показанному узлу. - Повторный контекст сохраняется одним атомарным пакетом, позиции текущего пути - кэшируются в памяти сессии без изменения формата хранения. +- Desktop-тренажёр дебютов (α): с 2.4.0 — упрощённый UI (`repertoire_ui.rs`, `opening_session.rs`, + `opening_lines.rs`, `opening_layout.rs`) поверх ядра `crates/trainer/src/repertoire`: общая SRS-модель + по `(профиль, FEN4, UCI)`, дневное занятие (к повторению + до 10 новых), «Повторить всё подряд», + тренировка ветки; режимы, параметры контекста и дашборд из UI удалены, формат хранения не менялся. Android продолжает использовать прежний линейный тренер и совместимые legacy-данные; web-версия этот экран не получает. - Очередь и идеи — `docs/dev/tasks.md`; перенос на другую машину — `docs/dev/handoff.md`. diff --git a/docs/decisions.md b/docs/decisions.md index 304e0c2..8b05daf 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -523,3 +523,10 @@ PGN для точного выбора пометок, минимальная г - Цвет задаётся при импорте/создании. При первом открытии раздела (файла библиотеки ещё нет) создаются два примера: Испанская партия (белые) и Найдорф (чёрные); удалённые примеры не возвращаются. - Неверный ход на только что показанном новом ходе ошибкой не считается: «Не тот ход» ~0,4 с, затем снова показ. +## Выпуск 2.4.0 (2026-11-27) + +Владелец поручил слить ветку `feature/opening-trainer-v2` в `main`, отправить в Forgejo и GitHub, +собрать сборки и обновить сайт по обычному процессу. После 2.3.0 это 2.4.0, тег v2.4.0. +Таблица репертуаров по замечаниям владельца: «Сегодня» — фраза («повторить N», «новые: N», «завтра»), +«Пройдено A/Y» с полосой «пройдено/закреплено»; слова «учится/выучено» заменены на «пройдено/закреплено». + diff --git a/docs/dev/tasks.md b/docs/dev/tasks.md index de4da45..6a7dab5 100644 --- a/docs/dev/tasks.md +++ b/docs/dev/tasks.md @@ -281,7 +281,7 @@ - **Статус:** выпущено в 2.3.0. Workspace — 696 passed, 17 ignored; Clippy/fmt, desktop build и wasm check успешны. В изолированном приложении проверены ответ программы после хода пользователя с большой историей, пауза/продолжение, сохранность PGN и отсутствие дублей. Подробности: `docs/qa/training-performance-2026-11-06.md`. ### 40. Тренировка дебюта v2: простой и понятный раздел (2026-11-26) -- **Статус:** реализовано в ветке `feature/opening-trainer-v2` (от 2.3.0), принято дизайн-ревью с исправлениями; ждёт решения владельца о слиянии в `main` и выпуске. +- **Статус:** сделано — выпуск 2.4.0 (2026-11-27), ветка `feature/opening-trainer-v2` слита в `main`. - **Суть (владелец):** переписать раздел как ChessTempo, но проще и понятнее; остальные разделы не менять. Решения делегированы оркестратору — `docs/decisions.md`, «Тренировка дебюта v2». - **Сделано:** один экран «Репертуары» (таблица + карточка: «Сегодня: N повторить · M новых», «Выучено X из Y · учится Z», «Тренироваться», «Варианты…», «Повторить всё»); занятие — линия от начала, новый ход показывается стрелкой, на ошибке — правильный ход, ошибка возвращается в том же занятии, комментарии и название дебюта; итог; «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты»; цвет при импорте; два стартовых репертуара (Испанская за белых, Найдорф за чёрных). Удалены режимы/порядки, окно параметров, дашборд с графиками, Branches/Lines, режим «за оба цвета», скрытый лимит глубины; ~13 тыс. строк старого UI. - **Проверено:** fmt, clippy `-D warnings`; trainer 200 passed, desktop 161 passed / 3 ignored (перепроверено оркестратором); mobile-api check. Дизайн-ревью `docs/qa/opening-trainer-v2-design-review.md`: скачков нет (0 px в серии состояний), шапка и доска совпадают с экраном партии после исправлений. diff --git a/docs/qa/release-2.4.0.md b/docs/qa/release-2.4.0.md new file mode 100644 index 0000000..54cb62b --- /dev/null +++ b/docs/qa/release-2.4.0.md @@ -0,0 +1,11 @@ +# Выпуск 2.4.0 — 27.11.2026 + +- Версия 2.4.0 / тег v2.4.0: минорное увеличение по поручению владельца. +- Изменения: переписанный desktop-раздел «Тренировка дебюта» (задача 40, `docs/dev/tasks.md`), + стартовые репертуары, временные стрелки и круги в игре и тренировке. Формат данных не менялся; + данные 2.2/2.3 читаются без изменений (`opening-trainer-v2-migration.md`). +- Перед выпуском (оркестратор): `cargo fmt --check`; `cargo clippy --workspace --all-targets --locked -D warnings`; + `cargo test --workspace --locked` — 593 passed / 0 failed / 16 ignored (меньше, чем в 2.3.0, из-за удалённых + тестов старого UI и мёртвого ядра); `cargo check -p chesspenguin-web --target wasm32-unknown-unknown --locked` — ок. +- Независимые проверки: дизайн-ревью `opening-trainer-v2-design-review.md`, функциональная + `opening-trainer-v2-functional.md` (4/4 PASS). diff --git a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml index 8cf0e93..13fcc1a 100644 --- a/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml +++ b/packaging/io.github.vrubelroman.chessPenguin.metainfo.xml @@ -43,6 +43,11 @@ BoardGame + + +

Desktop opening training is rewritten to be simpler: one screen of repertoires with clear progress, a daily session of reviews plus up to ten new moves, new moves are shown before they are asked, mistakes show the right move and return in the same session. Two example repertoires are included. Temporary arrows and circles can be drawn in play and training.

+
+

Desktop opening training shows PGN move badges, arrows and marked squares during user moves and automatic playback. All enabled variations can be trained. Automatic context avoids repeated PGN parsing and redundant progress writes.