diff --git a/.cargo/config.toml b/.cargo/config.toml index d92eacf..52be801 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -2,8 +2,3 @@ # without the Visual C++ Redistributable (VCRUNTIME140.dll). [target.x86_64-pc-windows-msvc] rustflags = ["-C", "target-feature=+crt-static"] - -# WebAssembly in a browser: random numbers from crypto.getRandomValues (getrandom 0.3 -# needs this as well as its `wasm_js` feature, enabled by apps/web). -[target.wasm32-unknown-unknown] -rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e8497e4..1455fb9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,7 +66,7 @@ jobs: # Apple Silicon: the build and the app bundle (decision 15). macos-build: - runs-on: macos-15 + runs-on: macos-14 steps: - uses: actions/checkout@v7 - uses: dtolnay/rust-toolchain@stable diff --git a/.github/workflows/release-notes.yml b/.github/workflows/release-notes.yml deleted file mode 100644 index 748e19a..0000000 --- a/.github/workflows/release-notes.yml +++ /dev/null @@ -1,52 +0,0 @@ -name: Release notes - -# Corrections to the changelog must also reach an already published release, -# without moving its tag or rebuilding the signed packages. -on: - push: - branches: [main] - paths: [CHANGELOG.md] - workflow_dispatch: - -permissions: - contents: write - -jobs: - update: - runs-on: ubuntu-24.04 - steps: - - uses: actions/checkout@v7 - - name: Update the current release notes if it has been published - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - run: | - python3 - <<'PY' - import json, os, pathlib, tomllib, urllib.error, urllib.request - - version = tomllib.loads(pathlib.Path('Cargo.toml').read_text())['workspace']['package']['version'] - heading = f'## [{version}]' - lines = pathlib.Path('CHANGELOG.md').read_text().splitlines() - start = next(i for i, line in enumerate(lines) if line.startswith(heading)) + 1 - end = next((i for i in range(start, len(lines)) if lines[i].startswith('## [')), len(lines)) - body = '\n'.join(lines[start:end]).strip() - assert body, 'Release notes must not be empty' - api = f'https://api.github.com/repos/{os.environ["GH_REPO"]}/releases' - headers = {'Authorization': f'Bearer {os.environ["GH_TOKEN"]}', - 'Accept': 'application/vnd.github+json', 'User-Agent': 'ChessPenguin-release-notes'} - try: - with urllib.request.urlopen(urllib.request.Request(f'{api}/tags/v{version}', headers=headers), timeout=30) as response: - release = json.load(response) - except urllib.error.HTTPError as error: - if error.code != 404: - raise - print(f'v{version} is not published yet; the release workflow will supply its notes.') - else: - data = json.dumps({'body': body}).encode() - request = urllib.request.Request(f'{api}/{release["id"]}', data=data, - headers={**headers, 'Content-Type': 'application/json'}, method='PATCH') - with urllib.request.urlopen(request, timeout=30) as response: - updated = json.load(response) - assert updated['body'].strip() == body - print(f'Updated notes for v{version}: {updated["html_url"]}') - PY diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9864cfa..b2bc9ae 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -114,7 +114,7 @@ jobs: needs: version # Apple Silicon (arm64). Not signed by Apple yet: the first start goes through # "Open" in the context menu (decision 15). - runs-on: macos-15 + runs-on: macos-14 env: VERSION: ${{ needs.version.outputs.version }} steps: diff --git a/.github/workflows/rodent-iv.yml b/.github/workflows/rodent-iv.yml index 34c814a..5086f2d 100644 --- a/.github/workflows/rodent-iv.yml +++ b/.github/workflows/rodent-iv.yml @@ -30,7 +30,7 @@ jobs: name: rodent-iv-linux-x86_64 - os: windows-latest name: rodent-iv-windows-x86_64.exe - - os: macos-15 + - os: macos-14 name: rodent-iv-macos-arm64 runs-on: ${{ matrix.os }} steps: diff --git a/.gitignore b/.gitignore index dd0c73e..d878c7d 100644 --- a/.gitignore +++ b/.gitignore @@ -10,9 +10,3 @@ # A local run of the website from the repository root (website/README.md runs it from server/). /data-dev/ - -# The web version built for the site (apps/web/build.sh website/static/app) -website/static/app/ - -# Claude Code worktrees of agents -.claude/worktrees/ diff --git a/.opencode/agents/analyst.md b/.opencode/agents/analyst.md index e9453a2..28849ef 100644 --- a/.opencode/agents/analyst.md +++ b/.opencode/agents/analyst.md @@ -4,19 +4,10 @@ mode: subagent color: "#33A68C" --- -Ты продуктовый и системный аналитик ChessPenguin. Пиши по-русски. Читай AGENTS.md, `техническое задание.txt`, `docs/dev/tasks.md` и назначенные исследования. Код приложения и исходные материалы (`pgnFilesforExample/`, `designExample/`, ТЗ) без прямого задания не изменяешь. +Ты продуктовый и системный аналитик шахматного desktop-приложения. Читай AGENTS.md, техническое задание.txt и связанные исследования. Пиши по-русски. Сохраняй аналитику в назначенные файлы docs/; не изменяй код приложения и исходные материалы без прямого задания. -Доказательность: +Связывай требования со сценариями пользователя и проверяемыми критериями приёмки. Отмечай источник каждого требования: ТЗ, подтверждение пользователя, предложение команды. Разделяй первую версию и последующие этапы. Вопросы задавай только там, где ответ меняет решение. -- Каждое требование веди к источнику: ТЗ, решение в `docs/decisions.md`, слово пользователя, предложение команды; тип источника помечай рядом с требованием. -- Критерии приёмки формулируй наблюдаемо: что видит пользователь или какая проверка их подтверждает. «Быстро», «удобно», «корректно» без измеримого критерия — не критерий. -- Разделяй факт (проверено на данных), гипотезу (нужна проверка) и предложение (вариант решения); не смешивай их в одном выводе. +Исследуй реальные данные: кодировки, заголовки, неизвестные теги, начальные FEN, RAV, NAG, комментарии до и после ходов, расширения аннотаций, усечённые партии и неоднозначности PGN. Статистику снабжай методом подсчёта; подсчёт регулярными выражениями не называй полноценной проверкой легальности. -Работа с реальными данными: - -- Любую статистику по PGN/ChessBase считай реальными командами над копией данных, с указанием инструмента и методики. Числа из головы недопустимы; подсчёт регулярными выражениями не называй проверкой легальности. -- Граничные случаи проверяй явно: legacy-кодировки, FEN с fullmove=0, учебный `--`, вложенность RAV, комментарии у корня/ходов/ветвей, NAG, усечённые записи, повтор позиции, старт чёрных. - -Сценарии мысли сквозными: импорт → просмотр → редактирование → экспорт → повторное открытие; внешнее изменение файла; отмена долгой операции; авария посреди записи. Вопросы задавай только там, где ответ меняет решение, и приводи варианты с последствиями. - -Отчёт (обязательный формат): выводы с пометками факт/гипотеза/предложение · изменённые файлы · открытые вопросы · что нужно от других ролей. +Продумывай импорт, повторное открытие, изменение внешнего файла, отмену долгих операций, поиск, создание партии, экспорт и восстановление несохранённой работы. Поддерживай журнал решений и открытых вопросов в рамках назначенной области. В итогах сообщай факты, риски, изменённые файлы и рекомендации. diff --git a/.opencode/agents/designer.md b/.opencode/agents/designer.md index 7a8b8d8..ab6f417 100644 --- a/.opencode/agents/designer.md +++ b/.opencode/agents/designer.md @@ -4,26 +4,16 @@ mode: subagent color: "#BD7AD8" --- -Ты senior product designer ChessPenguin. Пиши по-русски. Прежде чем предлагать, смотри реальные материалы: изображения `designExample/` и актуальные снимки `docs/screenshots/` — инструментом просмотра изображений, не по именам файлов. Новое решение должно быть неотличимо по системе от существующего интерфейса. +Ты senior product designer шахматного аналитического приложения. Прочитай AGENTS.md, ТЗ и релевантные изображения designExample через инструмент просмотра изображений. Изучай референсы визуально, а не только по именам файлов. Пиши и сохраняй результаты по-русски в назначенные файлы. -Методика на каждый экран или изменение: +Рабочая методика: +1. Определи основную задачу экрана и приоритет информации. +2. Опиши пользовательский путь, переходы и сохранение контекста между библиотекой и партией. +3. Сделай wireframe и объясни размещение доски, нотации, вариантов, комментариев и анализа. +4. Опиши конкретные компоненты, размеры, плотность, типографику, цвета и состояния. Избегай декоративного dashboard-дизайна, огромных карточек и градиентов без функции. +5. Проверь пустые, загрузочные, ошибочные, переполненные состояния и несохранённые изменения; протестируй компоновку мысленно на небольшом окне и HiDPI. +6. Задай клавиатурную навигацию, фокус, tooltip, видимую выбранную позицию и читаемость без опоры только на цвет. -1. Задача экрана и приоритет информации — одной фразой, до макета. -2. Пользовательский путь и сохранение контекста (библиотека ⇄ партия, возврат из предпросмотра). -3. Компоновка: доска, нотация, варианты, комментарии, анализ; обоснуй размещение каждого элемента. -4. Конкретика: компоненты, плотность, типографика, цвета, отступы, состояния. Без декора ради декора: никаких бесполезных карточек, градиентов и dashboard-стилистики. -5. Матрица состояний: пустое, загрузка, ошибка, переполнение, несохранённые изменения, узкое окно, HiDPI, большие базы. -6. Клавиатура: полная карта клавиш и фокуса, tooltip, видимая активная позиция, читаемость без опоры только на цвет. +Доска и чтение аннотированной партии — центр продукта. Основная линия, побочные ветки, комментарии и NAG должны оставаться понятными при глубоком вложении. Предпросмотр PV движка должен визуально отличаться от партии и иметь очевидный возврат. Активная позиция, выбранная строка и раскрытая ветка — разные состояния. -Независимая визуальная приёмка после реализации: - -- Ревьюер — отдельный агент, не автор макета или кода изменения. Он обязан запустить приложение в изолированных настройках и посмотреть реальные снимки, а не оценивать вёрстку только по коду. -- Обязательны сравнение с главным экраном и экраном партии, широкое и узкое окно, пустые и заполненные состояния, HiDPI в доступном окружении. Проверять типографику, отступы, выравнивание, одинаковые размеры кнопок и строк, читаемость выделения. -- Отдельно проверять последовательность состояний: выбор строки, запуск, завершение, возврат, появление статистики и фоновых сообщений. Размеры блоков не должны скачком меняться без явного действия пользователя; любое изменение высоты фиксировать на серии снимков. -- Вердикт подтверждать ссылками на снимки, размером и состоянием каждого. Общее «всё ровно» без визуальных доказательств не считается приёмкой. Дефекты записывать конкретно: место, ожидаемое/фактическое выравнивание, шаги воспроизведения. - -Центр продукта — доска и чтение аннотированной партии: основная линия, ветки, комментарии и NAG остаются понятными при глубоком вложении; предпросмотр PV движка визуально отличим от партии и имеет очевидный выход. Активная позиция, выбранная строка и раскрытая ветка — три разных состояния, не сливать их. - -Ограничения egui проверяй по документации и исходникам (перенос rich text, hit testing ходов, виртуализация таблиц, clipboard, диалоги, звук, SVG, IME). Сомнительную возможность не утверждай — предложи проверяемый UI-прототип. Код меняешь только по прямому назначению оркестратора; чужие фирменные ресурсы без проверки происхождения не копируешь. - -Отчёт: решения с обоснованием · макеты и состояния · требования к реализации для разработчика · что передать тестировщику. +Учитывай нативные ограничения выбранного Rust UI: перенос rich text, hit testing ходов, виртуализация таблиц, clipboard, диалоги, звук, SVG, IME. Предлагай проверяемый UI-прототип для сомнительных возможностей. Код приложения меняй только по прямому назначению оркестратора. Не скачивай случайные skills и не копируй фирменные ресурсы без проверки происхождения. diff --git a/.opencode/agents/developer.md b/.opencode/agents/developer.md index cfedea2..de12148 100644 --- a/.opencode/agents/developer.md +++ b/.opencode/agents/developer.md @@ -4,25 +4,12 @@ mode: subagent color: "#E5AC57" --- -Ты senior Rust-разработчик ChessPenguin. Читай AGENTS.md, `docs/architecture.md`, `docs/decisions.md` и dev-доки назначенной области (`docs/dev/`). UI-фреймворк без объяснения и согласования не меняешь; работаешь только в назначенных файлах. +Ты senior Rust desktop разработчик. Читай AGENTS.md, ТЗ, согласованные решения docs/architecture.md и связанные требования. Не выбирай другой UI-фреймворк без объяснения и согласования. Работай только в назначенной области. -Дисциплина кода: +Держи шахматную модель и PGN независимо от UI. Используй проверенную библиотеку правил; самостоятельно проектируй дерево документа, привязку комментариев и сериализацию. Различай идентификатор узла, позицию, историю ходов, активную ветку и временный preview анализа. Проектируй семантический roundtrip PGN с сохранением исходного текста для неизменённых игр. -- Сначала читай существующий код области и следуй его идиомам: стиль файла важнее личных предпочтений. Без абстракций «на вырост» и без комментариев-извинений — код и история говорят сами. -- `unwrap`/`expect`/`panic` на пользовательских данных и границах ввода запрещены: `Result` на границах, ошибки типизированные (thiserror), с понятным текстом для пользователя. -- Зависимость добавляешь только после проверки версии и лицензии и убедившись, что существующие зависимости нужду не покрывают; фиксируешь по стилю workspace. +UCI реализуй как явную машину состояний, с отдельным процессом, асинхронным чтением stdout/stderr, контролем stop/bestmove, таймаутами, MultiPV, типизированными опциями и привязкой результатов к поиску. Сначала завершай старый поиск, затем начинай новый: внутренний request ID не добавляет идентификатор в сам протокол UCI. Не вызывай движок через shell-строку. Завершай процессы при закрытии документа и приложения. -Предметные инварианты (нарушать нельзя): +Отделяй индекс библиотеки от исходного PGN; учитывай изменение файла, отмену импорта, пагинацию и атомарную запись. Не читай большую базу целиком в UI-потоке. Обрабатывай Result на границах; не применяй unwrap к пользовательским данным. Избегай абстракций ради гипотетических функций. -- Шахматная модель и PGN независимы от UI. Дерево документа — стабильные NodeId, один шаг Undo на операцию. Различай идентификатор узла, позицию, историю ходов, активную ветку и временный preview анализа. -- Исходные байты PGN/ChessBase сохраняются; roundtrip — семантический, с диагностикой; побайтовую идентичность после редактирования не обещаем. -- UCI — только через крейт `uci`: сначала завершить старый поиск (bestmove, затем readyok), потом начинать новый; таймауты, MultiPV, типизированные опции, движок не через shell-строку, процессы завершать при закрытии документа и приложения. -- Тяжёлая работа не в UI-потоке: фоновые потоки, прогресс, отмена, наружу — события. - -Ворота качества — обязательны, с фактическим выводом в отчёте: - -- `cargo fmt`, `cargo clippy` без предупреждений в тронутых крейтах, `cargo test -p ` зелёные. Сломать существующий тест нельзя; падающий до тебя тест фиксируешь и сообщаешь, чужое молча не «чинишь». -- Поведенческие изменения — с тестами: ошибки данных, отмена, конкурентность, roundtrip. UI проверенным объявляешь только после реального запуска (dev-хуки `CP_*`, снимок), не «на глаз» по коду. -- Замеры производительности с методикой и оборудованием; цели не выдаёшь за результаты. - -Отчёт: изменённые файлы · команды проверки и их итог (скопированный вывод) · принятые решения и почему · непроверенное · вопросы. +Проверяй доступные API по документации и исходникам, фиксируй версии и лицензии зависимостей. Для изменений запускай подходящие cargo fmt/check/clippy/test или объясняй блокер. Добавляй значимые тесты на ошибки данных и конкурентность. Отчитывайся о точных командах и фактических результатах; не объявляй UI проверенным без запуска. diff --git a/.opencode/agents/orchestrator.md b/.opencode/agents/orchestrator.md index c6635d2..1269bd5 100644 --- a/.opencode/agents/orchestrator.md +++ b/.opencode/agents/orchestrator.md @@ -4,14 +4,10 @@ mode: primary color: "#5B8DEF" --- -Ты оркестратор ChessPenguin — серьёзного локального шахматного приложения (Rust + egui; релизы на Linux, Windows, macOS, Android). Общайся по-русски. До первого вывода прочитай: AGENTS.md (инварианты продукта), `docs/dev/tasks.md` (что в работе), `docs/decisions.md` (что решено; решения пользователя не переоткрываем), `docs/architecture.md` (устройство системы). ТЗ и `docs/research/` — за исходной постановкой и историей. +Ты оркестратор Linux-приложения для шахматных баз и анализа. Общайся по-русски. Сначала прочитай AGENTS.md, исходное ТЗ и актуальную сводку docs/architecture.md, если она существует. -Твоя работа — доводить до проверенного результата, а не до активности: +Выясняй цель текущего этапа: исследование, согласование, реализация или проверка. Предлагай конкретное решение с аргументами, учитывая желание пользователя использовать стек Artcraft. Не выдавай собственную рекомендацию за решение пользователя. -1. Определи ближайший проверяемый результат и назови его пользователю до начала работы. -2. Делегируй независимые части агентам analyst, designer, developer, tester: каждой — отдельные файлы без пересечений, в задании — цель, известные пути и факты, ожидаемый артефакт. Не дублируй их исследования своими и не делай их работу за них. После UI-реализации отдельно назначай дизайн-ревьюера, который не писал эту реализацию: обязательны реальные скриншоты, сравнение с основными экранами и проверка отсутствия скачков между состояниями. -3. Интегрируй только проверенное: утверждение агента принимай как гипотезу, пока не увидел доказательства (команда, её вывод, файл:строка). Ключевое и спорное перепроверяй сам. -4. Закрывая задачу, обновляй `docs/dev/tasks.md`, при существенных решениях — `docs/decisions.md`; в отчёте различай: сделано / проверено / рекомендовано / ждёт ответа пользователя. -5. Продуктовые решения предлагай вариантами с рекомендацией и ценой каждого; свою рекомендацию не выдавай за решение пользователя. Объём без согласования не расширяй. +Делегируй независимые задачи агентам analyst, designer, developer и tester. Если инструменты текущей сессии ещё не показывают эти профили, используй general с полным контекстом роли и сообщи об этом. Назначай отдельные файлы и ожидаемый результат, не запускай дублирующее исследование. Сам интегрируй результаты, устраняй противоречия, поддерживай docs/architecture.md. Сохраняй существенные решения, открытые вопросы и следующий проверяемый шаг. -Если инструменты текущей сессии не показывают профили команды, используй субагентов общего назначения с полным текстом роли из `.opencode/agents/<роль>.md` и скажи об этом пользователю. Активный сервис (OpenCode, Kimi Code) самостоятельно не перезапускай. +Для реализации выбирай небольшой сквозной сценарий с работающим UI и реальными PGN. Перед расширением функций получай независимую проверку тестировщика. В конце различай выполненное, проверенное, рекомендованное и требующее ответа пользователя. Не перезапускай активный OpenCode самостоятельно. diff --git a/.opencode/agents/tester.md b/.opencode/agents/tester.md index e9a909a..691d6b3 100644 --- a/.opencode/agents/tester.md +++ b/.opencode/agents/tester.md @@ -4,16 +4,12 @@ mode: subagent color: "#E87575" --- -Ты инженер качества ChessPenguin. Пиши по-русски. Читай AGENTS.md, назначенное изменение и профильные dev-доки. Приоритет — реальные, воспроизводимые дефекты, а не число тестов. Независимость главная: отчёты разработчика и оркестратора — гипотезы, не доказательства; всё ключевое воспроизводишь сам, с нуля, по шагам. +Ты инженер качества шахматного desktop-приложения. Читай AGENTS.md, требования и изменённые файлы. Пиши по-русски. Приоритет — реальные дефекты и воспроизводимость, а не число тестов. -Предметные чек-листы: +Проверяй на реальных примерах и малых синтетических fixtures: RAV с несколькими уровнями, FEN и ход чёрных, комментарии у корня/ходов/ветвей, NAG, нестандартные теги, кодировки, усечённые данные, рокировки, en passant, превращения, мат, пат, повторение. Roundtrip сравнивай семантически; отдельно проверяй сохранение неизменённых исходных данных. -- PGN и дерево: RAV нескольких уровней, FEN и ход чёрных, комментарии у корня/ходов/ветвей, NAG, нестандартные теги, legacy-кодировки, усечённые данные, рокировки, en passant, превращения, мат, пат, повтор позиции. Roundtrip сравнивай семантически; отдельно проверяй, что неизменённый исходник уцелел побайтово. -- UCI: детерминированный fake engine, воспроизводящий задержки, устаревший `info` после `bestmove`, отсутствие `readyok`, мусорные строки, MultiPV, мат и завершение процесса. Реальный Stockfish — дополнительная интеграция, а не замена управляемым сценариям гонок. -- UI и сценарии: переход библиотека—партия—библиотека, клавиатура и фокус, предпросмотр PV без изменения документа, отмена операций, экспорт, восстановление после аварии; Wayland/X11 и HiDPI в доступном окружении. +Для UCI используй детерминированный fake engine, который воспроизводит задержки, старый info, отсутствие readyok, некорректные строки, MultiPV, мат и завершение процесса. Реальный Stockfish — дополнительная интеграция, а не замена управляемым сценариям гонок. -Оформление дефекта — строго: серьёзность · окружение и версия · шаги · ожидаемое и фактическое поведение · файл/строка · минимальный пример воспроизведения. Не воспроизвёл — не репортишь: пишешь «не подтвердилось» с перечнем проверок. Производительность: фиксируешь оборудование, размер входа, методику и измерения; цели не называешь результатами. +Проверяй переход библиотека—партия—библиотека, клавиатуру и фокус, preview PV без изменения документа, отмену операций, экспорт, восстановление и Linux Wayland/X11/HiDPI в доступном окружении. Для производительности фиксируй оборудование, размер входа, методику и измерение; цели не называй результатами. -Границы: production-код без задания не исправляешь; неподтверждённые бинарники не запускаешь; пользовательские PGN и базы не изменяешь — работаешь на копиях; внешние тестовые библиотеки не публикуешь без выяснения условий распространения. - -Отчёт: проверено (чем и каким сценарием) · дефекты (по формату) · не подтвердилось · непроверенное — явным списком · оценка рисков остатка. +Не запускай неподтверждённые бинарники и не изменяй пользовательские PGN. Не исправляй production-код в ревью без задания. На дефект указывай серьёзность, шаги, ожидаемое/фактическое поведение, файл/строку и минимальный пример. Явно перечисляй непроверенное. Внешние тестовые библиотеки не публикуй без выяснения условий их распространения. diff --git a/AGENTS.md b/AGENTS.md index 914434b..ce28f80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,27 +5,21 @@ - Исходное ТЗ: `техническое задание.txt`. - Пользовательские материалы: `designExample/`, `pgnFilesforExample/`, `engines/`. - Рабочий язык обсуждений и проектных заметок — русский; идентификаторы кода — английский. -- Текущий этап: развитие выпускаемого продукта (релиз 2.5.2). Задачи и бэклог — `docs/dev/tasks.md`. -- Архитектура реализованной системы: `docs/architecture.md`; архитектурное предложение этапа исследования — `docs/research/architecture-proposal-2026-10-17.md`; исследования: `docs/research/`. -- Журнал решений: `docs/decisions.md`; подтверждённые пользователем решения имеют приоритет над предложениями исследований. +- Текущий этап: исследование и согласование архитектуры. Рекомендация не равна утверждённому решению. +- Сводка решений: `docs/architecture.md`; исследования: `docs/research/`. +- Подтверждённые пользователем границы первой версии: `docs/decisions.md`; они имеют приоритет над ранними предложениями исследований. ## Команда Оркестратор распределяет независимые задачи между `analyst`, `designer`, `developer`, `tester`, согласует результаты и обсуждает продуктовые решения с пользователем. Делегирование разрешено. Дочерние агенты не создают дополнительные уровни команды без необходимости. - Аналитик поддерживает требования, реальные особенности PGN и критерии приёмки. -- Дизайнер отвечает за сценарии, компоновку, состояния, клавиатуру и визуальную систему. После UI-реализации отдельный дизайн-ревьюер, не автор реализации, проверяет её на реальных снимках приложения: сравнение с главным экраном и экраном партии, выравнивание, размеры и состояния, отсутствие скачков при переходах и появлении данных. Одного чтения кода и тестов для визуальной приёмки недостаточно. +- Дизайнер отвечает за сценарии, компоновку, состояния, клавиатуру и визуальную систему. - Разработчик отвечает за Rust, архитектуру, хранение, PGN и UCI. - Тестировщик независимо проверяет поведение и сообщает конкретные воспроизводимые дефекты. Каждой параллельной задаче назначать собственные файлы. Не перезаписывать работу другого агента. В отчёте указывать изменения, проверки и нерешённые вопросы. -### Механика в Kimi Code - -Канонические профили ролей — файлы `.opencode/agents/*.md` (orchestrator, analyst, designer, developer, tester); содержимое нейтрально к среде исполнения. Kimi Code не регистрирует собственные типы субагентов, и субагент стартует «холодным», поэтому роль передаётся в задании: ссылка на файл профиля («прочитай и следуй ему») плюс цель, уже известные пути и факты, назначенные файлы и ожидаемый результат. - -Тип субагента выбирается по требуемым инструментам: `coder` — ролям, которым нужно править файлы или запускать команды (developer, tester; analyst и designer при записи результатов в docs/); `plan` — read-only планирование и проектирование; `explore` — быстрое read-only исследование без записи файлов. Оркестратор — основная сессия; его рабочие правила — в `.opencode/agents/orchestrator.md`. - ## Инварианты продукта - Локальное приложение для просмотра, ввода и анализа шахматных партий, с PGN как форматом обмена. @@ -40,8 +34,4 @@ ## Работа -Окна приложения для тестов и снимков запускать только через `scripts/dev/headless-run.sh -- ENV=… команда` (невидимый монитор Hyprland 1920×1080, без фокуса и курсора владельца); прямой запуск окна на мониторах владельца запрещён. Не запускать и не подменять службы сессии владельца (AT-SPI, D-Bus, порталы, ydotool и т. п.) для эмуляции ввода; нужное действие — через отладочный хук приложения. - -Экономия (владелец, 2026-11-27): визуальная проверка — одно разрешение 1920×1080 и основная (тёмная) тема; светлая — только если меняются цвета. Минимум снимков: только те, что доказывают критерий; не снимать серии и другие разрешения без нужды, не держать несколько агентов на проверке одного и того же. - -Не изменять исходное ТЗ и референсы. Не запускать неподтверждённые бинарники и незавершённые загрузки движков. Проверенные факты отделять от предложений; для внешних технических утверждений сохранять ссылки. Тестировать значимое поведение, особенно сохранность PGN и гонки UCI; не объявлять запланированные проверки выполненными. +Не изменять исходное ТЗ и референсы. Не запускать незавершённые загрузки движков. Не устанавливать инструменты и не начинать большой каркас приложения до выбора стека. Проверенные факты отделять от предложений; для внешних технических утверждений сохранять ссылки. Тестировать значимое поведение, особенно сохранность PGN и гонки UCI; не объявлять запланированные проверки выполненными. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9436f70..e1e9df2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,182 +4,6 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https ## [Unreleased] -## [2.5.2] — 2026-11-30 - -- Android: the «Analyse game» button is in the bottom bar next to the engine button and has the - brilliant-move colour. Tap the previous/next arrows to go one move, or hold them to jump to the - start/end of the line. -- Android: simple opponent preparation. Pick an exact player name from a database or an open game, - choose their colour, and study from your own side of the board. Continuations are shown by arrows - and a frequency-sorted list with game counts and the selected player's wins/draws/losses; play a move - on the board, from the list or with an arrow. Statistics use exact names, transpositions and main - lines only, without engine analysis or changing the source games. - -## [2.5.1] — 2026-11-28 - -- Desktop: select 1–100 games in a database and use «Find great moves» to analyse just those games. - The confirmation shows how many selected games are hidden by the current filter; those games are - included. Changing the selection after starting does not change the batch. Clear the selection to - analyse the filtered games instead. - -## [2.5.0] — 2026-11-27 - -- Desktop: find great moves in the filtered games of a database (up to 100). The «!! Find great moves» - button on the right of the conditions line asks first with a time estimate, then Stockfish 19 goes - through the games with «Analysed N of M» and «Stop»; games already analysed are taken from the cache. - The summary adds up brilliant, great, inaccuracy, mistake and blunder moves, average centipawn loss and - accuracy, and lists the brilliant moves; with a player in the filter only that player's moves count. - A new «!!» column marks games with brilliant or great moves. Games against the engine wait for the search. -- Desktop: select several games in a database (Ctrl/Shift-click, Shift+arrows, Ctrl+A) and make a new - database of them («New database from selected…», Ctrl+Shift+S). The copy runs in the background with - progress and cancel, never overwrites a file, keeps every game as «Add to database» does and skips only - exact duplicates; the source database is not changed. -- Desktop: a hint above the notation tells that arrows and circles can be drawn with the right mouse - button and are saved in PGN; moves with arrows or circles get a small sign in the notation. -- Desktop: the «Analyse game» button has the colour of a brilliant move. -- Desktop opening training: four example repertoires — Spanish and Queen's Gambit for White, Najdorf and - the Semi-Slav triangle for Black — with Russian comments in the Russian interface. Users who updated get - the missing examples once; deleted examples do not come back. The repertoire panel is wider by default, - names and progress are no longer cut, and side kings are drawn so White and Black read correctly on dark - backgrounds. -- Desktop: Enter in «Delete the game from the database?» no longer also opens the game. - -## [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. -- 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 - automatic moves. Previously displayed context is persisted in one atomic batch, - retaining every progress event without rewriting the entire history for each old move. -- Opening training displays the PGN author's move badges, arrows and marked squares - after the user's moves and during automatic playback, using the same appearance as - the game viewer. Annotations follow the displayed PGN node, including pauses and retries. -- All enabled repertoire variations can be trained, including several own answers in - one position. A pending alternative credits the move actually played; another known - answer is handled without an error penalty. Preferred moves affect order rather than - excluding alternatives. Shared position-and-move statistics remain deduplicated. - -## [2.2.0] — 2026-11-06 - -- Desktop opening training (α version): collect PGN repertoires, add a line from a game, and learn - one main answer per position for White or Black. Learning history and the SRS schedule - are shared between transpositions and repertoires. Three independent correct answers - mark a move as learnt without ending reviews; mistakes, previews and replays after an - error are recorded separately and do not inflate independent accuracy. Persistent v3 - JSON keeps atomic, idempotent session and event writes, migration backups and legacy data. -- Opening training has spaced repetition, ordered review and least-recent modes, four - learning priorities, and resumable sessions. Automatic context plays one move at a time - with fixed or knowledge-adaptive animation; reinforcement, preview and replay are distinct - from independent answers. Each repertoire stores its context policy, while an active session - keeps the policy it started with. The editor preserves PGN while changing the main answer, - training depth and disabled branches. -- The learning dashboard compares repertoires and their branches without double-counting - shared positions, and shows exact move analytics, daily history, scheduled reviews and - answer-sequence charts. Snapshots are captured automatically on the first daily view of - a scope without changing PGN or learning state. Full-line - statistics preserve shared moves on each actual PGN line while the global total deduplicates - them. The library table keeps ECO codes, opening names and the actual number of variations; - the training board has no move list. PGN annotations are preserved, but the new alpha - training screen does not yet display move badges, PGN arrows or marked squares. -- Training follows the main application's layout: clearer progress labels and settings, - consistent buttons, compact session controls and board rotation in the bottom toolbar. - The selected repertoire is ready to train on entry; its saved colour and mode are restored. - Progress saves in the background without a repeated status message or blocking the board. -- Moves no longer jump back after a drag while progress is being saved. A completed move - reused as the next task's context does not repeat its animation or sound. -- Opponent preparation ignores a player's later mistakes once their opponent has made the - first mistake. Saved reports and cached evaluations are rechecked without rerunning the engine. -- The main toolbar keeps its position and button appearance while the app starts and checks - the network. Online games can be opened immediately; connection status and retry are shown - inside that dialog. Startup spinners have been removed from the main screen. -- Android: when the app opens or returns to the foreground, a PGN in the clipboard can be - opened from a small confirmation dialog. One or several games are stored as a local copy, - and the first game always opens on the board. Opening or dismissing the same text is remembered - across restarts; an unsuccessful import can be retried. Clipboard checks are local, generation-safe, - limited to 8 MiB and never start an import without confirmation. - -## [2.1.5] — 2026-11-02 - -- Preparing against an opponent is saved by itself: a preparation appears in the - library's «Preparations» as soon as it is started, and its report and the errors - found are written there as they come. The «★ Save» button is gone. -- Preparing against an opponent: the engine starts looking for the opening errors - by itself once the report is built — progress on the Errors tab, «Stop» keeps the - evaluations and the search does not restart by itself after it; changing the depth - or the period starts it again. -- The book comparison has been removed from opponent preparation: its controls, - background work and book-exit statistics are gone. Old saved data remains readable. -- Preparing against an opponent: the game counts for White and Black line up, the - score percentage stays visible in the compact summary, and the error counts and - their game percentages have separate aligned columns. - -## [2.1.4] — 2026-10-31 - -(2.1.3 was not published: its macOS build was cancelled by GitHub retiring the macOS 14 -runners. 2.1.4 is the same release.) - - -- Preparing against an opponent: choose which of his games — all, the last 3 or 6 - months, a year or two (counted back from his newest game), or his last 50, 100 or 200 - games of each colour; every choice shows how many games it takes. Games without a date - are taken only with all games, and the report says how many were left out. -- Saved preparations: «★ Save» keeps a preparation with the errors found; «🗐 - Preparations» in the library opens, renames and deletes them. New games of the - database are added when it is opened again, and the engine looks only at what is new. -- A game downloaded from Lichess or Chess.com opens on the site: the globe after the - result, the ☰ menu or the game list's menu. A Lichess game opens at the move shown, - from the side at the bottom of the board. - -## [2.1.2] — 2026-10-31 - -- The game review runs on your own Stockfish when it is the same Stockfish 19 as - ChessPenguin's: checked once per engine file with three test searches against our - reference (move, score and node count), so the marks stay the same everywhere. Another - engine is told by name and why Stockfish 19 is needed; your engine stays for the - position analysis. Engines for playing (Rodent, Maia) are never used for the review. -- Desktop: files dropped on the window open as databases (PGN, ChessBase, archives, - several at once or a folder) — on Windows, macOS and X11; a Wayland session does not - take dropped files. -- Sizes are written in the interface's language («2,2 ГБ»). -- Less memory to check the encoding of a large PGN file. - -## [2.1.1] — 2026-10-29 - -- Brilliant moves (!!) also for the only good move that a shallow search misses, sacrifice - or not (as people see brilliance: a move a weak engine rates lower and a strong one - best). The game review adds a short search for the moves that could be such (1–2 % - longer). On chess.com's marks of 20 famous games: 90 % of their !! found, 95 % of ours - are theirs. -- Great moves (!) are surer: no ! for an attacked piece stepping quietly to its one good - square, nor for the king stepping out of check — 27 of our 28 ! are chess.com's. -- Website statistics count a file downloaded again the same day by the same visitor once. - -## [2.1.0] — 2026-10-28 - -- Desktop: preparing against an opponent. Pick a player of a database (similar names - shown apart, spellings can be joined) and get their opening repertoire: a tree of - their moves for each colour with opening names (the Lichess opening table), games, - score and the last game, a table of openings and variations with their first moves, - and — on request — the engine's look at their opening mistakes, by opening, with the - mistakes they repeat. A book from the shelf shows where they leave theory. Every - table sorts by its columns; the tree starts folded. -- The game review always uses the same engine search, on every computer and phone: - Stockfish 19 of ChessPenguin, one million nodes a position, one thread per engine - process and several processes side by side. The same game gets the same marks - everywhere; nothing to choose any more (the analysis dialog is gone). An analysis made - with other settings says so and offers «Update». -- Brilliant (!!) and great (!) moves recalibrated on chess.com's marks of 15 famous - games (a check set the program keeps): !! now agree with chess.com 96 % of the time. - Great moves are rarer and surer: never for a capture, only when every other move is - clearly worse; no ! or !! for a book move. -- The sample «Classic games» grow from 38 to 100 famous games; a new version of a - sample replaces the old one on update (desktop and Android). - ## [2.0.0] — 2026-10-28 - The databases downloaded from Lichess and Chess.com get the games played since on their diff --git a/Cargo.lock b/Cargo.lock index 094a952..7856ae4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -716,12 +716,6 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - [[package]] name = "cc" version = "1.8.0" @@ -774,18 +768,17 @@ dependencies = [ [[package]] name = "chess-core" -version = "2.5.2" +version = "2.0.0" dependencies = [ "encoding_rs", "pgn-reader", - "serde", "shakmaty", "thiserror 2.0.21", ] [[package]] name = "chess-import" -version = "2.5.2" +version = "2.0.0" dependencies = [ "chess-core", "encoding_rs", @@ -796,24 +789,14 @@ dependencies = [ "zip", ] -[[package]] -name = "chess-openings" -version = "2.5.2" -dependencies = [ - "chess-import", - "serde", - "shakmaty", -] - [[package]] name = "chesspenguin" -version = "2.5.2" +version = "2.0.0" dependencies = [ "arboard", "base64 0.22.1", "chess-core", "chess-import", - "chess-openings", "chrono", "directories", "eframe", @@ -824,12 +807,10 @@ dependencies = [ "game-review", "getrandom 0.3.4", "image", - "js-sys", "log", "maia", "online-games", "play", - "prep", "releases", "rfd", "rodio", @@ -840,31 +821,14 @@ dependencies = [ "skrifa", "sys-locale", "tar", - "thiserror 2.0.21", "trainer", "uci", "ureq", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "web-time", "whatlang", "winresource", "zip", ] -[[package]] -name = "chesspenguin-web" -version = "2.5.2" -dependencies = [ - "chesspenguin", - "eframe", - "log", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "chrono" version = "0.4.45" @@ -872,9 +836,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", - "js-sys", "num-traits", - "wasm-bindgen", "windows-link", ] @@ -1706,15 +1668,13 @@ dependencies = [ [[package]] name = "game-review" -version = "2.5.2" +version = "2.0.0" dependencies = [ "chess-core", - "chess-openings", "serde", "serde_json", "shakmaty", "uci", - "web-time", ] [[package]] @@ -1745,11 +1705,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" dependencies = [ "cfg-if", - "js-sys", "libc", "r-efi 5.3.0", "wasip2", - "wasm-bindgen", ] [[package]] @@ -2427,7 +2385,7 @@ dependencies = [ [[package]] name = "maia" -version = "2.5.2" +version = "2.0.0" dependencies = [ "serde_json", "shakmaty", @@ -2476,16 +2434,6 @@ dependencies = [ "unicase", ] -[[package]] -name = "minicov" -version = "0.3.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d" -dependencies = [ - "cc", - "walkdir", -] - [[package]] name = "minimal-lexical" version = "0.2.1" @@ -2514,7 +2462,7 @@ dependencies = [ [[package]] name = "mobile-api" -version = "2.5.2" +version = "2.0.0" dependencies = [ "chess-core", "chess-import", @@ -2660,15 +2608,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num-bigint" version = "0.4.8" @@ -3122,7 +3061,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "online-games" -version = "2.5.2" +version = "2.0.0" dependencies = [ "chess-core", "serde", @@ -3130,12 +3069,6 @@ dependencies = [ "ureq", ] -[[package]] -name = "oorandom" -version = "11.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" - [[package]] name = "option-ext" version = "0.2.0" @@ -3395,7 +3328,7 @@ checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" [[package]] name = "play" -version = "2.5.2" +version = "2.0.0" dependencies = [ "chess-core", "getrandom 0.3.4", @@ -3494,19 +3427,6 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1" -[[package]] -name = "prep" -version = "2.5.2" -dependencies = [ - "chess-core", - "chess-import", - "chess-openings", - "game-review", - "serde", - "serde_json", - "uci", -] - [[package]] name = "presser" version = "0.3.1" @@ -3695,7 +3615,7 @@ dependencies = [ [[package]] name = "releases" -version = "2.5.2" +version = "2.0.0" dependencies = [ "serde_json", "ureq", @@ -4446,10 +4366,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" dependencies = [ - "js-sys", "libc", - "wasm-bindgen", - "web-sys", ] [[package]] @@ -4693,13 +4610,12 @@ dependencies = [ [[package]] name = "trainer" -version = "2.5.2" +version = "2.0.0" dependencies = [ "chess-core", "chrono", "serde", "serde_json", - "web-time", ] [[package]] @@ -4736,16 +4652,10 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" [[package]] name = "uci" -version = "2.5.2" +version = "2.0.0" dependencies = [ - "js-sys", "libc", "thiserror 2.0.21", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-bindgen-test", - "web-sys", - "web-time", ] [[package]] @@ -5116,45 +5026,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-bindgen-test" -version = "0.3.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42" -dependencies = [ - "async-trait", - "cast", - "js-sys", - "libm", - "minicov", - "nu-ansi-term", - "num-traits", - "oorandom", - "serde", - "serde_json", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-bindgen-test-macro", - "wasm-bindgen-test-shared", -] - -[[package]] -name = "wasm-bindgen-test-macro" -version = "0.3.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "wasm-bindgen-test-shared" -version = "0.2.129" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe" - [[package]] name = "wayland-backend" version = "0.3.17" diff --git a/Cargo.toml b/Cargo.toml index 1884f98..ede3ac0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,6 @@ members = [ "crates/chess-core", "crates/chess-import", "crates/uci", - "crates/openings", "crates/game-review", "crates/online-games", "crates/releases", @@ -12,13 +11,11 @@ members = [ "crates/maia", "crates/trainer", "crates/play", - "crates/prep", "apps/desktop", - "apps/web", ] [workspace.package] -version = "2.5.2" +version = "2.0.0" edition = "2024" rust-version = "1.97" license = "GPL-3.0-or-later" @@ -31,8 +28,6 @@ shakmaty = "0.30.2" pgn-reader = "0.29.1" encoding_rs = "0.8" thiserror = "2" -# `Instant`/`SystemTime` that also work in a browser (std's panic there). -web-time = "1.1" serde = { version = "1", features = ["derive"] } serde_json = "1" egui = "=0.36.2" @@ -48,20 +43,10 @@ chess-import = { path = "crates/chess-import" } uci = { path = "crates/uci" } maia = { path = "crates/maia" } game-review = { path = "crates/game-review" } -chess-openings = { path = "crates/openings" } online-games = { path = "crates/online-games" } releases = { path = "crates/releases" } trainer = { path = "crates/trainer" } play = { path = "crates/play" } -prep = { path = "crates/prep" } [profile.dev.package."*"] opt-level = 2 - -# The web version (apps/web/build.sh): small to download, the release otherwise. -[profile.web] -inherits = "release" -opt-level = "s" -lto = "fat" -codegen-units = 1 -panic = "abort" diff --git a/README.md b/README.md index bbcb8ad..bd752f8 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,8 @@

ChessPenguin

- A chess database for Linux, Windows, macOS and Android: open PGN and ChessBase collections, - read annotated games, enter your own, analyse them with Stockfish, prepare against an - opponent and play against the computer. + A native chess database for Linux: open PGN collections, read annotated games, + enter your own and analyse them with Stockfish or any UCI engine.

@@ -15,7 +14,7 @@ Русский

-![A game with its review](docs/screenshots/game.png) +![Analysis](docs/screenshots/analysis.png) ## Features @@ -29,24 +28,11 @@ - **Notation** — main line as a two-column table, comments and variations as blocks, mouse and keyboard navigation. - **Stockfish included** — analysis works right after installation; other UCI engines can be added. -- **Reference** — the moves played from the current position in a database of your shelf - (a big one for theory) with their statistics, how long the game stays in it, the - strongest games that reached it. -- **Search by position** — set up moves on a board and filter a database of millions of - games by the position, next to filters by player, years, rating, opening and result. - **Engine analysis** — any UCI engine, up to 5 lines, best-move arrows, evaluation bar; search time, threads and memory are set right in the analysis panel. -- **Game review** — evaluate the whole game in the background: evaluation graph under the board, +- **Game analysis** — evaluate the whole game in the background: evaluation graph under the board, accuracy, inaccuracies, mistakes and blunders per player and per game phase (Lichess method), - **brilliant (!!) and great (!) moves** calibrated on chess.com's marks of famous games, better - moves in the notation and marks on the board; write it into the game as NAGs, comments and - `[%eval]` (undoable). The review always runs the same engine search, so a game gets the same - marks on every computer and phone. -- **Preparing against an opponent** — pick a player of a database and see their opening - repertoire for each colour: a tree of their moves with opening names, games, score and the - last game, a table of openings and variations with their first moves, where they leave - theory; on request the engine finds their opening mistakes, by opening, with the ones they - repeat. Every table sorts by its columns. + better moves in the notation; write it into the game as NAGs, comments and `[%eval]` (undoable). - **Engine lines on the board** — step through a line without touching the game, add it as a variation with one click (undoable). - **Editing** — enter moves and variations, promote or delete lines, undo/redo, @@ -75,24 +61,16 @@ player's database. Maia (316 MB) and Rodent (48 and 70 MB) are downloaded on request. - **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets, dark and light themes. -- **Online games** — download anyone's games from Lichess and Chess.com by nickname (yours, a pupil's, an opponent's; no login) into a database, both sites merged or one per site; new games arrive by themselves. -- **100 classic games** built in — from Anderssen and Morphy to Carlsen, the famous ones - with short introductions; the sample databases update with the program. -- **Android app** — databases and games in the same formats, moves on the board, your own - databases, game review with !! and !, play against Maia, learning an opening. +- **Online games** — download anyone's games from Lichess and Chess.com by nickname (yours, a pupil's, an opponent's; no login) into a database, both sites merged or one per site, and fetch the new ones with one click. - **Languages** — English, Русский, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша. -| Preparing against an opponent | Game review: report, !! and ! | +| Game analysis: graph and report | Engine marks and better lines | | --- | --- | -| ![Preparing against an opponent](docs/screenshots/prep-openings.jpg) | ![Game review](docs/screenshots/review.png) | -| **Engine analysis** | **Reference: what was played here** | -| ![Engine analysis](docs/screenshots/engine.jpg) | ![Reference](docs/screenshots/reference.jpg) | -| **Library with filters** | **Search by position** | -| ![Library](docs/screenshots/library.png) | ![Search by position](docs/screenshots/position-search.jpg) | -| **Play against the computer** | **Android** | -| ![Play](docs/screenshots/play.jpg) | ![Android](docs/screenshots/android.jpg) | -| **Boards, pieces and a light theme** | | -| ![Looks](docs/screenshots/looks.jpg) | | +| ![Game analysis](docs/screenshots/review.png) | ![Engine marks](docs/screenshots/marks.png) | +| **Engine settings in the analysis panel** | **Library** | +| ![Engine settings](docs/screenshots/engine.png) | ![Library](docs/screenshots/library.png) | +| **Boards and pieces** | | +| ![Settings](docs/screenshots/settings.png) | | ## Install @@ -107,7 +85,7 @@ Packages for every release are on the [Releases](https://github.com/vrubelroman/ | Flatpak | `flatpak install --user ChessPenguin--x86_64.flatpak` | | Windows | unzip `ChessPenguin--windows-x86_64.zip`, run `ChessPenguin.exe` | | macOS (Apple Silicon) | open `ChessPenguin--macos-arm64.dmg`, drag ChessPenguin to Applications | -| Android 12+ | open `ChessPenguin--android.apk` (Stockfish built in) or `…-android-noengine.apk` (Stockfish downloaded in the app) on the phone | +| Android 12+ (alpha) | open `ChessPenguin--android.apk` (Stockfish built in) or `…-android-noengine.apk` (Stockfish downloaded in the app) on the phone | On macOS the app is not signed by Apple yet: the first time, right-click ChessPenguin in Applications and choose **Open** (on macOS 15: System Settings → Privacy & Security → Open Anyway). @@ -117,10 +95,10 @@ official Stockfish 19 (about 80 MB, checked before use, installed for your accou button is also in **Settings → Engines**. A `stockfish` installed on the system is found automatically, any other UCI engine can be added from a file. The Flatpak includes Stockfish. -The **Android app** opens databases and games (the same formats), with the notation under the -board and Stockfish. Moves are made on the board (variations, undo); your own databases live on -the phone; game review with !! and !; play against Maia and Rodent IV; learn an opening up to a -move. The two APKs install over each other; databases and settings are kept. +The **Android app** (alpha) opens databases and games (the same formats), with the notation under +the board and Stockfish. Moves are made on the board (variations, undo); your own databases live on +the phone; play against Maia (the small model, no clocks; games kept in the player's database) and learn an opening up to a move. The two +APKs install over each other; databases and settings are kept. ### Build from source diff --git a/README.ru.md b/README.ru.md index b4a00ef..5b233aa 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,14 +1,11 @@ # ChessPenguin -Шахматная база для Linux, Windows, macOS и Android: открывайте сборники PGN и ChessBase, читайте -аннотированные партии, вводите свои, анализируйте их со Stockfish, готовьтесь к сопернику и -играйте с компьютером. +Нативная шахматная база для Linux: открывайте PGN-сборники, читайте аннотированные партии, +вводите свои и анализируйте их со Stockfish или любым UCI-движком. [English](README.md) · [Скачать](https://github.com/vrubelroman/chessPenguin/releases/latest) -![Партия с разбором](docs/screenshots/game.png) - -Скриншоты — английского интерфейса; в программе девять языков, русский среди них. +![Анализ](docs/screenshots/ru/analysis.png) ## Возможности @@ -20,22 +17,11 @@ (windows-1251, windows-1252, KOI8-R, CP866) и учебные нулевые ходы `--`. Исходные файлы не изменяются. - **Нотация** — основная линия таблицей в две колонки, комментарии и варианты блоками, навигация мышью и клавиатурой. -- **Справочник** — какие ходы делали из текущей позиции в базе с полки (для теории — в большой), - их статистика, сколько партия держится в базе, сильнейшие партии с этой позицией. -- **Поиск по позиции** — расставьте ходы на доске и отфильтруйте базу на миллионы партий по - позиции, рядом — фильтры по игроку, годам, рейтингу, дебюту и результату. - **Анализ движком** — любой UCI-движок, до 5 линий, стрелки лучших ходов, шкала оценки; время, потоки и память настраиваются прямо в панели анализа. -- **Разбор партии** — оценка всей партии в фоне: график под доской, точность, неточности, ошибки - и зевки каждого игрока и по стадиям партии (методика Lichess), **блестящие (!!) и - замечательные (!) ходы**, сверенные с отметками chess.com на известных партиях, лучшие ходы в - нотации и значки на доске; запись разбора в партию знаками, комментариями и `[%eval]` (с - отменой). Разбор всегда идёт на одних и тех же параметрах движка, поэтому у партии одинаковые - отметки на любом компьютере и телефоне. -- **Подготовка к сопернику** — выберите игрока базы и посмотрите его дебютный репертуар за белых и - за чёрных: дерево его ходов с названиями дебютов, партиями, счётом и датой последней партии, - таблица дебютов и вариантов с первыми ходами, где он уходит из теории; по кнопке движок находит - его ошибки в дебютах — по дебютам и те, что он повторяет. Все таблицы сортируются по колонкам. +- **Анализ партии** — оценка всей партии в фоне: график под доской, точность, неточности, ошибки + и зевки каждого игрока и по стадиям партии (методика Lichess), лучшие ходы в нотации; + запись анализа в партию знаками, комментариями и `[%eval]` (с отменой). - **Линии движка на доске** — просмотр линии без изменения партии и вставка её вариантом (с отменой). - **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор, копирование PGN/FEN, сохранение партии в новый файл. @@ -51,24 +37,16 @@ в проигранной позиции соперник предлагает сдаться. Сыгранные партии сами записываются в базу игрока. Maia (316 МБ) и Rodent (48 и 70 МБ) скачиваются по кнопке. - **Оформление** — 17 наборов фигур, 37 досок (цвета и текстуры), 7 наборов звуков, тёмная и светлая тема. -- **Онлайн-партии** — партии любого игрока с Lichess и Chess.com по нику (без входа) в базу; новые партии приходят сами. -- **100 классических партий** встроены — от Андерсена и Морфи до Карлсена, знаменитые — с - короткими введениями; встроенные базы обновляются вместе с программой. -- **Приложение для Android** — базы и партии тех же форматов, ходы на доске, свои базы, разбор - партии с !! и !, игра с Maia, изучение дебюта. +- **Ваши онлайн-партии** — загрузка своих партий с Lichess и Chess.com по нику (без входа) в базу и обновление одной кнопкой. - **Языки** — English, Русский, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша. -| Подготовка к сопернику | Разбор партии: отчёт, !! и ! | +| Анализ партии: график и отчёт | Отметки движка и лучшие варианты | | --- | --- | -| ![Подготовка к сопернику](docs/screenshots/prep-openings.jpg) | ![Разбор партии](docs/screenshots/review.png) | -| **Анализ движком** | **Справочник: что здесь играли** | -| ![Анализ движком](docs/screenshots/engine.jpg) | ![Справочник](docs/screenshots/reference.jpg) | -| **Библиотека с фильтрами** | **Поиск по позиции** | -| ![Библиотека](docs/screenshots/library.png) | ![Поиск по позиции](docs/screenshots/position-search.jpg) | -| **Игра с компьютером** | **Android** | -| ![Игра](docs/screenshots/play.jpg) | ![Android](docs/screenshots/android.jpg) | -| **Доски, фигуры и светлая тема** | | -| ![Оформление](docs/screenshots/looks.jpg) | | +| ![Анализ партии](docs/screenshots/ru/review.png) | ![Отметки движка](docs/screenshots/ru/marks.png) | +| **Настройки движка в панели анализа** | **Библиотека** | +| ![Настройки движка](docs/screenshots/ru/engine.png) | ![Библиотека](docs/screenshots/ru/library.png) | +| **Доски и фигуры** | | +| ![Настройки](docs/screenshots/ru/settings.png) | | ## Установка @@ -81,9 +59,8 @@ Stockfish 19 (около 80 МБ, проверяется перед запуск в **Настройки → Движки**. Установленный в системе `stockfish` находится сам, другие UCI-движки добавляются из файла. Во Flatpak Stockfish уже есть. -**Android 12+:** базы и партии (те же форматы), нотация под доской, Stockfish; ходы на доске -(варианты, отмена), свои базы на телефоне, разбор партии с !! и !, игра с Maia и Rodent IV, -изучение дебюта. +**Android 12+ (альфа-версия):** базы и партии (те же форматы), нотация под доской, Stockfish; ходы на доске +(варианты, отмена), свои базы на телефоне, игра с Maia (малая модель, без часов; партии сами пишутся в базу игрока) и изучение дебюта. Две сборки: `ChessPenguin-<версия>-android.apk` — Stockfish уже внутри, `…-android-noengine.apk` — Stockfish скачивается в приложении. Ставятся одна поверх другой, базы и настройки сохраняются. diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index c0403f8..136f4e8 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -149,39 +149,6 @@ platform into the user's data directory and checks its SHA-256 (pinned in Open Database License (ODbL). - ChessPenguin runs Stockfish as a separate process over the UCI protocol. -### Stockfish.js (the web version) - -The web version (`/app/` on the site) uses **Stockfish.js 19.0.1** by Nathan Rugg and Chess.com -(https://github.com/nmrugg/stockfish.js), its single-threaded build `stockfish-19-single.js` + -`stockfish-19-single.wasm`, unmodified, from the npm package `stockfish@19.0.1` -(https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz, integrity -`sha512-bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ==`, -checked by `apps/web/build.sh`). It is Stockfish 19 compiled to WebAssembly with the network -`nn-1a298aa575a0` built in. Our site serves the files beside the program (`/app/engine/`, with the -package's `Copying.txt`); the browser downloads the `.wasm` only when the user agrees and keeps it -in its Cache Storage; it runs in Web Workers over UCI. - -- License: GNU General Public License version 3 (the engine; `Copying.txt`); the JavaScript - wrapper as published in the package. -- Source code: https://github.com/nmrugg/stockfish.js/tree/v19.0.1 (the build scripts and the - emscripten glue) and the Stockfish source above. - -## Opening names (preparing against an opponent) - -`crates/openings/data/a.tsv` … `e.tsv` are the five files of the Lichess opening table -https://github.com/lichess-org/chess-openings (the lichess.org contributors), downloaded -unmodified at revision `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27) on 2026-10-28 and -embedded in the program. Its README: "As a collection of facts, this data set is in the public -domain … released under the CC0 Public Domain Dedication" (CC0 1.0). SHA-256 of the files: - -| File | SHA-256 | -| --- | --- | -| `a.tsv` | `3282e4c9155289a29224f9a85fba0decb46efa35c2fa5e39662d2ac48fb0f793` | -| `b.tsv` | `4bf2269a8e7571a00a7b346bae4fa86a241a6e7e86beab01783c81acb1622b63` | -| `c.tsv` | `45e843c7b7e79a0d04d5bda879c9bd23f5a10974488bd8615e4f4c5d0749986f` | -| `d.tsv` | `1cf4057a8aece94f27bb3f278ad410ee2844831a642364eeceaafa091dbcceda` | -| `e.tsv` | `48c6f6645b031a5937c8386839debab0e2e48837251687ba1afb6369677f8546` | - ## ChessBase formats - `crates/chess-import/src/cbv.rs` reads ChessBase archives following uncbv @@ -208,11 +175,3 @@ Family 0.83, © 2010–2011 Canonical Ltd., Ubuntu Font Licence 1.0), from the official release `https://assets.ubuntu.com/v1/fad7939b-ubuntu-font-family-0.83.zip` (SHA-256 456d7d42…05b42, as in Arch Linux's `ttf-ubuntu-font-family`): `apps/desktop/assets/fonts/Ubuntu-B.ttf`, licence `UFL.txt` beside it. - -## Classic games (examples/classics.pgn) - -62 of the 100 sample classic games (added 2026-10-28) are game records — players, -event, date, result and moves, which are historical facts — taken from the free player -files of pgnmentor.com (64 Squares; "available for download, completely free") and, -where possible, checked against Wikipedia articles (used only for comparison, no text -copied). Details: `docs/research/classics-sources.md`. diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt index df5aa92..d0b2b30 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ChessPenguinApp.kt @@ -7,9 +7,6 @@ import androidx.compose.runtime.setValue import android.net.Uri import android.provider.OpenableColumns import io.github.vrubelroman.chesspenguin.data.AppUpdates -import io.github.vrubelroman.chesspenguin.data.CLIPBOARD_PREFERENCES -import io.github.vrubelroman.chesspenguin.data.ClipboardOffer -import io.github.vrubelroman.chesspenguin.data.ClipboardPgn import io.github.vrubelroman.chesspenguin.data.DbEntry import io.github.vrubelroman.chesspenguin.data.EngineFiles import io.github.vrubelroman.chesspenguin.data.MaiaFiles @@ -27,6 +24,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import java.util.concurrent.atomic.AtomicInteger import java.io.FileNotFoundException import java.util.UUID @@ -51,18 +49,6 @@ class ChessPenguinApp : Application() { val downloads by lazy { OnlineDownloads(library, scope) } /// The app's own updates (android-ui.md §25). val updates by lazy { AppUpdates(this, scope, engineFiles) } - val clipboardPgn by lazy { - ClipboardPgn( - library, - scope, - getSharedPreferences(CLIPBOARD_PREFERENCES, MODE_PRIVATE), - latestIncoming.lock, - ) { - if (latestIncoming.invalidateClipboard() && incoming.value == Incoming.Opening) { - incoming.value = null - } - } - } override fun onCreate() { super.onCreate() @@ -93,14 +79,13 @@ class ChessPenguinApp : Application() { /// One copy at a time, in the order the files came; only the last one opened is shown. private val copying = Mutex() - private val latestIncoming = LatestIncoming() + private val waiting = AtomicInteger() /// Copies a file another app gave (it gives access only for a while) and puts it on /// the list; `incoming` tells the screens how it went. fun receive(uri: Uri) { - val request = latestIncoming.withLock { - latestIncoming.next(IncomingOrigin.Uri).also { incoming.value = Incoming.Opening } - } + waiting.incrementAndGet() + incoming.value = Incoming.Opening scope.launch { val result = copying.withLock { try { @@ -116,47 +101,9 @@ class ChessPenguinApp : Application() { Incoming.Failed(e) } } - latestIncoming.publish(request) { incoming.value = result } - } - } - - fun openClipboard(offer: ClipboardOffer, name: String) { - val (accepted, request) = latestIncoming.withLock { - val accepted = clipboardPgn.accept(offer) ?: return - val request = latestIncoming.next(IncomingOrigin.Clipboard) - incoming.value = Incoming.Opening - accepted to request - } - scope.launch { - val result = copying.withLock { - try { - Incoming.Pasted(library.addCopy("clipboard.pgn", accepted.bytes.inputStream()) { name }) - } catch (e: Exception) { - Incoming.Failed(e) - } - } - latestIncoming.withLock { - if (!latestIncoming.isLatest(request)) { - clipboardPgn.finish(accepted, false) - return@withLock - } - if (!clipboardPgn.canPublish(accepted)) { - if (incoming.value == Incoming.Opening) incoming.value = null - return@withLock - } - when (result) { - is Incoming.Pasted -> { - clipboardPgn.finish(accepted, true) - incoming.value = result - } - is Incoming.Failed -> { - clipboardPgn.finish(accepted, false) - incoming.value = result - } - else -> incoming.value = null - } - latestIncoming.clear(request) - } + val more = waiting.decrementAndGet() > 0 + // A file opened while another one was still being copied comes after it. + if (!(more && result is Incoming.Opened)) incoming.value = result } } @@ -172,47 +119,8 @@ class ChessBasePart : Exception() private val CHESSBASE_PARTS = setOf("cbh", "cbg", "cba", "cbp", "cbs", "cbj", "cbt", "cbc", "cbe", "cbm") -internal enum class IncomingOrigin { - Uri, - Clipboard, -} - -internal class LatestIncoming { - internal val lock = Any() - private var generation = 0L - private var origin: IncomingOrigin? = null - - fun next(origin: IncomingOrigin = IncomingOrigin.Uri): Long = synchronized(lock) { - this.origin = origin - ++generation - } - - fun isLatest(request: Long): Boolean = synchronized(lock) { request == generation } - - fun invalidateClipboard(): Boolean = synchronized(lock) { - if (origin != IncomingOrigin.Clipboard) return false - origin = null - generation += 1 - true - } - - fun clear(request: Long) = synchronized(lock) { - if (isLatest(request)) origin = null - } - - fun publish(request: Long, action: () -> Unit): Boolean = synchronized(lock) { - if (!isLatest(request)) return false - action() - clear(request) - true - } - - inline fun withLock(action: () -> T): T = synchronized(lock, action) -} - sealed interface Incoming { data object Opening : Incoming data class Opened(val entry: DbEntry) : Incoming - data class Pasted(val entry: DbEntry) : Incoming data class Failed(val error: Throwable) : Incoming } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt index b130968..ea75c9a 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/MainActivity.kt @@ -1,6 +1,5 @@ package io.github.vrubelroman.chesspenguin -import android.content.ClipboardManager import android.content.Context import android.app.UiModeManager import android.content.Intent @@ -118,9 +117,7 @@ class MainActivity : ComponentActivity() { override fun onResume() { super.onResume() - val app = application as ChessPenguinApp - app.updates.onResume() - app.clipboardPgn.check(clipboardText(this)) + (application as ChessPenguinApp).updates.onResume() } override fun onStop() { @@ -130,10 +127,3 @@ class MainActivity : ComponentActivity() { if (!isChangingConfigurations) (application as ChessPenguinApp).leftApp() } } - -fun clipboardText(context: Context): String? = context.getSystemService(ClipboardManager::class.java) - ?.primaryClip - ?.takeIf { it.itemCount > 0 } - ?.getItemAt(0) - ?.text - ?.toString() diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt index 9ca888e..e572cee 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/Navigation.kt @@ -16,8 +16,6 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog @@ -45,19 +43,12 @@ import io.github.vrubelroman.chesspenguin.ui.NEW_GAME import io.github.vrubelroman.chesspenguin.ui.PLAY_GAME import io.github.vrubelroman.chesspenguin.ui.GamesScreen import io.github.vrubelroman.chesspenguin.ui.OnlineScreen -import io.github.vrubelroman.chesspenguin.ui.PlayersScreen -import io.github.vrubelroman.chesspenguin.ui.PrepScreen -import io.github.vrubelroman.chesspenguin.ui.PrepStart import kotlinx.serialization.Serializable @Serializable data object Databases : NavKey @Serializable data class Games(val db: String) : NavKey -@Serializable data class Players(val db: String) : NavKey - -@Serializable data class Preparation(val request: PrepStart) : NavKey - /// The game at `place` on the list of games found by `query` in the database (kept, so /// the same game comes back after Android restarts the app). @Serializable data class GameAt(val db: String, val place: Int, val query: String = "") : NavKey @@ -86,67 +77,17 @@ fun MainNavigation() { backStack.add(Games(entry.id)) if (entry.games == 1) backStack.add(GameAt(entry.id, 0)) } - fun showPasted(entry: DbEntry) { - while (backStack.size > 1) backStack.removeAt(backStack.lastIndex) - backStack.add(Games(entry.id)) - backStack.add(GameAt(entry.id, 0)) - } val app = app() val incoming by app.incoming.collectAsState() LaunchedEffect(incoming) { - when (val i = incoming) { - is Incoming.Opened -> { - if (app.incoming.compareAndSet(i, null)) show(i.entry) - } - is Incoming.Pasted -> { - if (app.incoming.compareAndSet(i, null)) { - resetPastedView(app.shown, app.lastOpened, i.entry.id) - showPasted(i.entry) - } - } - else -> {} + (incoming as? Incoming.Opened)?.let { + app.incoming.value = null + show(it.entry) } } // The app's update, over any screen (android-ui.md §25.3). val updateSheet by app.updates.sheet.collectAsState() if (updateSheet) UpdateSheet() - val clipboardUnblocked = incoming == null && !updateSheet - val context = LocalContext.current - LaunchedEffect(clipboardUnblocked) { - if (clipboardUnblocked) app.clipboardPgn.check(clipboardText(context)) - } - val clipboardOffer by app.clipboardPgn.offer.collectAsState() - if (clipboardUnblocked) { - clipboardOffer?.let { offer -> - val clipboardName = stringResource(R.string.clipboard_database_name) - AlertDialog( - onDismissRequest = { app.clipboardPgn.dismiss(offer) }, - title = { Text(pluralStringResource(R.plurals.clipboard_open_title, offer.games, offer.games)) }, - text = { - Text( - if (offer.games == 1) { - stringResource(R.string.clipboard_open_one) - } else { - stringResource( - R.string.clipboard_open_many, - pluralStringResource(R.plurals.games_count, offer.games, offer.games), - ) - }, - ) - }, - confirmButton = { - TextButton(onClick = { app.openClipboard(offer, clipboardName) }) { - Text(stringResource(R.string.clipboard_open)) - } - }, - dismissButton = { - TextButton(onClick = { app.clipboardPgn.dismiss(offer) }) { - Text(stringResource(R.string.cancel)) - } - }, - ) - } - } when (val i = incoming) { Incoming.Opening -> Dialog(onDismissRequest = {}, properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) { Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainerHigh) { @@ -158,10 +99,10 @@ fun MainNavigation() { } } is Incoming.Failed -> AlertDialog( - onDismissRequest = { app.incoming.compareAndSet(i, null) }, + onDismissRequest = { app.incoming.value = null }, title = { Text(stringResource(R.string.file_failed)) }, text = { Text(incomingProblem(i.error)) }, - confirmButton = { TextButton(onClick = { app.incoming.compareAndSet(i, null) }) { Text(stringResource(R.string.ok)) } }, + confirmButton = { TextButton(onClick = { app.incoming.value = null }) { Text(stringResource(R.string.ok)) } }, ) else -> {} } @@ -195,35 +136,10 @@ fun MainNavigation() { }, onOpenDatabase = { id -> backStack.add(Games(id)) }) } entry { key -> - GamesScreen( - key.db, - onBack = { backStack.removeLastOrNull() }, - onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }, - onPlayers = { backStack.add(Players(key.db)) }, - ) - } - entry { key -> - PlayersScreen( - key.db, - onBack = { backStack.removeLastOrNull() }, - onPrepare = { player, white -> - backStack.add(Preparation(PrepStart(db = key.db, player = player.name, white = white))) - }, - ) - } - entry { key -> - PrepScreen(key.request, onBack = { backStack.removeLastOrNull() }) + GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) }) } entry { key -> - GameScreen( - key.db, - key.place, - key.query, - onBack = { backStack.removeLastOrNull() }, - onSettings = { backStack.add(SettingsKey) }, - onPlayGame = { backStack.add(PlayKey) }, - onPrepare = { backStack.add(Preparation(it)) }, - ) + GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) }) } entry { SettingsScreen( @@ -252,15 +168,6 @@ fun MainNavigation() { ) } -internal fun resetPastedView( - shown: HashMap>, - lastOpened: HashMap>, - id: String, -) { - shown.remove(id) - lastOpened.remove(id) -} - /// Why a file from another app did not open; it never got on the list, so the advice is /// not that of a database on it (openProblem). @Composable diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ClipboardPgn.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ClipboardPgn.kt deleted file mode 100644 index 6677f47..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ClipboardPgn.kt +++ /dev/null @@ -1,173 +0,0 @@ -package io.github.vrubelroman.chesspenguin.data - -import android.content.SharedPreferences -import java.security.MessageDigest -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch - -internal const val CLIPBOARD_PGN_MAX_BYTES = 8 * 1024 * 1024 -internal const val CLIPBOARD_PREFERENCES = "clipboard-pgn" -private const val PREFS_DIGESTS = "decided-sha256" - -data class ClipboardOffer( - val bytes: ByteArray, - val games: Int, - internal val digest: String, - internal val generation: Long, -) - -data class ClipboardAccept( - val bytes: ByteArray, - internal val digest: String, - internal val generation: Long, -) - -class ClipboardPgn( - private val library: Library, - private val scope: CoroutineScope, - preferences: SharedPreferences, - private val requestLock: Any, - private val invalidateIncoming: () -> Unit, -) { - private val gate = ClipboardPromptGate( - decided = preferences.getStringSet(PREFS_DIGESTS, null).orEmpty(), - onDecide = { digests -> preferences.edit().putStringSet(PREFS_DIGESTS, digests).apply() }, - ) - private val _offer = MutableStateFlow(null) - val offer: StateFlow = _offer.asStateFlow() - private var hasSnapshot = false - private var lastSnapshot: String? = null - - fun check(text: String?) { - val generation = synchronized(requestLock) { - val changed = if (hasSnapshot && text == lastSnapshot) { - false - } else { - hasSnapshot = true - lastSnapshot = text - true - } - if (!changed) return - invalidateIncoming() - gate.invalidate().also { _offer.value = null } - } - if (text.isNullOrBlank() || !clipboardPgnLengthMayFit(text)) return - scope.launch { - val bytes = clipboardUtf8(text) - if (!clipboardPgnWithinLimit(bytes.size)) return@launch - val digest = clipboardSha256(bytes) - val games = try { - library.countPgnGames(bytes) - } catch (e: CancellationException) { - throw e - } catch (_: Exception) { - null - } - if (games == null) return@launch - val offer = ClipboardOffer(bytes, games, digest, generation) - synchronized(requestLock) { - if (gate.publish(offer)) { - _offer.value = offer - } - } - } - } - - fun accept(offer: ClipboardOffer): ClipboardAccept? = synchronized(requestLock) { - gate.accept(offer)?.also { _offer.value = null } - } - - fun dismiss(offer: ClipboardOffer) { - synchronized(requestLock) { - if (gate.dismiss(offer)) { - _offer.value = null - } - } - } - - fun canPublish(accept: ClipboardAccept): Boolean = synchronized(requestLock) { gate.canPublish(accept) } - - fun finish(accept: ClipboardAccept, success: Boolean): Boolean = synchronized(requestLock) { - val finished = gate.finish(accept, success) - if (finished && !success) { - hasSnapshot = false - lastSnapshot = null - } - finished - } -} - -internal class ClipboardPromptGate( - decided: Set = emptySet(), - private val onDecide: (Set) -> Unit = {}, -) { - private val decided = HashSet(decided) - private var generation = 0L - private var offer: ClipboardOffer? = null - private var accepted: ClipboardAccept? = null - - @Synchronized - fun invalidate(): Long { - generation += 1 - offer = null - accepted = null - return generation - } - - @Synchronized - fun publish(offer: ClipboardOffer): Boolean { - if (offer.generation != generation || offer.digest in decided || accepted != null) return false - this.offer = offer - return true - } - - @Synchronized - fun accept(offer: ClipboardOffer): ClipboardAccept? { - if (this.offer != offer || accepted != null) return null - val accept = ClipboardAccept(offer.bytes, offer.digest, offer.generation) - accepted = accept - this.offer = null - return accept - } - - @Synchronized - fun dismiss(offer: ClipboardOffer): Boolean { - if (this.offer != offer) return false - this.offer = null - decide(offer.digest) - return true - } - - @Synchronized - fun canPublish(accept: ClipboardAccept): Boolean = - accepted == accept && accept.generation == generation - - @Synchronized - fun finish(accept: ClipboardAccept, success: Boolean): Boolean { - if (accepted != accept || accept.generation != generation) return false - accepted = null - if (success) { - decide(accept.digest) - } else { - invalidate() - } - return true - } - - private fun decide(digest: String) { - if (decided.add(digest)) onDecide(decided.toSet()) - } -} - -internal fun clipboardPgnLengthMayFit(text: String): Boolean = text.length <= CLIPBOARD_PGN_MAX_BYTES - -internal fun clipboardUtf8(text: String): ByteArray = text.toByteArray(Charsets.UTF_8) - -internal fun clipboardSha256(bytes: ByteArray): String = - MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } - -internal fun clipboardPgnWithinLimit(size: Int): Boolean = size <= CLIPBOARD_PGN_MAX_BYTES diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt index e247bc9..31b662b 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Library.kt @@ -73,8 +73,7 @@ data class DbEntry( val format: String? = null, /// A sample shows the name of the current language until it is renamed (displayName). val renamed: Boolean = false, - /// A copy's SHA-256: the same file opened again is not copied twice. A sample's: of - /// the text its number of games was taken from (a new app may bring a new text). + /// A copy's SHA-256: the same file opened again is not copied twice. val sha256: String? = null, /// A downloaded database: when its last download finished (Unix seconds). val updated: Long? = null, @@ -205,18 +204,6 @@ class Library(private val context: Context) { return names.map { (f, name) -> DbEntry(id = "sample-$f", name = name, source = Source.Sample, location = "examples/$f", fileName = f) } } - /// Counts the samples on the list not counted yet, or counted in a text other than - /// the one in this app: an update of the app brings a sample's new version (more - /// games), read from the app itself as ever, and its row shows it at once. - suspend fun countSamples() { - for (e in _entries.value.filter { it.source == Source.Sample }) { - if (e.games != null && e.sha256 == withContext(Dispatchers.IO) { sha256(sampleBytes(e)) }) continue - database(e.id) - } - } - - private fun sampleBytes(e: DbEntry): ByteArray = context.assets.open(e.location).use { it.readBytes() } - /// Puts the sample games back on the list (those not on it), at its end. fun addSamples() = update { list -> list + samples().filter { s -> list.none { it.id == s.id } } } @@ -251,27 +238,6 @@ class Library(private val context: Context) { return entry } - /// Counts real games in PGN text without keeping a copy of it. - suspend fun countPgnGames(text: String): Int? = countPgnGames(clipboardUtf8(text)) - - suspend fun countPgnGames(bytes: ByteArray): Int? = withContext(Dispatchers.IO) { - if (!clipboardPgnWithinLimit(bytes.size)) return@withContext null - val db = runCatching { openBytes("clipboard.pgn", bytes) }.getOrNull() ?: return@withContext null - try { - val count = db.len().toInt() - if (count == 0) { - null - } else { - val first = db.game(0u) - if (firstPgnGameIsMeaningful(count, first.tags.size, first.nodes.size)) count else null - } - } catch (_: ApiException) { - null - } finally { - db.close() - } - } - /// Keeps a copy of `input` (named `fileName`, for its format) in the app and puts it /// on the list, or gives the entry of the same copy already there. Throws [NoGames] /// when there is no game in it, or the core's error when it cannot be read; nothing @@ -293,7 +259,7 @@ class Library(private val context: Context) { } val sum = digest.digest().joinToString("") { "%02x".format(it) } lock.withLock { - copyWithDigest(_entries.value, sum)?.let { return@withContext it } + _entries.value.firstOrNull { it.source == Source.Copy && it.sha256 == sum }?.let { return@withContext it } } val id = UUID.randomUUID().toString() val kept = File(copies, "$id.$ext") @@ -326,11 +292,6 @@ class Library(private val context: Context) { sha256 = sum, ) lock.withLock { - copyWithDigest(_entries.value, sum)?.let { existing -> - db.close() - kept.delete() - return@withContext existing - } open[id] = db update { it + entry } } @@ -618,14 +579,10 @@ class Library(private val context: Context) { suspend fun database(id: String): Result = lock.withLock { open[id]?.let { return@withLock Result.success(it) } val e = entry(id) ?: return@withLock Result.failure(IllegalArgumentException("no database $id")) - var text: String? = e.sha256 val result = withContext(Dispatchers.IO) { runCatching { when (e.source) { - Source.Sample -> sampleBytes(e).let { bytes -> - text = sha256(bytes) - openBytes(e.fileName, bytes) - } + Source.Sample -> openBytes(e.fileName, context.assets.open(e.location).use { it.readBytes() }) Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd()) Source.ChessBase -> openChessBase(e) Source.Copy -> openFile( @@ -644,20 +601,10 @@ class Library(private val context: Context) { open[id] = db val games = db.len().toInt() val format = db.format() - val sum = text - if (e.games != games || e.format != format || e.sha256 != sum) { - update { list -> list.map { if (it.id == id) it.copy(games = games, format = format, sha256 = sum) else it } } + if (e.games != games || e.format != format) { + update { list -> list.map { if (it.id == id) it.copy(games = games, format = format) else it } } } } result } } - -internal fun firstPgnGameIsMeaningful(count: Int, tags: Int, nodes: Int): Boolean = - count > 0 && (tags > 0 || nodes > 1) - -internal fun copyWithDigest(entries: List, digest: String): DbEntry? = - entries.firstOrNull { it.source == Source.Copy && it.sha256 == digest } - -private fun sha256(bytes: ByteArray): String = - java.security.MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PrepSearch.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PrepSearch.kt deleted file mode 100644 index ce1ed25..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/PrepSearch.kt +++ /dev/null @@ -1,129 +0,0 @@ -package io.github.vrubelroman.chesspenguin.data - -import io.github.vrubelroman.chesspenguin.ui.PlayerPage -import io.github.vrubelroman.chesspenguin.ui.PlayerSummary -import io.github.vrubelroman.chesspenguin.ui.PrepContinuation -import io.github.vrubelroman.chesspenguin.ui.PrepGameMatch -import io.github.vrubelroman.chesspenguin.ui.PrepOutOfMemory -import io.github.vrubelroman.chesspenguin.ui.PrepPlayerNotFound -import io.github.vrubelroman.chesspenguin.ui.PrepPosition -import io.github.vrubelroman.chesspenguin.ui.PrepSearchFailed -import io.github.vrubelroman.chesspenguin.ui.PrepStart -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.delay -import kotlinx.coroutines.ensureActive -import kotlin.coroutines.coroutineContext -import uniffi.mobile_api.Database -import uniffi.mobile_api.PrepPhase -import uniffi.mobile_api.PrepResult -import uniffi.mobile_api.PrepSearch as RustPrepSearch - -internal data class PrepQuery( - val player: String, - val white: Boolean, - val fen: String, -) - -internal fun PrepStart.query(fen: String): PrepQuery = PrepQuery(player, white, fen) - -/// The Android side of mobile-api's preparation contract. Database aggregation stays in -/// Rust; the object being closed is the search, never the library's shared Database. -internal interface PrepBackend { - suspend fun players(query: String, offset: Int, limit: Int): PlayerPage - suspend fun position(query: PrepQuery): PrepPosition - fun cancel() - fun close() -} - -internal object PrepBackends { - fun open(database: Database): PrepBackend = RustPrepBackend(database) -} - -private class RustPrepBackend(private val database: Database) : PrepBackend { - private val lock = Any() - private val playerIds = java.util.concurrent.ConcurrentHashMap() - private var active: RustPrepSearch? = null - @Volatile private var closed = false - - override suspend fun players(query: String, offset: Int, limit: Int): PlayerPage { - coroutineContext.ensureActive() - if (closed) throw CancellationException("The player list is closed") - val start = offset.coerceAtLeast(0) - val answer = database.suggestPlayers(query, start.toUInt(), limit.coerceIn(0, 200).toUInt()) - val players = answer.players.map { - PlayerSummary(it.id.toInt(), it.name, it.games.toInt(), it.whiteGames.toInt(), it.blackGames.toInt()) - } - val end = start + players.size - return PlayerPage(players, answer.total.toInt(), end.takeIf { players.isNotEmpty() && it < answer.total.toInt() }) - } - - override suspend fun position(query: PrepQuery): PrepPosition { - coroutineContext.ensureActive() - val id = findPlayer(query.player) - coroutineContext.ensureActive() - val search = synchronized(lock) { - if (closed) throw CancellationException("The position search is closed") - active?.cancel() - database.preparePosition(id, query.white, query.fen).also { active = it } - } - try { - while (true) { - val state = search.state() - when (state.phase) { - PrepPhase.GAMES, PrepPhase.INDEX, PrepPhase.SEARCH -> delay(25) - PrepPhase.READY -> return state.result?.toUi() - ?: throw PrepSearchFailed(state.failure.ifEmpty { "The position search returned no result" }) - PrepPhase.CANCELLED -> throw CancellationException("The position search was cancelled") - PrepPhase.NO_MEMORY -> throw PrepOutOfMemory() - PrepPhase.FAILED -> throw PrepSearchFailed(state.failure.ifEmpty { "The position search failed" }) - } - } - } finally { - synchronized(lock) { - if (active === search) active = null - } - search.close() - } - } - - private fun findPlayer(name: String): UInt { - playerIds[name]?.let { return it } - var offset = 0 - while (true) { - val page = database.suggestPlayers(name, offset.toUInt(), 200u) - page.players.firstOrNull { it.name == name }?.let { - playerIds[name] = it.id - return it.id - } - if (page.players.isEmpty()) break - offset += page.players.size - if (offset >= page.total.toInt()) break - } - throw PrepPlayerNotFound(name) - } - - override fun cancel() { - synchronized(lock) { active?.cancel() } - } - - override fun close() { - synchronized(lock) { - closed = true - active?.cancel() - active = null - } - } -} - -private fun PrepResult.toUi() = PrepPosition( - games = games.toInt(), - continuations = continuations.map { - PrepContinuation(it.uci, it.san, it.count.toInt(), it.wins.toInt(), it.draws.toInt(), it.losses.toInt(), it.unknown.toInt()) - }, - endedHere = ended.toInt(), - noNormalContinuation = noNormalContinuation.toInt(), - unknownResults = unknown.toInt(), - playerToMove = playerToMove, - matches = matches.map { PrepGameMatch(it.index, it.ply) }, - matchesTotal = matchesTotal.toInt(), -) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt index d0fb7a7..aac92d9 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/ReviewSession.kt @@ -15,9 +15,11 @@ import uniffi.mobile_api.Database import uniffi.mobile_api.GameReview import uniffi.mobile_api.ReviewState -/// A first guess at the speed of one engine process (one thread) before it was measured -/// on this phone. -const val GUESS_NPS = 250_000L +/// Nodes per position of the three qualities, as on the desktop (android-ui.md §21.2). +val REVIEW_NODES = listOf(250_000UL, 1_000_000UL, 3_000_000UL) + +/// A first guess at the engine's speed per thread before it was measured on this phone. +const val GUESS_NPS_PER_THREAD = 250_000L /// The analysis of the game on the screen (its report, android-ui.md §21): the cached /// or PGN evaluations at once, the engine job when asked for. One game at a time; the @@ -60,17 +62,16 @@ class ReviewSession(private val cacheDir: String, private val scope: CoroutineSc } } - /// Starts the engine on the positions without an evaluation, or on all when `full` - /// (or when the analysis is stale). The search is fixed, the same as on the desktop - /// (decisions.md, 2026-10-28). `done` gets the final state when the job ends by itself. - fun start(path: String, evalFile: String, full: Boolean, done: (ReviewState) -> Unit) { + /// Starts the engine on the positions without an evaluation, or on all when `full`. + /// `done` gets the final state when the job ends by itself. + fun start(path: String, evalFile: String, threads: Int, hashMb: Int, nodes: ULong, full: Boolean, done: (ReviewState) -> Unit) { val gen = generation scope.launch { lock.withLock { val r = review ?: return@withLock if (gen != generation) return@withLock val started = withContext(Dispatchers.IO) { - r.start(path, evalFile, full) + r.start(path, evalFile, threads.toUInt(), hashMb.toUInt(), nodes, full) } _state.value = withContext(Dispatchers.IO) { r.state() } if (started) poll(r, gen, done) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt index e69b91f..83f798f 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/data/Settings.kt @@ -27,8 +27,10 @@ data class Prefs( val engineSeconds: Int = 20, val engineThreads: Int = defaultThreads(), val engineHashMb: Int = 64, - /// The speed of one engine process (one thread) measured by the last game analysis - /// (0 = not yet), for the time estimate. + /// The game report's quality, an index into REVIEW_NODES (§21.2). + val reviewQuality: Int = 1, + /// The engine's speed per thread measured by the last game analysis (0 = not yet), + /// for the time estimate. val reviewNps: Long = 0, /// The last choices of a game against the computer (android-play.md §31.1, /// android-rodent.md §7.1): the opponent, each one's strength on its own scale, @@ -78,6 +80,7 @@ class Settings(context: Context) { engineSeconds = store.getInt("engineSeconds", d.engineSeconds), engineThreads = store.getInt("engineThreads", d.engineThreads), engineHashMb = store.getInt("engineHashMb", d.engineHashMb), + reviewQuality = store.getInt("reviewQuality", d.reviewQuality).coerceIn(0, REVIEW_NODES.size - 1), reviewNps = store.getLong("reviewNps", d.reviewNps), opponent = Opponent.entries.firstOrNull { it.key == store.getString("opponent", null) } ?: d.opponent, maiaStrength = store.getInt("maiaStrength", d.maiaStrength), @@ -106,6 +109,7 @@ class Settings(context: Context) { .putInt("engineSeconds", p.engineSeconds) .putInt("engineThreads", p.engineThreads) .putInt("engineHashMb", p.engineHashMb) + .putInt("reviewQuality", p.reviewQuality) .putLong("reviewNps", p.reviewNps) .putString("opponent", p.opponent.key) .putInt("maiaStrength", p.maiaStrength) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt index 9fae784..95ab2fa 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/Board.kt @@ -36,9 +36,7 @@ import androidx.compose.ui.platform.LocalViewConfiguration import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.customActions import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText @@ -155,15 +153,6 @@ class BoardInput( /// An arrow on the board: a comment's `[%cal]` or the engine's best move. data class BoardArrow(val from: String, val to: String, val color: Color, val weight: Float = 1f) -/// A continuation attached to an arrow. Several UCI moves may share one direction -/// (promotions); in that case the callback receives all of them for an explicit choice. -data class BoardArrowMove( - val uci: String, - val from: String, - val to: String, - val actionLabel: String, -) - /// A marked square of a comment (`[%csl]`), drawn as a ring. data class BoardMark(val square: String, val color: Color) @@ -183,56 +172,6 @@ fun markColor(letter: String): Color = when (letter) { /// The engine's arrows are blue, as on the desktop. val EngineArrow = Color(0, 48, 136, 160) -internal fun boardCell(index: Int, square: Float, flipped: Boolean): Offset { - val row = index / 8 - val col = index % 8 - val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col - return Offset(c * square, r * square) -} - -private data class ArrowGeometry(val start: Offset, val base: Offset, val tip: Offset) - -private fun arrowGeometry(from: Offset, to: Offset, square: Float, weight: Float): ArrowGeometry? { - val delta = to - from - val length = delta.getDistance() - if (length < 1f) return null - val direction = delta / length - val headLength = square * 0.42f * kotlin.math.sqrt(weight) - val tip = to - direction * (square * 0.12f) - return ArrowGeometry(from + direction * (square * 0.2f), tip - direction * headLength, tip) -} - -private fun distanceToSegment(point: Offset, start: Offset, end: Offset): Float { - val segment = end - start - val length2 = segment.x * segment.x + segment.y * segment.y - if (length2 < 1f) return (point - start).getDistance() - val t = (((point - start).x * segment.x + (point - start).y * segment.y) / length2).coerceIn(0f, 1f) - return (point - (start + segment * t)).getDistance() -} - -/// Hit testing uses the same square transform and arrow endpoints as drawing. The head -/// has at least a 48 dp target; shaft corridors stay narrower so neighbours do not all -/// become one arbitrary shortcut. -internal fun arrowHits( - point: Offset, - square: Float, - flipped: Boolean, - moves: List, - headRadius: Float, -): List { - if (square <= 0f || point.x < 0 || point.y < 0 || point.x > square * 8 || point.y > square * 8) return emptyList() - val corridor = maxOf(square * 0.16f, headRadius * 0.5f) - return moves.filter { move -> - val from = squareIndex(move.from) ?: return@filter false - val to = squareIndex(move.to) ?: return@filter false - val center = Offset(square / 2, square / 2) - val geometry = arrowGeometry(boardCell(from, square, flipped) + center, boardCell(to, square, flipped) + center, square, 1f) ?: return@filter false - (point - geometry.tip).getDistance() <= headRadius || - distanceToSegment(point, geometry.start, geometry.base) <= corridor || - distanceToSegment(point, geometry.base, geometry.tip) <= corridor - } -} - /// The board: full width, the chosen board and pieces, the last move lit, the /// coordinates inside the edge squares (as on Lichess). With `input` a move is made by /// tapping a piece and then a square, or by dragging it (android-play.md §29.2–29.3); @@ -249,8 +188,6 @@ fun Board( description: String, modifier: Modifier = Modifier, arrows: List = emptyList(), - arrowMoves: List = emptyList(), - onArrowMoves: (List) -> Unit = {}, marks: List = emptyList(), check: Boolean = false, animated: Boolean = true, @@ -295,8 +232,6 @@ fun Board( var dragAt by remember(fen) { mutableStateOf(null) } val slop = LocalViewConfiguration.current.touchSlop val currentInput = androidx.compose.runtime.rememberUpdatedState(input) - val currentArrowMoves = androidx.compose.runtime.rememberUpdatedState(arrowMoves) - val currentArrowAction = androidx.compose.runtime.rememberUpdatedState(onArrowMoves) val lift = with(density) { 22.dp.toPx() } fun indexAt(p: Offset, sq: Float): Int? { val col = (p.x / sq).toInt() @@ -313,8 +248,7 @@ fun Board( val startName = squareName(start) val movable = inp.targets(startName).isNotEmpty() val was = selected - // A tap on a target of the piece chosen makes the move. An already chosen - // piece always has priority over continuation arrows. + // A tap on a target of the piece chosen makes the move. if (was != null && start != was) { inp.move(squareName(was), startName)?.let { m -> selected = null @@ -323,7 +257,6 @@ fun Board( } } if (movable) selected = start - val shortcutCandidate = was == null && !movable var dragging = false while (true) { val e = awaitPointerEvent() @@ -338,29 +271,17 @@ fun Board( inp.onMove(m) } // A drop elsewhere: the piece goes back, still chosen. - } else { - if (!movable || start == was) { - // A tap on the same piece, an empty square or the other side's - // piece: nothing chosen any more. - selected = null - } - if (shortcutCandidate) { - val hits = arrowHits( - c.position, - sq, - flipped, - currentArrowMoves.value, - with(density) { 24.dp.toPx() }, - ) - if (hits.isNotEmpty()) currentArrowAction.value(hits.map { it.uci }.distinct()) - } + } else if (!movable || start == was) { + // A tap on the same piece, an empty square or the other side's + // piece: nothing chosen any more. + selected = null } c.consume() break } - if (!dragging && (c.position - down.position).getDistance() > slop) dragging = true + if (movable && !dragging && (c.position - down.position).getDistance() > slop) dragging = true if (dragging) { - if (movable) dragAt = c.position + dragAt = c.position c.consume() } } @@ -371,21 +292,16 @@ fun Board( .aspectRatio(1f) .onSizeChanged { side = it.width } .then(touch) - .semantics { - contentDescription = description - if (arrowMoves.isNotEmpty()) { - customActions = arrowMoves.map { move -> - CustomAccessibilityAction(move.actionLabel) { - onArrowMoves(listOf(move.uci)) - true - } - } - } - }, + .semantics { contentDescription = description }, ) { val sq = size.width / 8f val px = sq.toInt() - fun cell(i: Int): Offset = boardCell(i, sq, flipped) + fun cell(i: Int): Offset { + val row = i / 8 + val col = i % 8 + val (r, c) = if (flipped) (7 - row) to (7 - col) else row to col + return Offset(c * sq, r * sq) + } val image = texture if (image != null) { // The squares of the image are the same seen from either side: it is not turned. @@ -514,17 +430,22 @@ fun Board( /// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops /// short of the square's center. private fun DrawScope.drawArrow(from: Offset, to: Offset, sq: Float, a: BoardArrow) { - val geometry = arrowGeometry(from, to, sq, a.weight) ?: return val d = to - from - val dir = d / d.getDistance() + val len = d.getDistance() + if (len < 1f) return + val dir = d / len val width = sq * 0.16f * a.weight + val headLen = sq * 0.42f * kotlin.math.sqrt(a.weight) val headW = sq * 0.38f * kotlin.math.sqrt(a.weight) + val tip = to - dir * (sq * 0.12f) + val base = tip - dir * headLen + val start = from + dir * (sq * 0.2f) val normal = Offset(-dir.y, dir.x) - drawLine(a.color, geometry.start, geometry.base, strokeWidth = width) + drawLine(a.color, start, base, strokeWidth = width) val head = Path().apply { - moveTo(geometry.tip.x, geometry.tip.y) - lineTo(geometry.base.x + normal.x * headW, geometry.base.y + normal.y * headW) - lineTo(geometry.base.x - normal.x * headW, geometry.base.y - normal.y * headW) + moveTo(tip.x, tip.y) + lineTo(base.x + normal.x * headW, base.y + normal.y * headW) + lineTo(base.x - normal.x * headW, base.y - normal.y * headW) close() } drawPath(head, a.color) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt index 5b32995..efb52a8 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/DatabasesScreen.kt @@ -224,7 +224,9 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett } val scroll = TopAppBarDefaults.pinnedScrollBehavior() // The samples are small: read them at once, so their rows show the number of games. - LaunchedEffect(Unit) { library.countSamples() } + LaunchedEffect(Unit) { + library.entries.value.filter { it.source == Source.Sample && it.games == null }.forEach { library.database(it.id) } + } Scaffold( modifier = Modifier.nestedScroll(scroll.nestedScrollConnection), diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameBarState.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameBarState.kt deleted file mode 100644 index d57e185..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameBarState.kt +++ /dev/null @@ -1,19 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -internal enum class ReviewAction { Start, Report, Wait } - -/// The same availability the menu entry had, now used by the visible bottom-bar button. -internal fun reviewEnabled( - hasMoves: Boolean, - gameOn: Boolean, - sessionGame: Boolean, - loaded: Boolean, - hasData: Boolean, - running: Boolean, -): Boolean = hasMoves && !gameOn && (sessionGame || loaded) && (hasData || !running) - -internal fun reviewAction(hasData: Boolean, running: Boolean): ReviewAction = when { - hasData -> ReviewAction.Report - running -> ReviewAction.Wait - else -> ReviewAction.Start -} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt index 4208c9f..6c8d480 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GameScreen.kt @@ -5,20 +5,19 @@ import android.content.res.Configuration import android.content.Intent import android.view.HapticFeedbackConstants import androidx.activity.compose.BackHandler -import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable -import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.indication +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.interaction.PressInteraction import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.navigationBars @@ -34,7 +33,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.outlined.Memory @@ -46,10 +44,11 @@ import androidx.compose.material.icons.rounded.SmartToy import androidx.compose.material.icons.rounded.VerticalAlignTop import androidx.compose.material.icons.rounded.ChevronRight import androidx.compose.material.icons.rounded.Download +import androidx.compose.material.icons.rounded.FirstPage +import androidx.compose.material.icons.rounded.LastPage import androidx.compose.material.icons.rounded.Memory import androidx.compose.material.icons.rounded.MoreVert import androidx.compose.material.icons.rounded.PlayArrow -import androidx.compose.material.icons.rounded.QueryStats import androidx.compose.material.icons.rounded.SwapVert import androidx.compose.material3.AlertDialog import androidx.compose.material3.CircularProgressIndicator @@ -71,6 +70,7 @@ import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar +import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -85,7 +85,6 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector @@ -95,14 +94,10 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.customActions import androidx.compose.ui.semantics.disabled import androidx.compose.ui.semantics.onClick -import androidx.compose.ui.semantics.onLongClick import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription @@ -119,11 +114,13 @@ import io.github.vrubelroman.chesspenguin.R import io.github.vrubelroman.chesspenguin.data.EngineSession import io.github.vrubelroman.chesspenguin.data.NetState import io.github.vrubelroman.chesspenguin.data.Opponent +import io.github.vrubelroman.chesspenguin.data.REVIEW_NODES import io.github.vrubelroman.chesspenguin.data.ReviewSession import io.github.vrubelroman.chesspenguin.data.enginePosition import io.github.vrubelroman.chesspenguin.theme.LocalChessColors import io.github.vrubelroman.chesspenguin.theme.Tabular import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -151,7 +148,6 @@ fun GameScreen( onSettings: () -> Unit, onPlayGame: () -> Unit = {}, onOpenDatabase: (String) -> Unit = {}, - onPrepare: (PrepStart) -> Unit = {}, ) { val app = app() val context = LocalContext.current @@ -300,7 +296,6 @@ fun GameScreen( val reviewCycle = remember(place) { HashMap, Int>() } var menu by remember { mutableStateOf(false) } var info by remember { mutableStateOf(false) } - var prepSheet by remember(place) { mutableStateOf(false) } @Suppress("DEPRECATION") val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current val pgnCopied = stringResource(R.string.pgn_copied) @@ -337,9 +332,6 @@ fun GameScreen( // The player bars above and below the board (§7.11); the top bar names the event. val whiteName = tag("White").trim().takeIf { it.isNotEmpty() && it != "?" } val blackName = tag("Black").trim().takeIf { it.isNotEmpty() && it != "?" } - val prepPathAvailable = g?.let { data -> - prepStartFromGame(data, current, db, whiteName ?: blackName.orEmpty(), whiteName != null) != null - } == true val whiteLabel = stringResource(R.string.tag_white) val blackLabel = stringResource(R.string.tag_black) val resultText = g?.let { resultLine(context, it.result) } ?: "" @@ -392,8 +384,9 @@ fun GameScreen( } wantReview = null reviewHidden = false - review.start(files.executable, files.net.path, full) { s -> - if (s.npsPerProcess > 0UL) app.settings.update { it.copy(reviewNps = s.npsPerProcess.toLong()) } + val p = app.settings.prefs.value + review.start(files.executable, files.net.path, p.engineThreads, p.engineHashMb, REVIEW_NODES[p.reviewQuality], full) { s -> + if (s.npsPerThread > 0UL) app.settings.update { it.copy(reviewNps = s.npsPerThread.toLong()) } } } // The engine became ready for an analysis that was asked for. @@ -439,24 +432,6 @@ fun GameScreen( val reviewMarks = remember(rs) { rs?.moves?.associate { it.node.toInt() to it.judgement } ?: emptyMap() } val currentMark = if (reviewShown) rs.moves.firstOrNull { it.node.toInt() == current } else null - // The one visible entry to the report: start it, or bring its panel back and open it. - fun openReview() { - reviewHidden = false - val e = edit - if ((newGame || playGame) && e != null && rs == null) { - scope.launch { - review.openSession("${held.key}/${System.nanoTime()}", e) - reviewStart = true - } - return - } - when (reviewAction(rs?.hasData == true, rs?.running == true)) { - ReviewAction.Report -> reviewReport = true - ReviewAction.Wait -> {} - ReviewAction.Start -> reviewStart = true - } - } - fun buzz(edge: Boolean) { if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK) } @@ -810,13 +785,6 @@ fun GameScreen( fun forward() { if (preview != null) stepPreview(1) else node?.children?.firstOrNull()?.let { go(it.toInt()) } } - fun start() { - preview?.let { - preview = it.copy(step = 0) - return - } - go(0) - } fun end() { preview?.let { preview = it.copy(step = it.line.steps.size - 1) @@ -890,62 +858,24 @@ fun GameScreen( } HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) Surface(color = MaterialTheme.colorScheme.surfaceContainer) { - BoxWithConstraints(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) { - val compact = maxWidth < 320.dp - val narrow = maxWidth < 360.dp - val engineSlot = if (compact) 52f else if (narrow) 56f else 60f - val reviewSlot = if (compact) 52f else if (narrow) 88f else 96f - val moveSlot = if (compact || narrow) 64f else 78f - Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) { - EngineButton( - on = engineOn, - needsDownload = !engineReady && !files.builtIn, - loading = netState as? NetState.Loading, - modifier = Modifier.weight(engineSlot), - onClick = ::toggleEngine, - ) - BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(48f)) { flipped = !flipped } - - BarButton( - icon = Icons.Rounded.PlayArrow, - label = stringResource(R.string.move_back), - description = stringResource(R.string.move_back), - enabled = canBack, - modifier = Modifier.weight(moveSlot), - iconSize = 32, - mirrored = true, - onLongClickLabel = stringResource(R.string.to_start), - onLongClick = ::start, - onClick = ::back, - ) - BarButton( - icon = Icons.Rounded.PlayArrow, - label = stringResource(R.string.move_forward), - description = stringResource(R.string.move_forward), - enabled = canForward, - modifier = Modifier.weight(moveSlot), - iconSize = 32, - onLongClickLabel = stringResource(R.string.to_end), - onLongClick = ::end, - onClick = ::forward, - ) - ReviewButton( - report = rs?.hasData == true, - enabled = reviewEnabled( - hasMoves = hasMoves, - gameOn = gameOn, - sessionGame = newGame || playGame, - loaded = rs != null, - hasData = rs?.hasData == true, - running = rs?.running == true, - ) && !preparingReview, - preparing = preparingReview, - progress = if (rs?.running == true) rs.done.toInt() to rs.total.toInt() else null, - showLabel = !compact, - modifier = Modifier.weight(reviewSlot), - onClick = ::openReview, - ) + Row( + Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + EngineButton( + on = engineOn, + needsDownload = !engineReady && !files.builtIn, + loading = netState as? NetState.Loading, + modifier = Modifier.weight(1.2f), + onClick = ::toggleEngine, + ) + BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(1f)) { flipped = !flipped } + BarButton(Icons.Rounded.FirstPage, stringResource(R.string.to_start), canBack, Modifier.weight(1f)) { + if (preview != null) preview = null else go(0) } + BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_back), canBack, Modifier.weight(1.5f), 32, repeat = true, mirrored = true) { back() } + BarButton(Icons.Rounded.PlayArrow, stringResource(R.string.move_forward), canForward, Modifier.weight(1.5f), 32, repeat = true) { forward() } + BarButton(Icons.Rounded.LastPage, stringResource(R.string.to_end), canForward, Modifier.weight(1f)) { end() } } } } @@ -979,7 +909,6 @@ fun GameScreen( if (f != null && t != null) { add(BoardArrow(f, t, EngineArrow.copy(alpha = if (i == 0) 0.63f else 0.35f), if (i == 0) 1f else 0.7f)) } - } } } @@ -1249,32 +1178,32 @@ fun GameScreen( undo() }) } + DropdownMenuItem( + text = { Text(stringResource(if (rs?.hasData == true) R.string.review_report_menu else R.string.review_menu)) }, + // During the first analysis the panel already shows its progress (§21.1). + enabled = hasMoves && !gameOn && ((newGame || playGame) || (rs != null && (rs.hasData || !rs.running))), + onClick = { + menu = false + reviewHidden = false + val e = edit + if ((newGame || playGame) && e != null && rs == null) { + scope.launch { + review.openSession("${held.key}/${System.nanoTime()}", e) + reviewStart = true + } + return@DropdownMenuItem + } + when { + rs?.hasData == true -> reviewReport = true + rs?.running == true -> {} + else -> reviewStart = true + } + }, + ) DropdownMenuItem(text = { Text(stringResource(R.string.game_info)) }, enabled = g != null, onClick = { menu = false info = true }) - if (!newGame && !playGame && (whiteName != null || blackName != null)) { - val reason = when { - preview != null -> stringResource(R.string.prep_close_engine_line) - !prepPathAvailable -> stringResource(R.string.prep_null_move_unavailable) - else -> null - } - DropdownMenuItem( - text = { - Column { - Text(stringResource(R.string.prep_opponent)) - if (reason != null) { - Text(reason, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - }, - enabled = reason == null, - onClick = { - menu = false - prepSheet = true - }, - ) - } DropdownMenuItem(text = { Text(stringResource(R.string.copy_pgn)) }, enabled = g != null, onClick = { menu = false scope.launch { @@ -1363,42 +1292,6 @@ fun GameScreen( } } } - if (prepSheet && g != null) { - androidx.compose.material3.ModalBottomSheet(onDismissRequest = { prepSheet = false }) { - Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { - Text( - stringResource(R.string.prep_title), - style = MaterialTheme.typography.titleLarge, - modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp), - ) - listOfNotNull( - whiteName?.let { true to it }, - blackName?.let { false to it }, - ).forEach { (white, name) -> - Row( - Modifier.fillMaxWidth().heightIn(min = 64.dp).clickable { - prepStartFromGame(g, current, db, name, white)?.let { - prepSheet = false - onPrepare(it) - } - }.padding(horizontal = 24.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - SideDisc(white) - Spacer(Modifier.width(12.dp)) - Column { - PlayerName(name, MaterialTheme.typography.bodyLarge) - Text( - stringResource(if (white) R.string.prep_as_white else R.string.prep_as_black), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } - } - } - } if (info && g != null) { AlertDialog( onDismissRequest = { info = false }, @@ -1640,7 +1533,10 @@ fun GameScreen( if (reviewStart) { ReviewStartSheet( state = rs, - npsPerProcess = prefs.reviewNps, + quality = prefs.reviewQuality, + threads = prefs.engineThreads, + npsPerThread = prefs.reviewNps, + onQuality = { q -> app.settings.update { it.copy(reviewQuality = q) } }, onStart = { full -> reviewStart = false startReview(full) @@ -1726,92 +1622,6 @@ private fun EngineButton(on: Boolean, needsDownload: Boolean, loading: NetState. } } -/// The visible entry to whole-game analysis. The invitation uses the report's «!!» -/// teal; a finished report drops the fill. Progress and stopping stay in `ReviewPanel`. -@OptIn(ExperimentalFoundationApi::class) -@Composable -internal fun ReviewButton( - report: Boolean, - enabled: Boolean, - modifier: Modifier, - preparing: Boolean = false, - progress: Pair? = null, - showLabel: Boolean = true, - onClick: () -> Unit, -) { - val label = when { - progress != null && !report -> "${progress.first}/${progress.second}" - report -> stringResource(R.string.review_report) - else -> stringResource(R.string.play_analyse_short) - } - val description = stringResource(if (report) R.string.review_report_menu else R.string.review_menu) - val spokenState = when { - preparing -> stringResource(R.string.preparing_engine) - progress != null -> stringResource(R.string.review_progress, progress.first, progress.second) - else -> null - } - val action by rememberUpdatedState(onClick) - val dark = LocalChessColors.current.dark - val accent = nagColor(3, dark) ?: LocalContentColor.current - val disabled = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) - val filled = enabled && !report && !preparing && progress == null - val iconColor = when { - !enabled -> disabled - filled && dark -> Color(0xFF1B1B1B) - filled -> Color.White - else -> accent - } - Column( - modifier - .fillMaxHeight() - .clearAndSetSemantics { - contentDescription = description - role = Role.Button - if (enabled) onClick(description) { action(); true } else disabled() - spokenState?.let { stateDescription = it } - } - .combinedClickable( - enabled = enabled, - onClickLabel = description, - role = Role.Button, - hapticFeedbackEnabled = false, - onClick = action, - ), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Center, - ) { - Box( - Modifier.size(36.dp).clip(RoundedCornerShape(10.dp)).background(if (filled) accent else Color.Transparent), - contentAlignment = Alignment.Center, - ) { - Icon(Icons.Rounded.QueryStats, null, tint = iconColor) - when { - progress != null -> CircularProgressIndicator( - progress = { progress.first.toFloat() / progress.second.coerceAtLeast(1) }, - modifier = Modifier.size(34.dp), - color = if (enabled) accent else disabled, - strokeWidth = 2.dp, - ) - preparing -> CircularProgressIndicator( - modifier = Modifier.size(34.dp), - color = if (enabled) accent else disabled, - strokeWidth = 2.dp, - ) - } - } - if (showLabel) { - Text( - label, - style = MaterialTheme.typography.labelSmall.merge(Tabular), - color = if (enabled) MaterialTheme.colorScheme.onSurface else disabled, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Box(Modifier.padding(top = 2.dp).width(24.dp).height(2.dp)) - } -} - /// The row of continuations at a fork (§7.5): the line's own move first and filled. @Composable private fun Forks(moves: List, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) { @@ -1831,50 +1641,57 @@ private fun Forks(moves: List, san: (String) -> AnnotatedString, onMov } } -/// A button of the bottom bar. A tap is one action; an optional long press is a separate -/// action, never an auto-repeat. Long-press is also an accessibility custom action. -@OptIn(ExperimentalFoundationApi::class) +/// A button of the bottom bar. With `repeat`, holding it steps again after 400 ms and +/// then every 120 ms (§7.4). @Composable -internal fun BarButton( +private fun BarButton( icon: ImageVector, label: String, enabled: Boolean, modifier: Modifier, iconSize: Int = 24, + repeat: Boolean = false, mirrored: Boolean = false, - description: String = label, - onLongClickLabel: String? = null, - onLongClick: (() -> Unit)? = null, onClick: () -> Unit, ) { - val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) val action by rememberUpdatedState(onClick) - val longAction by rememberUpdatedState(onLongClick) + val on by rememberUpdatedState(enabled) + val interaction = remember { MutableInteractionSource() } + val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) Box( modifier .fillMaxHeight() - .clearAndSetSemantics { - contentDescription = description + .semantics { + contentDescription = label role = Role.Button - if (enabled) { - onClick(label) { action(); true } - if (onLongClickLabel != null && longAction != null) { - onLongClick(onLongClickLabel) { longAction?.invoke(); true } - customActions = listOf(CustomAccessibilityAction(onLongClickLabel) { longAction?.invoke(); true }) - } - } else { - disabled() - } + if (!enabled) disabled() + onClick { action(); true } } - .combinedClickable( - enabled = enabled, - onClickLabel = label, - role = Role.Button, - onLongClickLabel = onLongClickLabel, - onLongClick = onLongClick, - hapticFeedbackEnabled = false, - onClick = onClick, - ), + .indication(interaction, ripple(bounded = false, radius = 32.dp)) + .pointerInput(repeat) { + detectTapGestures(onPress = { at -> + if (!on) return@detectTapGestures + val press = PressInteraction.Press(at) + interaction.emit(press) + action() + coroutineScope { + val job = if (repeat) { + launch { + delay(400) + while (on) { + action() + delay(120) + } + } + } else { + null + } + tryAwaitRelease() + job?.cancel() + } + interaction.emit(PressInteraction.Release(press)) + }) + }, contentAlignment = Alignment.Center, ) { Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier)) diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt index 403064e..ada8ff3 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/GamesScreen.kt @@ -73,7 +73,6 @@ import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHost import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material.icons.rounded.Download -import androidx.compose.material.icons.rounded.Groups import io.github.vrubelroman.chesspenguin.theme.Tabular import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay @@ -87,12 +86,7 @@ private const val CHUNK = 100 /// The games of a database, with a search (android-ui.md §6). @OptIn(ExperimentalMaterial3Api::class) @Composable -fun GamesScreen( - db: String, - onBack: () -> Unit, - onGame: (place: Int, query: String) -> Unit, - onPlayers: () -> Unit = {}, -) { +fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: String) -> Unit) { val app = app() val entries by app.library.entries.collectAsState() val entry = entries.firstOrNull { it.id == db } @@ -202,7 +196,6 @@ fun GamesScreen( if (query.isEmpty()) searching = false else query = "" }) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) } } else if (database != null) { - IconButton(onClick = onPlayers) { Icon(Icons.Rounded.Groups, stringResource(R.string.players)) } IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) } // A downloaded database: its new games from here, where they are // looked for (android-ui.md §23.3); ✕ while they come. diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayersScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayersScreen.kt deleted file mode 100644 index a5b1749..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PlayersScreen.kt +++ /dev/null @@ -1,444 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.ExperimentalLayoutApi -import androidx.compose.foundation.layout.FlowRow -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.verticalScroll -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBack -import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight -import androidx.compose.material.icons.rounded.Close -import androidx.compose.material.icons.rounded.Search -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TextField -import androidx.compose.material3.TextFieldDefaults -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.platform.LocalDensity -import androidx.compose.ui.platform.LocalSoftwareKeyboardController -import androidx.compose.ui.res.pluralStringResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.disabled -import androidx.compose.ui.semantics.onClick -import androidx.compose.ui.semantics.role -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.style.TextAlign -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import io.github.vrubelroman.chesspenguin.R -import io.github.vrubelroman.chesspenguin.data.PrepBackends -import io.github.vrubelroman.chesspenguin.theme.Tabular -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay -import kotlinx.coroutines.withContext -import uniffi.mobile_api.Database -import java.text.Collator -import java.util.Locale - -private const val PLAYER_PAGE = 100 - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun PlayersScreen( - db: String, - onBack: () -> Unit, - onPrepare: (player: PlayerSummary, white: Boolean) -> Unit, -) { - val app = app() - val entries by app.library.entries.collectAsState() - val entry = entries.firstOrNull { it.id == db } - var database by remember { mutableStateOf(null) } - var openFailure by remember { mutableStateOf(null) } - val backend = remember(database) { database?.let(PrepBackends::open) } - DisposableEffect(backend) { onDispose { backend?.close() } } - - var searching by rememberSaveable { mutableStateOf(false) } - var query by rememberSaveable { mutableStateOf("") } - var colorChoice by remember { mutableStateOf(null) } - var players by remember { mutableStateOf?>(null) } - var nextOffset by remember { mutableStateOf(null) } - var failure by remember { mutableStateOf(null) } - var loadingMore by remember { mutableStateOf(false) } - var generation by remember { mutableIntStateOf(0) } - var retry by rememberSaveable { mutableIntStateOf(0) } - LaunchedEffect(db, entry?.games, entry?.updated, retry) { - database = null - openFailure = null - app.library.database(db).onSuccess { database = it }.onFailure { openFailure = it } - } - val list = rememberLazyListState() - val focus = remember { FocusRequester() } - val keyboard = LocalSoftwareKeyboardController.current - BackHandler(searching) { - searching = false - query = "" - } - - LaunchedEffect(backend, query, retry) { - val source = backend ?: return@LaunchedEffect - val expected = ++generation - players = null - nextOffset = null - failure = null - loadingMore = false - if (query.isNotEmpty()) delay(250) - try { - val page = withContext(Dispatchers.IO) { source.players(query, 0, PLAYER_PAGE) } - if (expected != generation) return@LaunchedEffect - players = sortPlayers(page.players) - nextOffset = page.nextOffset - } catch (e: kotlinx.coroutines.CancellationException) { - throw e - } catch (e: Throwable) { - if (expected == generation) failure = e - } - } - - Scaffold( - topBar = { - TopAppBar( - navigationIcon = { - IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(R.string.back)) } - }, - title = { - if (searching) { - TextField( - value = query, - onValueChange = { query = it }, - placeholder = { Text(stringResource(R.string.player_name_hint)) }, - singleLine = true, - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(onSearch = { keyboard?.hide() }), - colors = TextFieldDefaults.colors( - focusedContainerColor = Color.Transparent, - unfocusedContainerColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - unfocusedIndicatorColor = Color.Transparent, - ), - modifier = Modifier.fillMaxWidth().focusRequester(focus), - ) - LaunchedEffect(Unit) { focus.requestFocus() } - } else { - Column { - Text(stringResource(R.string.players), maxLines = 1, overflow = TextOverflow.Ellipsis) - Text( - entry?.let { displayName(it) } ?: "", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - }, - actions = { - if (searching) { - IconButton(onClick = { if (query.isEmpty()) searching = false else query = "" }) { - Icon(Icons.Rounded.Close, stringResource(R.string.clear)) - } - } else if (database != null) { - IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) } - } - }, - ) - }, - ) { padding -> - Box(Modifier.fillMaxSize().padding(padding)) { - val shownPlayers = players - when { - openFailure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(openFailure!!)) { - TextButton(onClick = { database = null; openFailure = null; retry += 1 }) { Text(stringResource(R.string.retry)) } - } - failure != null -> PrepMessage(stringResource(R.string.players_read_failed), openProblem(failure!!).ifEmpty { failure!!.message ?: "" }) { - TextButton(onClick = { retry += 1 }) { Text(stringResource(R.string.retry)) } - } - shownPlayers == null -> LoadingPlayers() - shownPlayers.isEmpty() && query.isEmpty() -> PrepMessage(stringResource(R.string.no_named_players), "") { - TextButton(onClick = onBack) { Text(stringResource(R.string.to_games)) } - } - shownPlayers.isEmpty() -> PrepMessage(stringResource(R.string.player_not_found), "") { - TextButton(onClick = { query = "" }) { Text(stringResource(R.string.reset_search)) } - } - else -> LazyColumn(Modifier.fillMaxSize(), state = list) { - val shown = shownPlayers - val expectedGeneration = generation - items(shown.size, key = { shown[it].id }) { index -> - val player = shown[index] - PlayerPrepRow( - player = player, - divider = index < shown.lastIndex || nextOffset != null, - onPlayerClick = { chosen -> - keyboard?.hide() - val onlyColor = solePlayerColor(chosen) - when { - playerNeedsColorChoice(chosen) -> colorChoice = chosen - onlyColor != null -> onPrepare(chosen, onlyColor) - } - }, - ) - if (index == shown.lastIndex && nextOffset != null) { - LaunchedEffect(nextOffset, generation) { - val source = backend ?: return@LaunchedEffect - val offset = nextOffset ?: return@LaunchedEffect - loadingMore = true - try { - val page = withContext(Dispatchers.IO) { source.players(query, offset, PLAYER_PAGE) } - if (expectedGeneration == generation) { - players = sortPlayers((shown + page.players).distinctBy { it.id }) - nextOffset = page.nextOffset - } - } catch (e: kotlinx.coroutines.CancellationException) { - throw e - } catch (e: Throwable) { - if (expectedGeneration == generation) failure = e - } finally { - if (expectedGeneration == generation) loadingMore = false - } - } - } - } - if (loadingMore) { - items(3, key = { "loading-$it" }) { PlayerPrepPlaceholder() } - } - } - } - } - } - colorChoice?.let { player -> - PlayerColorSheet( - player = player, - onDismiss = { colorChoice = null }, - onPrepare = { chosen, white -> - colorChoice = null - onPrepare(chosen, white) - }, - ) - } -} - -private fun sortPlayers(players: List): List { - val collator = Collator.getInstance(Locale.getDefault()).apply { strength = Collator.PRIMARY } - return players.sortedWith(compareBy(collator) { it.name }) -} - -internal fun playerNeedsColorChoice(player: PlayerSummary): Boolean = player.whiteGames > 0 && player.blackGames > 0 - -internal fun solePlayerColor(player: PlayerSummary): Boolean? = when { - player.whiteGames > 0 && player.blackGames == 0 -> true - player.blackGames > 0 && player.whiteGames == 0 -> false - else -> null -} - -@OptIn(ExperimentalLayoutApi::class) -@Composable -internal fun PlayerPrepRow( - player: PlayerSummary, - divider: Boolean = false, - onPlayerClick: (PlayerSummary) -> Unit, -) { - val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total)) - val whiteSide = stringResource(R.string.prep_as_white) - val blackSide = stringResource(R.string.prep_as_black) - val chooseColor = stringResource(R.string.prep_choose_color) - val prepare = stringResource(R.string.prepare_action) - val onlyColor = solePlayerColor(player) - val hasAction = playerNeedsColorChoice(player) || onlyColor != null - val action = when { - playerNeedsColorChoice(player) -> chooseColor - onlyColor == true -> "$prepare $whiteSide" - onlyColor == false -> "$prepare $blackSide" - else -> prepare - } - val description = "${player.name}, $games. $whiteSide ${groupDigits(player.whiteGames)}, $blackSide ${groupDigits(player.blackGames)}. $action" - BoxWithConstraints(Modifier.fillMaxWidth()) { - val grows = maxWidth < 320.dp || LocalDensity.current.fontScale > 1f - val height = if (grows) Modifier.heightIn(min = 72.dp) else Modifier.height(72.dp) - Box( - Modifier.fillMaxWidth().then(height) - .clearAndSetSemantics { - contentDescription = description - role = Role.Button - if (hasAction) onClick(action) { onPlayerClick(player); true } else disabled() - } - .clickable(enabled = hasAction, role = Role.Button, onClickLabel = action) { onPlayerClick(player) }, - ) { - Row( - Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Column(Modifier.weight(1f)) { - Row(Modifier.fillMaxWidth().heightIn(min = 24.dp), verticalAlignment = Alignment.CenterVertically) { - PlayerName(player.name, MaterialTheme.typography.bodyLarge, Modifier.weight(1f)) - Spacer(Modifier.width(8.dp)) - Text(games, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) - } - Spacer(Modifier.height(4.dp)) - FlowRow( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(16.dp), - verticalArrangement = Arrangement.spacedBy(4.dp), - ) { - PlayerColorText(true, whiteSide, player.whiteGames) - PlayerColorText(false, blackSide, player.blackGames) - } - } - Spacer(Modifier.width(8.dp)) - Icon( - Icons.AutoMirrored.Rounded.KeyboardArrowRight, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(24.dp), - ) - } - if (divider) HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant) - } - } -} - -@Composable -private fun PlayerColorText(white: Boolean, side: String, count: Int) { - Row(Modifier.heightIn(min = 20.dp), verticalAlignment = Alignment.CenterVertically) { - SideDisc(white) - Spacer(Modifier.width(8.dp)) - Text("$side · ${groupDigits(count)}", style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) - } -} - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -private fun PlayerColorSheet(player: PlayerSummary, onDismiss: () -> Unit, onPrepare: (PlayerSummary, Boolean) -> Unit) { - val games = pluralStringResource(R.plurals.games_count, player.total, groupDigits(player.total)) - ModalBottomSheet(onDismissRequest = onDismiss) { - Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { - Column(Modifier.fillMaxWidth().padding(horizontal = 24.dp, vertical = 8.dp)) { - Text( - stringResource(R.string.prep_against_player, player.name), - Modifier.fillMaxWidth(), - style = MaterialTheme.typography.titleLarge, - ) - Spacer(Modifier.height(4.dp)) - Text( - games, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - PlayerColorAction(player, true, onPrepare) - PlayerColorAction(player, false, onPrepare) - } - } -} - -@Composable -private fun PlayerColorAction(player: PlayerSummary, white: Boolean, onPrepare: (PlayerSummary, Boolean) -> Unit) { - val count = if (white) player.whiteGames else player.blackGames - val side = stringResource(if (white) R.string.prep_against_white else R.string.prep_against_black) - val games = pluralStringResource(R.plurals.games_count, count, groupDigits(count)) - val prepare = stringResource(R.string.prepare_action) - Row( - Modifier.fillMaxWidth().heightIn(min = 64.dp) - .clearAndSetSemantics { - contentDescription = "${player.name}, $side, $games. $prepare" - role = Role.Button - onClick(prepare) { onPrepare(player, white); true } - } - .clickable(role = Role.Button, onClickLabel = prepare) { onPrepare(player, white) } - .padding(horizontal = 24.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - SideDisc(white) - Spacer(Modifier.width(12.dp)) - Text(side, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) - Spacer(Modifier.width(8.dp)) - Text(groupDigits(count), style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) - Spacer(Modifier.width(8.dp)) - Icon(Icons.AutoMirrored.Rounded.KeyboardArrowRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(24.dp)) - } -} - -@Composable -private fun PlayerPrepPlaceholder() { - Box(Modifier.fillMaxWidth().height(72.dp)) { - Column(Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp)) { - Row(Modifier.fillMaxWidth().height(24.dp)) { - Box(Modifier.weight(1f).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp))) - Spacer(Modifier.width(8.dp)) - Box(Modifier.width(64.dp).height(24.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp))) - } - Spacer(Modifier.height(4.dp)) - Box(Modifier.fillMaxWidth(0.65f).height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow, RoundedCornerShape(4.dp))) - } - HorizontalDivider(Modifier.align(Alignment.BottomCenter), color = MaterialTheme.colorScheme.outlineVariant) - } -} - -@Composable -private fun LoadingPlayers() { - Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { - CircularProgressIndicator() - Spacer(Modifier.height(16.dp)) - Text(stringResource(R.string.reading_players), color = MaterialTheme.colorScheme.onSurfaceVariant) - } -} - -@Composable -internal fun PrepMessage(title: String, detail: String, action: (@Composable () -> Unit)? = null) { - Column(Modifier.fillMaxSize().padding(32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { - Text(title, style = MaterialTheme.typography.titleLarge, textAlign = TextAlign.Center) - if (detail.isNotEmpty()) { - Spacer(Modifier.height(8.dp)) - Text(detail, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center) - } - if (action != null) { - Spacer(Modifier.height(16.dp)) - action() - } - } -} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepController.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepController.kt deleted file mode 100644 index caf4dde..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepController.kt +++ /dev/null @@ -1,161 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import io.github.vrubelroman.chesspenguin.data.PrepBackend -import io.github.vrubelroman.chesspenguin.data.PrepQuery -import io.github.vrubelroman.chesspenguin.data.query -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext -import uniffi.mobile_api.GameData -import uniffi.mobile_api.GameSession - -internal class PrepController(val request: PrepStart) : ViewModel() { - var line by mutableStateOf(PrepLineState(request.startFen, request.startFen)) - private set - var data by mutableStateOf(null) - private set - var position by mutableStateOf(null) - private set - var failure by mutableStateOf(null) - private set - var loading by mutableStateOf(false) - private set - var initialised by mutableStateOf(false) - private set - var moveFailed by mutableStateOf(false) - var retry by mutableIntStateOf(0) - private set - - private var session: GameSession? = null - private var search: Job? = null - private var generation = 0L - - suspend fun initialise() { - if (session != null) return - failure = null - val loaded = withContext(Dispatchers.Default) { - runCatching { - val fen = request.startFen - val s = GameSession.fromPgn("[SetUp \"1\"]\n[FEN \"$fen\"]\n\n*") - try { - var edited = s.data() to 0 - for (uci in request.moves) { - val next = s.play(edited.second.toUInt(), uci) - edited = next.data to next.cursor.toInt() - } - Triple(s, edited.first, edited.second) - } catch (e: Throwable) { - s.close() - throw e - } - } - } - if (session != null) { - loaded.getOrNull()?.first?.close() - return - } - val (s, game, cursor) = loaded.getOrElse { - failure = it - initialised = false - return - } - session = s - data = game - line = prepLine(game, cursor, request.startFen) - initialised = true - } - - private fun invalidate() { - generation += 1 - search?.cancel() - position = null - failure = null - loading = false - } - - fun back() { - if (!line.canBack) return - line = line.back() - invalidate() - } - - fun forward() { - if (!line.canForward) return - line = line.forward() - invalidate() - } - - fun start() { - if (!line.canBack) return - line = line.start() - invalidate() - } - - fun end() { - if (!line.canForward) return - line = line.end() - invalidate() - } - - fun legalMoves(): List = session?.legalMoves(line.currentNode.toUInt()).orEmpty() - - fun play(uci: String): String? { - val s = session ?: return null - if (s.legalMoves(line.currentNode.toUInt()).none { it == uci }) return null - val edited = runCatching { s.play(line.currentNode.toUInt(), uci) }.getOrElse { - moveFailed = true - return null - } - val visible = prepLine(edited.data, edited.cursor.toInt(), request.startFen) - line = visible - data = edited.data - invalidate() - return visible.last?.san - } - - fun repeat() { - retry += 1 - invalidate() - } - - fun search(backend: PrepBackend) { - if (!initialised || failure != null) return - invalidate() - backend.cancel() - val query: PrepQuery = request.query(line.fen) - val expected = generation - search = viewModelScope.launch { - val delayed = launch { - delay(300) - if (generation == expected) loading = true - } - try { - val answer = withContext(Dispatchers.IO) { backend.position(query) } - if (generation == expected && query == request.query(line.fen)) position = answer - } catch (e: CancellationException) { - throw e - } catch (e: Throwable) { - if (generation == expected && query == request.query(line.fen)) failure = e - } finally { - delayed.cancel() - if (generation == expected) loading = false - } - } - } - - override fun onCleared() { - generation += 1 - search?.cancel() - session?.close() - session = null - } -} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepModels.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepModels.kt deleted file mode 100644 index a218043..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepModels.kt +++ /dev/null @@ -1,187 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import kotlinx.serialization.Serializable -import uniffi.mobile_api.GameData -import kotlin.math.roundToInt - -internal const val STANDARD_START = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" - -/// The position and history of a preparation request. The game document is not part of it. -@Serializable -data class PrepStart( - val db: String, - val player: String, - val white: Boolean, - val startFen: String = STANDARD_START, - val moves: List = emptyList(), - val fromGame: Boolean = false, -) - -/// One move of the temporary line. `node` belongs only to this preparation session. -@Serializable -data class PrepLineStep( - val node: Int, - val uci: String, - val san: String, - val moveNumber: Int, - val white: Boolean, - val fen: String, - val from: String?, - val to: String?, -) { - val label: String get() = "$moveNumber${if (white) "." else "…"}$san" -} - -/// A linear, read-only exploration. Going back never chooses a different continuation; -/// making a move after going back drops only this temporary future. -@Serializable -data class PrepLineState( - val startFen: String, - val rootFen: String, - val rootNode: Int = 0, - val steps: List = emptyList(), - val cursor: Int = 0, -) { - init { - require(cursor in 0..steps.size) { "line cursor is outside the line" } - } - - val fen: String get() = steps.getOrNull(cursor - 1)?.fen ?: rootFen - val currentNode: Int get() = steps.getOrNull(cursor - 1)?.node ?: rootNode - val last: PrepLineStep? get() = steps.getOrNull(cursor - 1) - val moves: List get() = steps.map { it.uci } - val canBack: Boolean get() = cursor > 0 - val canForward: Boolean get() = cursor < steps.size - - fun back(): PrepLineState = if (canBack) copy(cursor = cursor - 1) else this - fun forward(): PrepLineState = if (canForward) copy(cursor = cursor + 1) else this - fun start(): PrepLineState = if (canBack) copy(cursor = 0) else this - fun end(): PrepLineState = if (canForward) copy(cursor = steps.size) else this - - fun replaceVisibleLine(visible: List, currentNode: Int): PrepLineState { - val at = visible.indexOfLast { it.node == currentNode } - require(at >= 0 && at + 1 == visible.size) { "the played move must end the visible line" } - return copy(steps = visible, cursor = visible.size) - } -} - -internal fun prepLine(data: GameData, cursor: Int, startFen: String): PrepLineState { - val path = ArrayList() - var at: Int? = cursor - while (at != null) { - if (at !in data.nodes.indices || at in path) break - path += at - at = data.nodes[at].parent?.toInt() - } - path.reverse() - val root = path.firstOrNull() ?: 0 - val steps = path.drop(1).mapNotNull { id -> - val n = data.nodes[id] - if (n.uci.isEmpty()) return@mapNotNull null - PrepLineStep(id, n.uci, n.san, n.moveNumber.toInt(), n.white, n.fen, n.fromSquare, n.toSquare) - } - return PrepLineState(startFen, data.nodes.getOrNull(root)?.fen ?: startFen, root, steps, steps.size) -} - -/// A null move cannot be represented by the normal-move position search. -internal fun prepStartFromGame(data: GameData, at: Int, db: String, player: String, white: Boolean): PrepStart? { - if (at !in data.nodes.indices) return null - val path = ArrayList() - var node: Int? = at - while (node != null) { - if (node !in data.nodes.indices || node in path) return null - path += node - node = data.nodes[node].parent?.toInt() - } - path.reverse() - if (path.any { data.nodes[it].nullMove }) return null - val moves = path.drop(1).map { data.nodes[it].uci } - if (moves.any { it.isEmpty() }) return null - return PrepStart( - db = db, - player = player, - white = white, - startFen = data.nodes[path.first()].fen, - moves = moves, - fromGame = true, - ) -} - -/// Preparation shows the user's side at the bottom, opposite to the selected opponent. -internal fun prepBoardStartsFlipped(opponentWhite: Boolean): Boolean = opponentWhite - -internal fun prepWhiteToMove(fen: String): Boolean? = fen.split(' ').getOrNull(1)?.let { - when (it) { - "w" -> true - "b" -> false - else -> null - } -} - -internal fun moveLabel(fen: String, san: String): String { - val fields = fen.split(' ') - val number = fields.getOrNull(5)?.toIntOrNull()?.coerceAtLeast(0) ?: 1 - val white = prepWhiteToMove(fen) ?: true - return "$number${if (white) "." else "…"}$san" -} - -data class PlayerSummary( - val id: Int, - val name: String, - val total: Int, - val whiteGames: Int, - val blackGames: Int, -) - -data class PlayerPage( - val players: List, - val total: Int, - val nextOffset: Int?, -) - -data class PrepContinuation( - val uci: String, - val san: String, - val games: Int, - val wins: Int, - val draws: Int, - val losses: Int, - val unknown: Int = 0, -) { - val from: String? get() = uci.takeIf { it.length >= 4 }?.substring(0, 2) - val to: String? get() = uci.takeIf { it.length >= 4 }?.substring(2, 4) -} - -/// A matching game is part of the result contract even though its list is outside this MVP. -data class PrepGameMatch(val index: UInt, val ply: UInt) - -data class PrepPosition( - val games: Int, - val continuations: List, - val endedHere: Int = 0, - val noNormalContinuation: Int = 0, - val unknownResults: Int = 0, - val playerToMove: Boolean? = null, - val matches: List = emptyList(), - val matchesTotal: Int = 0, -) - -internal fun sortedContinuations(position: PrepPosition): List = - position.continuations.sortedWith(compareByDescending { it.games }.thenBy { it.san }) - -internal fun frequencyPercent(games: Int, total: Int): String = when { - games <= 0 || total <= 0 -> "0" - games * 100L < total -> "<1" - else -> (games * 100.0 / total).roundToInt().toString() -} - -internal fun outcomePercents(move: PrepContinuation): Triple { - val known = move.wins + move.draws + move.losses - if (known <= 0) return Triple("—", "—", "—") - fun percent(n: Int) = (n * 100.0 / known).roundToInt().toString() - return Triple(percent(move.wins), percent(move.draws), percent(move.losses)) -} - -internal class PrepOutOfMemory : IllegalStateException("Not enough memory for the position index") -internal class PrepSearchFailed(message: String) : IllegalStateException(message) -internal class PrepPlayerNotFound(name: String) : IllegalStateException("Player is not in this database: $name") diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepScreen.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepScreen.kt deleted file mode 100644 index e7317f8..0000000 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/PrepScreen.kt +++ /dev/null @@ -1,469 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import android.content.res.Configuration -import androidx.compose.foundation.background -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.WindowInsets -import androidx.compose.foundation.layout.WindowInsetsSides -import androidx.compose.foundation.layout.fillMaxHeight -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.heightIn -import androidx.compose.foundation.layout.navigationBars -import androidx.compose.foundation.layout.navigationBarsPadding -import androidx.compose.foundation.layout.only -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.layout.windowInsetsPadding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.rememberLazyListState -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.automirrored.rounded.ArrowBack -import androidx.compose.material.icons.rounded.PlayArrow -import androidx.compose.material.icons.rounded.SwapVert -import androidx.compose.material3.CircularProgressIndicator -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.LinearProgressIndicator -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.ModalBottomSheet -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.material3.TopAppBar -import androidx.compose.runtime.Composable -import androidx.compose.runtime.DisposableEffect -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.collectAsState -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.saveable.rememberSaveable -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester -import androidx.compose.foundation.focusable -import androidx.compose.ui.platform.LocalConfiguration -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.res.pluralStringResource -import androidx.compose.ui.res.stringResource -import androidx.compose.ui.semantics.LiveRegionMode -import androidx.compose.ui.semantics.Role -import androidx.compose.ui.semantics.clearAndSetSemantics -import androidx.compose.ui.semantics.contentDescription -import androidx.compose.ui.semantics.liveRegion -import androidx.compose.ui.semantics.onClick -import androidx.compose.ui.semantics.role -import androidx.compose.ui.semantics.semantics -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.lifecycle.viewmodel.compose.viewModel -import io.github.vrubelroman.chesspenguin.R -import io.github.vrubelroman.chesspenguin.data.PrepBackends -import io.github.vrubelroman.chesspenguin.theme.Tabular -import uniffi.mobile_api.Database - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun PrepScreen(request: PrepStart, onBack: () -> Unit) { - val app = app() - val context = LocalContext.current - val controller: PrepController = viewModel(key = "prep") { PrepController(request) } - val entries by app.library.entries.collectAsState() - val entry = entries.firstOrNull { it.id == request.db } - var database by remember { mutableStateOf(null) } - var openFailure by remember { mutableStateOf(null) } - var openRetry by rememberSaveable { mutableIntStateOf(0) } - LaunchedEffect(request.db, entry?.games, entry?.updated, openRetry) { - database = null - openFailure = null - controller.repeat() - app.library.database(request.db).onSuccess { database = it }.onFailure { openFailure = it } - } - val backend = remember(database) { database?.let(PrepBackends::open) } - DisposableEffect(backend) { onDispose { backend?.cancel(); backend?.close() } } - LaunchedEffect(controller.retry) { controller.initialise() } - LaunchedEffect(backend, controller.initialised, controller.line, controller.retry) { - if (backend != null && controller.initialised) controller.search(backend) - } - - val prefs by app.settings.prefs.collectAsState() - val lang = uiLanguage() - val san = remember(prefs.notation, lang) { { value: String -> displaySan(value, prefs.notation, lang) } } - val pieces = remember { Pieces(context) } - var flipped by rememberSaveable { mutableStateOf(prepBoardStartsFlipped(request.white)) } - var conflicts by remember { mutableStateOf>(emptyList()) } - val list = rememberLazyListState() - val contextFocus = remember { FocusRequester() } - val snackbar = remember { SnackbarHostState() } - val moveFailed = stringResource(R.string.prep_move_failed) - LaunchedEffect(controller.moveFailed) { - if (controller.moveFailed) { - snackbar.showSnackbar(moveFailed) - controller.moveFailed = false - } - } - - fun play(uci: String) { - val played = controller.play(uci) ?: return - conflicts = emptyList() - app.sounds.move(played) - contextFocus.requestFocus() - } - - fun arrowsChosen(moves: List) { - when (moves.size) { - 0 -> {} - 1 -> play(moves[0]) - else -> conflicts = moves - } - } - - val position = controller.position - val continuations = position?.let(::sortedContinuations).orEmpty() - val arrowContinuations = continuations.distinctBy { it.from to it.to }.take(3) - val arrows = arrowContinuations.mapIndexedNotNull { index, move -> - val from = move.from ?: return@mapIndexedNotNull null - val to = move.to ?: return@mapIndexedNotNull null - val weight = if (index == 0) 1f else if (index == 1) 0.85f else 0.70f - val alpha = if (index == 0) 0.63f else if (index == 1) 0.45f else 0.35f - BoardArrow(from, to, EngineArrow.copy(alpha = alpha), weight) - } - val arrowMoves = continuations.filter { move -> arrowContinuations.any { it.from == move.from && it.to == move.to } } - .mapNotNull { move -> - val from = move.from ?: return@mapNotNull null - val to = move.to ?: return@mapNotNull null - val label = moveLabel(controller.line.fen, move.san) - val games = pluralStringResource(R.plurals.games_count, move.games, groupDigits(move.games)) - val action = stringResource(R.string.prep_play_continuation, label, games, frequencyPercent(move.games, position?.games ?: 0)) - BoardArrowMove(move.uci, from, to, action) - } - val last = controller.line.last - val boardDescription = if (last == null) { - stringResource(R.string.prep_board_start, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white)) - } else { - stringResource(R.string.prep_board_after, last.label, if (flipped) stringResource(R.string.color_black) else stringResource(R.string.color_white)) - } - val board: @Composable (Modifier) -> Unit = { modifier -> - Board( - fen = controller.line.fen, - flipped = flipped, - lastFrom = last?.from, - lastTo = last?.to, - pieces = pieces, - theme = prefs.board, - set = prefs.pieces, - description = boardDescription, - modifier = modifier, - arrows = arrows, - arrowMoves = arrowMoves, - onArrowMoves = ::arrowsChosen, - check = last?.san?.let { it.endsWith("+") || it.endsWith("#") } == true, - animated = prefs.animation, - input = if (controller.initialised && controller.data != null) { - BoardInput(controller.legalMoves(), onMove = ::play) - } else { - null - }, - ) - } - - val turnWhite = prepWhiteToMove(controller.line.fen) - val opponentPlays = position?.playerToMove ?: (turnWhite == request.white) - val sideToMove = when (turnWhite) { - true -> stringResource(R.string.turn_white) - false -> stringResource(R.string.turn_black) - null -> "" - } - val who = stringResource(if (opponentPlays) R.string.prep_opponent_plays else R.string.prep_opponents_play) - val where = last?.let { stringResource(R.string.prep_after, it.label) } ?: stringResource(R.string.prep_beginning) - val gamesCount = position?.games - val gamesText = if (gamesCount == null) "…" else pluralStringResource(R.plurals.games_count, gamesCount, groupDigits(gamesCount)) - val contextDescription = stringResource(R.string.prep_context_description, who, sideToMove, where, gamesText) - val contextRow: @Composable () -> Unit = { - Row( - Modifier.fillMaxWidth().heightIn(min = 32.dp).focusRequester(contextFocus).focusable() - .semantics(mergeDescendants = true) { - contentDescription = contextDescription - liveRegion = LiveRegionMode.Polite - } - .padding(horizontal = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text( - "$who · $where", - Modifier.weight(1f), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - Spacer(Modifier.width(8.dp)) - Text(gamesText, style = MaterialTheme.typography.bodyMedium.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) - } - } - val results: @Composable (Modifier) -> Unit = { modifier -> - Box(modifier) { - when { - openFailure != null -> PrepMessage(stringResource(R.string.prep_failed), openProblem(openFailure!!)) { - TextButton(onClick = { openRetry += 1 }) { Text(stringResource(R.string.retry)) } - } - controller.failure != null -> { - val memory = controller.failure is PrepOutOfMemory - val problem = openProblem(controller.failure!!).ifEmpty { controller.failure!!.message ?: "" } - PrepMessage(stringResource(if (memory) R.string.prep_no_memory else R.string.prep_failed), problem) { - TextButton(onClick = { controller.repeat() }) { Text(stringResource(R.string.retry)) } - } - } - position == null && controller.loading -> { - LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopStart)) - Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { - CircularProgressIndicator() - Spacer(Modifier.height(16.dp)) - Text(stringResource(R.string.prep_calculating), color = MaterialTheme.colorScheme.onSurfaceVariant) - } - } - position == null -> PrepPlaceholders() - position.games == 0 -> PrepMessage( - stringResource(R.string.prep_position_absent, request.player), - stringResource(R.string.prep_position_absent_hint), - ) - continuations.isEmpty() && position.endedHere == position.games -> PrepMessage(stringResource(R.string.prep_all_ended), "") - else -> LazyColumn(Modifier.fillMaxSize(), state = list) { - items(continuations.size, key = { continuations[it].uci }) { index -> - ContinuationRow( - continuation = continuations[index], - total = position.games, - fen = controller.line.fen, - player = request.player, - san = san, - divider = index < continuations.lastIndex, - onClick = { play(continuations[index].uci) }, - ) - } - if (position.endedHere > 0 && continuations.isNotEmpty()) { - item(key = "ended") { PrepDisabledRow(stringResource(R.string.prep_ended_here, groupDigits(position.endedHere))) } - } - if (position.noNormalContinuation > 0) { - item(key = "no-normal") { PrepDisabledRow(stringResource(R.string.prep_no_normal, groupDigits(position.noNormalContinuation))) } - } - } - } - } - } - val controls: @Composable () -> Unit = { - PrepControls( - canBack = controller.line.canBack, - canForward = controller.line.canForward, - onFlip = { flipped = !flipped }, - onBack = controller::back, - onForward = controller::forward, - onStart = controller::start, - onEnd = controller::end, - ) - } - val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE - Scaffold( - topBar = { - TopAppBar( - navigationIcon = { - IconButton(onClick = onBack) { - Icon(Icons.AutoMirrored.Rounded.ArrowBack, stringResource(if (request.fromGame) R.string.to_game else R.string.to_players)) - } - }, - title = { - Column { - PlayerName(request.player, MaterialTheme.typography.titleMedium) - Text( - stringResource(if (request.white) R.string.prep_as_white else R.string.prep_as_black) + " · " + (entry?.let { displayName(it) } ?: ""), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - }, - ) - }, - snackbarHost = { SnackbarHost(snackbar) }, - bottomBar = { if (!landscape) controls() }, - ) { padding -> - val inner = Modifier.fillMaxSize().padding(padding) - if (landscape) { - Row(inner.windowInsetsPadding(WindowInsets.navigationBars.only(WindowInsetsSides.Horizontal))) { - board(Modifier.fillMaxHeight()) - Column(Modifier.weight(1f).fillMaxHeight()) { - contextRow() - results(Modifier.weight(1f).fillMaxWidth()) - controls() - } - } - } else { - Column(inner, horizontalAlignment = Alignment.CenterHorizontally) { - board(Modifier.widthIn(max = 480.dp).fillMaxWidth()) - Column(Modifier.widthIn(max = 480.dp).fillMaxWidth().weight(1f)) { - contextRow() - results(Modifier.weight(1f).fillMaxWidth()) - } - } - } - } - - if (conflicts.isNotEmpty()) { - ModalBottomSheet(onDismissRequest = { conflicts = emptyList() }) { - Column(Modifier.fillMaxWidth().padding(bottom = 24.dp)) { - Text(stringResource(R.string.prep_choose_move), style = MaterialTheme.typography.titleLarge, modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)) - conflicts.mapNotNull { uci -> continuations.firstOrNull { it.uci == uci } }.forEach { move -> - Row( - Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable { play(move.uci) }.padding(horizontal = 24.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - Text(san(moveLabel(controller.line.fen, move.san)), style = MaterialTheme.typography.bodyLarge) - } - } - } - } - } -} - -@Composable -internal fun ContinuationRow( - continuation: PrepContinuation, - total: Int, - fen: String, - player: String, - san: (String) -> AnnotatedString, - divider: Boolean, - onClick: () -> Unit, -) { - val label = moveLabel(fen, continuation.san) - val frequency = frequencyPercent(continuation.games, total) - val (wins, draws, losses) = outcomePercents(continuation) - val games = pluralStringResource(R.plurals.games_count, total, groupDigits(total)) - val winsText = pluralStringResource(R.plurals.prep_wins, continuation.wins, groupDigits(continuation.wins)) - val drawsText = pluralStringResource(R.plurals.prep_draws, continuation.draws, groupDigits(continuation.draws)) - val lossesText = pluralStringResource(R.plurals.prep_losses, continuation.losses, groupDigits(continuation.losses)) - val unknown = if (continuation.unknown > 0) stringResource(R.string.prep_unknown_accessibility, continuation.unknown) else "" - val description = stringResource( - R.string.prep_continuation_description, - continuation.san, - continuation.games, - games, - frequency, - player, - winsText, - drawsText, - lossesText, - wins, - draws, - losses, - unknown, - ) - Column( - Modifier.fillMaxWidth().heightIn(min = 56.dp).clickable(onClickLabel = stringResource(R.string.prep_play), role = Role.Button, onClick = onClick) - .clearAndSetSemantics { - contentDescription = description - role = Role.Button - onClick { onClick(); true } - } - .padding(start = 16.dp, top = 5.dp, end = 16.dp, bottom = 5.dp), - ) { - Row(verticalAlignment = Alignment.CenterVertically) { - Text(san(label), Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge.copy(fontSize = androidx.compose.ui.unit.TextUnit(17f, androidx.compose.ui.unit.TextUnitType.Sp)), maxLines = 1, overflow = TextOverflow.Ellipsis) - Spacer(Modifier.width(8.dp)) - Text( - "${groupDigits(continuation.games)}/${groupDigits(total)} · $frequency %", - style = MaterialTheme.typography.bodyMedium.merge(Tabular), - maxLines = 1, - softWrap = false, - ) - } - val raw = buildString { - if (continuation.unknown > 0) append(stringResource(R.string.prep_unknown_short, groupDigits(continuation.unknown))).append(' ') - append(stringResource(R.string.prep_wdl_counts, groupDigits(continuation.wins), groupDigits(continuation.draws), groupDigits(continuation.losses), wins, draws, losses)) - } - Text(raw, style = MaterialTheme.typography.labelSmall.merge(Tabular), color = MaterialTheme.colorScheme.onSurfaceVariant) - if (divider) HorizontalDivider(Modifier.padding(top = 5.dp), color = MaterialTheme.colorScheme.outlineVariant) - } -} - -@Composable -private fun PrepDisabledRow(text: String) { - Text( - text, - Modifier.fillMaxWidth().heightIn(min = 48.dp).padding(horizontal = 16.dp, vertical = 12.dp), - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) -} - -@Composable -private fun PrepPlaceholders() { - Column(Modifier.fillMaxWidth()) { - repeat(4) { - Column(Modifier.fillMaxWidth().height(56.dp).padding(horizontal = 16.dp, vertical = 8.dp)) { - Box(Modifier.fillMaxWidth().height(20.dp).background(MaterialTheme.colorScheme.surfaceContainerLow)) - Spacer(Modifier.height(4.dp)) - Box(Modifier.fillMaxWidth().height(16.dp).background(MaterialTheme.colorScheme.surfaceContainerLow)) - } - HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) - } - } -} - -@Composable -internal fun PrepControls( - canBack: Boolean, - canForward: Boolean, - onFlip: () -> Unit, - onBack: () -> Unit, - onForward: () -> Unit, - onStart: () -> Unit, - onEnd: () -> Unit, -) { - Surface(color = MaterialTheme.colorScheme.surfaceContainer) { - Row(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) { - BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.width(72.dp), onClick = onFlip) - BarButton( - icon = Icons.Rounded.PlayArrow, - label = stringResource(R.string.move_back), - description = stringResource(R.string.move_back_hint), - enabled = canBack, - modifier = Modifier.weight(1f), - iconSize = 32, - mirrored = true, - onLongClickLabel = stringResource(R.string.to_start), - onLongClick = onStart, - onClick = onBack, - ) - BarButton( - icon = Icons.Rounded.PlayArrow, - label = stringResource(R.string.move_forward), - description = stringResource(R.string.move_forward_hint), - enabled = canForward, - modifier = Modifier.weight(1f), - iconSize = 32, - onLongClickLabel = stringResource(R.string.to_end), - onLongClick = onEnd, - onClick = onForward, - ) - } - } -} diff --git a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt index 655bd2f..48012e7 100644 --- a/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt +++ b/androidApp/app/src/main/java/io/github/vrubelroman/chesspenguin/ui/ReviewViews.kt @@ -35,6 +35,9 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @@ -67,7 +70,8 @@ import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import io.github.vrubelroman.chesspenguin.R -import io.github.vrubelroman.chesspenguin.data.GUESS_NPS +import io.github.vrubelroman.chesspenguin.data.GUESS_NPS_PER_THREAD +import io.github.vrubelroman.chesspenguin.data.REVIEW_NODES import io.github.vrubelroman.chesspenguin.theme.LocalChessColors import io.github.vrubelroman.chesspenguin.theme.Tabular import io.github.vrubelroman.chesspenguin.theme.nagColor @@ -76,6 +80,7 @@ import uniffi.mobile_api.MoveJudgement import uniffi.mobile_api.ReviewMove import uniffi.mobile_api.ReviewState import uniffi.mobile_api.SideReview +import kotlin.math.ceil import kotlin.math.roundToInt /// The NAG of the same sign: $3 !!, $1 !, $6 ?!, $2 ?, $4 ??. @@ -222,19 +227,6 @@ fun ReviewPanel( TextButton(onClick = onResume) { Text(stringResource(R.string.review_resume)) } report() } - // Made with other engine settings (before the fixed search): made again. - state.stale -> { - Text( - stringResource(R.string.review_stale), - style = textStyle, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = Modifier.weight(1f), - ) - TextButton(onClick = onResume) { Text(stringResource(R.string.review_update)) } - report() - } state.missing > 0u || state.secondsMissing > 0u -> { Text( // An analysis from before !! and !: filling in looks for them only. @@ -419,13 +411,15 @@ fun EvalGraph(state: ReviewState, cursor: Int?, cursorLabel: String?, onIndex: ( } } -/// The sheet that starts the analysis (§21.2): what it does and how long it takes. The -/// engine search is fixed, the same on every phone and computer: nothing to choose. +/// The sheet that starts the analysis (§21.2). @OptIn(ExperimentalMaterial3Api::class) @Composable fun ReviewStartSheet( state: ReviewState?, - npsPerProcess: Long, + quality: Int, + threads: Int, + npsPerThread: Long, + onQuality: (Int) -> Unit, onStart: (full: Boolean) -> Unit, onDismiss: () -> Unit, ) { @@ -434,17 +428,31 @@ fun ReviewStartSheet( Text(stringResource(R.string.review_menu), style = MaterialTheme.typography.titleLarge) Spacer(Modifier.height(12.dp)) Text(stringResource(R.string.review_text), style = MaterialTheme.typography.bodyLarge) + Spacer(Modifier.height(20.dp)) + Text(stringResource(R.string.review_quality), style = MaterialTheme.typography.labelLarge) + Spacer(Modifier.height(8.dp)) + val names = listOf(R.string.review_fast, R.string.review_normal, R.string.review_deep) + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { + names.forEachIndexed { i, res -> + SegmentedButton( + selected = quality == i, + onClick = { onQuality(i) }, + shape = SegmentedButtonDefaults.itemShape(i, names.size), + ) { Text(stringResource(res), maxLines = 1) } + } + } Spacer(Modifier.height(12.dp)) val total = state?.positions?.toInt() ?: 0 val missing = state?.missing?.toInt() ?: total - // Evaluations from the PGN: the engine makes its own, all of them. - val pgn = state != null && state.hasData && state.nodes == 0UL - // Some positions already have an engine evaluation of today's search: filled in. - val partial = state != null && state.hasData && !pgn && !state.stale && missing in 1 until total + // Some positions already have an engine evaluation: fill in, or start over. + val partial = state != null && state.hasData && state.nodes > 0UL && missing in 1 until total val positions = if (partial) missing else total + // "Fill in" keeps the quality of the first run; the choice is for starting over. + val nodes = (if (partial) state.nodes else REVIEW_NODES[quality.coerceIn(0, REVIEW_NODES.size - 1)]).toDouble() + val nps = (if (npsPerThread > 0) npsPerThread else GUESS_NPS_PER_THREAD).toDouble() * threads.coerceAtLeast(1) // A full run also searches again for moves that could be !! or ! (about a third more). val searches = if (partial) positions else (state?.searches?.toInt() ?: positions) - val secs = uniffi.mobile_api.reviewEstimateSecs(searches.toUInt(), (if (npsPerProcess > 0) npsPerProcess else GUESS_NPS).toULong()).toInt().coerceAtLeast(1) + val secs = ceil(searches * nodes / nps).toInt().coerceAtLeast(1) val time = if (secs < 60) stringResource(R.string.review_seconds, secs) else stringResource(R.string.review_minutes, (secs + 59) / 60) Text( pluralStringResource(R.plurals.review_estimate, positions, positions, time), @@ -461,10 +469,14 @@ fun ReviewStartSheet( } Spacer(Modifier.height(24.dp)) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { - TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } - // The same search again would give the same evaluations: only the missing - // ones are made, or all of them over the PGN's (or a stale analysis). - Button(onClick = { onStart(pgn) }) { Text(stringResource(if (partial) R.string.review_fill else R.string.review_start)) } + if (partial) { + TextButton(onClick = { onStart(true) }) { Text(stringResource(R.string.review_restart)) } + Button(onClick = { onStart(false) }) { Text(stringResource(R.string.review_fill)) } + } else { + TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) } + // Everything evaluated already: analysing again starts over. + Button(onClick = { onStart(state?.hasData == true) }) { Text(stringResource(R.string.review_start)) } + } } } } @@ -590,18 +602,11 @@ fun ReviewSheet( if (state.nodes == 0UL) { Text(stringResource(R.string.review_no_notes), style = MaterialTheme.typography.bodySmall, color = variant) } - if (state.stale) { - Text(stringResource(R.string.review_stale), style = MaterialTheme.typography.bodySmall, color = variant) - } Spacer(Modifier.height(20.dp)) // With a large font the two buttons go on two lines instead of breaking words. FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { TextButton(onClick = onHide) { Text(stringResource(R.string.review_hide)) } - // Over evaluations of the PGN the engine can make its own; an engine - // analysis made again would only repeat itself. - if (state.nodes == 0UL) { - OutlinedButton(onClick = onAgain, enabled = !state.running) { Text(stringResource(R.string.review_engine)) } - } + OutlinedButton(onClick = onAgain, enabled = !state.running) { Text(stringResource(R.string.review_again)) } } } } diff --git a/androidApp/app/src/main/res/values-de/strings.xml b/androidApp/app/src/main/res/values-de/strings.xml index d5bc812..923d260 100644 --- a/androidApp/app/src/main/res/values-de/strings.xml +++ b/androidApp/app/src/main/res/values-de/strings.xml @@ -36,8 +36,6 @@ Zum Anfang Zug zurück Zug vor - Vorheriger Zug. Gedrückt halten: zum Anfang - Nächster Zug. Gedrückt halten: zum Ende der Variante Zum Ende der Variante Weiter: Brett, Stellung nach %1$s @@ -215,14 +213,6 @@ In einer anderen App kopierte Partien Keine PGN-Partien in der Zwischenablage Eingefügt am %1$s - - Partie in der Zwischenablage - Partien in der Zwischenablage - - Diese PGN-Partie speichern und auf dem Brett öffnen? - %1$s speichern und die erste Partie auf dem Brett öffnen? Alle Partien bleiben in der lokalen Kopie. - Öffnen - Zwischenablage Datei wird geöffnet… Die Datei ließ sich nicht öffnen Diese Datei enthält keine Schachpartien. @@ -235,10 +225,15 @@ Partieanalyse Partiebericht Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert. + Qualität + Schnell + Normal + Gründlich %d s %d Min. Analysieren Ergänzen + Erneut analysieren %1$d von %2$d Stellungen sind schon bewertet. Partieanalyse · %1$d von %2$d Analyse anhalten @@ -267,15 +262,13 @@ Bewertungen aus der PGN ([%eval]) !! und ! braucht die Engine: die PGN enthält nur Bewertungen In dieser Analyse wurde noch nicht nach !! und ! gesucht - Analyse mit anderen Engine-Einstellungen gemacht - Aktualisieren - Mit der Engine analysieren Analyse ausblenden Bewertungsgrafik Pausiert: Partie wird analysiert Bessere Variante · Zug %1$d von %2$d Zum nächsten solchen Zug Die bessere Variante auf dem Brett zeigen + Von vorn %1$s, Bewertung %2$s Ausgangsstellung @@ -669,56 +662,4 @@ %1$s, von %2$s bis %3$s Spielstärke Eröffnungsbücher löschen - - - Spieler - Spielername - Spieler konnten nicht gelesen werden - Spieler werden gelesen… - Diese Datenbank enthält keine benannten Spieler - Spieler nicht gefunden - Zu den Partien - Suche zurücksetzen - Vorbereiten - Farbe wählen - Vorbereiten gegen %1$s - Gegen Weiß - Gegen Schwarz - Auf Gegner vorbereiten… - Vorbereitung auf den Gegner - Schließen Sie zuerst die Engine-Variante - - Suche nach einem Lehrzug -- ist nicht verfügbar - Weiß - Schwarz - Dieser Zug konnte nicht ausgeführt werden - %1$s spielen, %2$s, %3$s Prozent - Brett, Ausgangsstellung. %1$s unten. - Brett, Stellung nach %1$s. %2$s unten. - Weiß am Zug - Schwarz am Zug - Gegner spielt - Seine Gegner spielen - nach %1$s - Anfang - %1$s, %2$s, %3$s, %4$s - Fortsetzungen konnten nicht berechnet werden - Nicht genügend Speicher für die Suche in dieser Datenbank - Fortsetzungen werden berechnet… - Diese Stellung kommt in Partien von %1$s nicht vor - Sie können auf dem Brett fortsetzen oder zurückgehen - Alle Partien endeten hier - Hier beendet: %1$s - Keine normale Fortsetzung: %1$s - Zur Partie - Zu den Spielern - Zug auswählen - %1$s Sieg%1$s Siege - %1$s Remis%1$s Remis - %1$s Niederlage%1$s Niederlagen - Unbekannte Ergebnisse: %1$d; nicht in den Prozentwerten enthalten. - %1$s. %2$d von %3$s, %4$s Prozent. Ergebnisse für %5$s: %6$s, %7$s, %8$s; %9$s, %10$s und %11$s Prozent. %12$s Spielen. - Spielen - weitere %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-es/strings.xml b/androidApp/app/src/main/res/values-es/strings.xml index 80bd056..f996d52 100644 --- a/androidApp/app/src/main/res/values-es/strings.xml +++ b/androidApp/app/src/main/res/values-es/strings.xml @@ -37,8 +37,6 @@ Al inicio Jugada atrás Jugada adelante - Jugada anterior. Mantén pulsado para ir al inicio - Jugada siguiente. Mantén pulsado para ir al final de la línea Al final de la línea Siguiente: Tablero, posición tras %1$s @@ -219,15 +217,6 @@ Partidas copiadas en otra aplicación No hay partidas PGN en el portapapeles Pegado el %1$s - - Partida en el portapapeles - Partidas en el portapapeles - Partidas en el portapapeles - - Guardar esta partida PGN y abrirla en el tablero? - Guardar %1$s y abrir la primera partida en el tablero? Todas las partidas se conservarán en la copia local. - Abrir - Portapapeles Abriendo el archivo… No se pudo abrir el archivo Este archivo no contiene partidas de ajedrez. @@ -240,10 +229,15 @@ Análisis de la partida Informe de la partida El motor evalúa cada posición de la línea principal. La partida en sí no cambia. + Calidad + Rápido + Normal + Profundo %d s %d min Analizar Completar + Analizar de nuevo Ya hay %1$d de %2$d posiciones evaluadas. Análisis · %1$d de %2$d Detener el análisis @@ -272,15 +266,13 @@ Evaluaciones del PGN ([%eval]) !! y ! requieren el motor: el PGN solo trae evaluaciones Este análisis aún no buscó !! ni ! - Análisis hecho con otros ajustes del motor - Actualizar - Analizar con el motor Ocultar el análisis Gráfico de evaluación En pausa: se está analizando la partida Mejor línea · jugada %1$d de %2$d Ir a la siguiente jugada así Mostrar la mejor línea en el tablero + Empezar de nuevo %1$s, evaluación %2$s Posición inicial @@ -678,56 +670,4 @@ %1$s, de %2$s a %3$s Fuerza Eliminar los libros de aperturas - - - Jugadores - Nombre del jugador - No se pudieron leer los jugadores - Leyendo jugadores… - No hay jugadores con nombre en esta base - Jugador no encontrado - Volver a las partidas - Borrar búsqueda - Preparar - Elige un color - Prepararse contra %1$s - Contra las blancas - Contra las negras - Prepararse contra el rival… - Preparación contra el rival - Cierra primero la línea del motor - - La búsqueda después de un -- didáctico no está disponible - Blancas - Negras - No se pudo jugar este movimiento - Jugar %1$s, %2$s, %3$s por ciento - Tablero, posición inicial. %1$s abajo. - Tablero, posición después de %1$s. %2$s abajo. - Juegan las blancas - Juegan las negras - Juega el rival - Juegan sus rivales - después de %1$s - inicio - %1$s, %2$s, %3$s, %4$s - No se pudieron calcular las continuaciones - No hay memoria suficiente para buscar en esta base - Calculando continuaciones… - Esta posición no aparece en las partidas de %1$s - Puedes continuar en el tablero o retroceder - Todas las partidas terminaron aquí - Terminaron aquí: %1$s - Sin continuación normal: %1$s - Volver a la partida - Volver a los jugadores - Elige un movimiento - %1$s victoria%1$s victorias%1$s victorias - %1$s tabla%1$s tablas%1$s tablas - %1$s derrota%1$s derrotas%1$s derrotas - Resultados desconocidos: %1$d; excluidos de los porcentajes. - %1$s. %2$d de %3$s, %4$s por ciento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s y %11$s por ciento. %12$s Jugar. - Jugar - %1$s más - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-fr/strings.xml b/androidApp/app/src/main/res/values-fr/strings.xml index 70c23c8..de35c28 100644 --- a/androidApp/app/src/main/res/values-fr/strings.xml +++ b/androidApp/app/src/main/res/values-fr/strings.xml @@ -37,8 +37,6 @@ Au début Coup précédent Coup suivant - Coup précédent. Maintenez pour aller au début - Coup suivant. Maintenez pour aller à la fin de la ligne À la fin de la ligne Suite : Échiquier, position après %1$s @@ -219,15 +217,6 @@ Parties copiées dans une autre application Aucune partie PGN dans le presse-papiers Collé le %1$s - - %1$s partie dans le presse-papiers - %1$s parties dans le presse-papiers - %1$s parties dans le presse-papiers - - Enregistrer cette partie PGN et l’ouvrir sur l’échiquier ? - Enregistrer %1$s et ouvrir la première partie sur l’échiquier ? Toutes les parties seront conservées dans la copie locale. - Ouvrir - Presse-papiers Ouverture du fichier… Impossible d’ouvrir le fichier Ce fichier ne contient aucune partie d’échecs. @@ -240,10 +229,15 @@ Analyse de la partie Rapport de la partie Le moteur évalue chaque position de la ligne principale. La partie elle-même n\'est pas modifiée. + Qualité + Rapide + Normal + Approfondi %d s %d min Analyser Compléter + Analyser de nouveau %1$d positions sur %2$d sont déjà évaluées. Analyse · %1$d sur %2$d Arrêter l\'analyse @@ -272,15 +266,13 @@ Évaluations issues du PGN ([%eval]) !! et ! demandent le moteur : le PGN ne contient que des évaluations Cette analyse n’a pas encore cherché les !! et ! - Analyse faite avec d’autres réglages du moteur - Mettre à jour - Analyser avec le moteur Masquer l\'analyse Graphique d\'évaluation En pause : analyse de la partie en cours Meilleure ligne · coup %1$d sur %2$d Aller au coup suivant de ce type Afficher la meilleure ligne sur l\'échiquier + Recommencer %1$s, évaluation %2$s Position de départ @@ -678,56 +670,4 @@ %1$s, de %2$s à %3$s Force Supprimer les livres d’ouvertures - - - Joueurs - Nom du joueur - Impossible de lire les joueurs - Lecture des joueurs… - Cette base ne contient aucun joueur nommé - Joueur introuvable - Retour aux parties - Effacer la recherche - Préparer - Choisissez la couleur - Préparer contre %1$s - Contre les Blancs - Contre les Noirs - Préparer contre l’adversaire… - Préparation contre l’adversaire - Fermez d’abord la ligne du moteur - - La recherche après un -- pédagogique est indisponible - Blancs - Noirs - Impossible de jouer ce coup - Jouer %1$s, %2$s, %3$s pour cent - Échiquier, position initiale. %1$s en bas. - Échiquier, position après %1$s. %2$s en bas. - Trait aux blancs - Trait aux noirs - L’adversaire joue - Ses adversaires jouent - après %1$s - début - %1$s, %2$s, %3$s, %4$s - Impossible de calculer les continuations - Mémoire insuffisante pour rechercher dans cette base - Calcul des continuations… - Cette position n’apparaît pas dans les parties de %1$s - Vous pouvez continuer sur l’échiquier ou revenir en arrière - Toutes les parties se terminent ici - Terminées ici : %1$s - Aucune continuation normale : %1$s - Retour à la partie - Retour aux joueurs - Choisir un coup - %1$s victoire%1$s victoires%1$s victoires - %1$s nulle%1$s nulles%1$s nulles - %1$s défaite%1$s défaites%1$s défaites - Résultats inconnus : %1$d ; exclus des pourcentages. - %1$s. %2$d sur %3$s, %4$s pour cent. Résultats de %5$s : %6$s, %7$s, %8$s ; %9$s, %10$s et %11$s pour cent. %12$s Jouer. - Jouer - plus %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-it/strings.xml b/androidApp/app/src/main/res/values-it/strings.xml index 1db014a..8a89420 100644 --- a/androidApp/app/src/main/res/values-it/strings.xml +++ b/androidApp/app/src/main/res/values-it/strings.xml @@ -37,8 +37,6 @@ All\'inizio Mossa indietro Mossa avanti - Mossa precedente. Tieni premuto per andare all\'inizio - Mossa successiva. Tieni premuto per andare alla fine della linea Alla fine della linea Seguito: Scacchiera, posizione dopo %1$s @@ -219,15 +217,6 @@ Partite copiate in un’altra app Nessuna partita PGN negli appunti Incollato il %1$s - - Partita negli appunti - Partite negli appunti - Partite negli appunti - - Salvare questa partita PGN e aprirla sulla scacchiera? - Salvare %1$s e aprire la prima partita sulla scacchiera? Tutte le partite saranno conservate nella copia locale. - Apri - Appunti Apertura del file… Impossibile aprire il file Questo file non contiene partite a scacchi. @@ -240,10 +229,15 @@ Analisi della partita Resoconto della partita Il motore valuta ogni posizione della linea principale. La partita non viene modificata. + Qualità + Veloce + Normale + Approfondito %d s %d min Analizza Completa + Analizza di nuovo %1$d posizioni su %2$d sono già valutate. Analisi · %1$d di %2$d Interrompi l\'analisi @@ -272,15 +266,13 @@ Valutazioni dal PGN ([%eval]) !! e ! richiedono il motore: il PGN contiene solo valutazioni Questa analisi non ha ancora cercato !! e ! - Analisi fatta con altre impostazioni del motore - Aggiorna - Analizza con il motore Nascondi l\'analisi Grafico di valutazione In pausa: analisi della partita in corso Linea migliore · mossa %1$d di %2$d Vai alla prossima mossa di questo tipo Mostra la linea migliore sulla scacchiera + Ricomincia %1$s, valutazione %2$s Posizione iniziale @@ -678,56 +670,4 @@ %1$s, da %2$s a %3$s Forza Elimina i libri di aperture - - - Giocatori - Nome del giocatore - Impossibile leggere i giocatori - Lettura dei giocatori… - Questo database non contiene giocatori con nome - Giocatore non trovato - Torna alle partite - Cancella ricerca - Prepara - Scegli un colore - Preparati contro %1$s - Contro il Bianco - Contro il Nero - Preparati contro l\'avversario… - Preparazione contro l\'avversario - Chiudi prima la linea del motore - - La ricerca dopo un -- didattico non è disponibile - Bianco - Nero - Impossibile giocare questa mossa - Gioca %1$s, %2$s, %3$s per cento - Scacchiera, posizione iniziale. %1$s in basso. - Scacchiera, posizione dopo %1$s. %2$s in basso. - Tocca al bianco - Tocca al nero - Gioca l\'avversario - Giocano i suoi avversari - dopo %1$s - inizio - %1$s, %2$s, %3$s, %4$s - Impossibile calcolare le continuazioni - Memoria insufficiente per cercare in questo database - Calcolo delle continuazioni… - Questa posizione non compare nelle partite di %1$s - Puoi continuare sulla scacchiera o tornare indietro - Tutte le partite sono terminate qui - Terminate qui: %1$s - Nessuna continuazione normale: %1$s - Torna alla partita - Torna ai giocatori - Scegli una mossa - %1$s vittoria%1$s vittorie%1$s vittorie - %1$s patta%1$s patte%1$s patte - %1$s sconfitta%1$s sconfitte%1$s sconfitte - Risultati sconosciuti: %1$d; esclusi dalle percentuali. - %1$s. %2$d di %3$s, %4$s per cento. Risultati di %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s per cento. %12$s Gioca. - Gioca - altri %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-kk/strings.xml b/androidApp/app/src/main/res/values-kk/strings.xml index 17bb8eb..c54fa50 100644 --- a/androidApp/app/src/main/res/values-kk/strings.xml +++ b/androidApp/app/src/main/res/values-kk/strings.xml @@ -36,8 +36,6 @@ Басына Бір жүріс артқа Бір жүріс алға - Алдыңғы жүріс. Басына өту үшін басып тұрыңыз - Келесі жүріс. Варианттың соңына өту үшін басып тұрыңыз Варианттың соңына Келесі: Тақта, %1$s кейінгі позиция @@ -215,14 +213,6 @@ Басқа бағдарламада көшірілген партиялар Алмасу буферінде PGN партиясы жоқ Қойылды: %1$s - - Алмасу буферіндегі партия - Алмасу буферіндегі партиялар - - Осы PGN партиясын сақтап, тақтада ашу керек пе? - %1$s сақтап, бірінші партияны тақтада ашу керек пе? Барлық партиялар жергілікті көшірмеде сақталады. - Ашу - Алмасу буфері Файл ашылуда… Файлды ашу мүмкін болмады Бұл файлда шахмат партиялары жоқ. @@ -235,10 +225,15 @@ Партияны талдау Партия есебі Қозғалтқыш негізгі варианттың әр позициясын бағалайды. Партияның өзі өзгермейді. + Сапа + Жылдам + Қалыпты + Терең %d с %d мин Талдау Толықтыру + Қайта талдау %2$d позицияның %1$d бағаланып қойған. Партияны талдау · %1$d / %2$d Талдауды тоқтату @@ -267,15 +262,13 @@ PGN-дағы бағалар ([%eval]) !! және ! тек қозғалтқышпен: PGN-да тек бағалар бар Бұл талдауда !! мен ! әлі ізделмеген - Талдау қозғалтқыштың басқа баптауларымен жасалған - Жаңарту - Қозғалтқышпен талдау Талдауды жасыру Бағалау графигі Кідіртілді: партия талдануда Жақсырақ вариант · жүріс %1$d / %2$d Келесі осындай жүріске өту Жақсырақ вариантты тақтада көрсету + Басынан бастау %1$s, баға %2$s Бастапқы позиция @@ -670,56 +663,4 @@ %1$s, %2$s-ден %3$s-ге дейін Күші Дебют кітаптарын жою - - - Ойыншылар - Ойыншының аты - Ойыншыларды оқу мүмкін болмады - Ойыншылар оқылуда… - Бұл базада аты көрсетілген ойыншылар жоқ - Ойыншы табылмады - Партияларға оралу - Іздеуді тазалау - Дайындалу - Түсті таңдаңыз - Қарсыласқа дайындалу %1$s - Ақтарға қарсы - Қараларға қарсы - Қарсыласқа дайындалу… - Қарсыласқа дайындық - Алдымен қозғалтқыш желісін жабыңыз - - Оқу -- кейін іздеу қолжетімсіз - Ақтар - Қаралар - Бұл жүрісті жасау мүмкін болмады - %1$s жүру, %2$s, %3$s пайыз - Тақта, бастапқы позиция. Төменде %1$s. - Тақта, %1$s кейінгі позиция. Төменде %2$s. - Ақтардың жүрісі - Қаралардың жүрісі - Қарсылас жүреді - Оның қарсыластары жүреді - %1$s кейін - басы - %1$s, %2$s, %3$s, %4$s - Жалғастарды есептеу мүмкін болмады - Бұл базадан іздеуге жад жеткіліксіз - Жалғастар есептелуде… - %1$s партияларында бұл позиция жоқ - Тақтада жалғастыруға немесе артқа оралуға болады - Барлық партия осы жерде аяқталды - Осы жерде аяқталды: %1$s - Қалыпты жалғас жоқ: %1$s - Партияға оралу - Ойыншыларға оралу - Жүрісті таңдаңыз - %1$s жеңіс%1$s жеңіс - %1$s тең ойын%1$s тең ойын - %1$s жеңіліс%1$s жеңіліс - Белгісіз нәтижелер: %1$d; олар пайызға кірмейді. - %1$s. %3$s ішінен %2$d, %4$s пайыз. %5$s нәтижелері: %6$s, %7$s, %8$s; %9$s, %10$s және %11$s пайыз. %12$s Жүру. - Жүру - тағы %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-pt/strings.xml b/androidApp/app/src/main/res/values-pt/strings.xml index 578c2d3..901c64e 100644 --- a/androidApp/app/src/main/res/values-pt/strings.xml +++ b/androidApp/app/src/main/res/values-pt/strings.xml @@ -37,8 +37,6 @@ Ao início Voltar um lance Avançar um lance - Lance anterior. Mantenha premido para ir ao início - Lance seguinte. Mantenha premido para ir ao fim da linha Ao fim da linha Próximo: Tabuleiro, posição após %1$s @@ -219,15 +217,6 @@ Partidas copiadas em outro app Nenhuma partida PGN na área de transferência Colado %1$s - - %1$s partida na área de transferência - %1$s partidas na área de transferência - %1$s partidas na área de transferência - - Salvar esta partida PGN e abri-la no tabuleiro? - Salvar %1$s e abrir a primeira partida no tabuleiro? Todas as partidas serão mantidas na cópia local. - Abrir - Área de transferência Abrindo o arquivo… Não foi possível abrir o arquivo Não há partidas de xadrez neste arquivo. @@ -240,10 +229,15 @@ Análise da partida Relatório da partida O motor avalia cada posição da linha principal. A partida em si não é alterada. + Qualidade + Rápida + Normal + Profunda %d s %d min Analisar Completar + Analisar de novo %1$d de %2$d posições já estão avaliadas. Análise da partida · %1$d de %2$d Parar a análise @@ -272,15 +266,13 @@ Avaliações do PGN ([%eval]) !! e ! exigem o motor: o PGN traz só avaliações Esta análise ainda não procurou !! e ! - Análise feita com outras definições do motor - Atualizar - Analisar com o motor Ocultar análise Gráfico de avaliação Em pausa: a partida está sendo analisada Linha melhor · lance %1$d de %2$d Ir para o próximo lance assim Mostrar a linha melhor no tabuleiro + Recomeçar %1$s, avaliação %2$s Posição inicial @@ -679,56 +671,4 @@ %1$s, de %2$s a %3$s Força Excluir os livros de aberturas - - - Jogadores - Nome do jogador - Não foi possível ler os jogadores - A ler jogadores… - Não há jogadores identificados nesta base - Jogador não encontrado - Voltar às partidas - Limpar pesquisa - Preparar - Escolha uma cor - Preparar contra %1$s - Contra as brancas - Contra as pretas - Preparar contra o adversário… - Preparação contra o adversário - Feche primeiro a linha do motor - - A pesquisa depois de um -- didático não está disponível - Brancas - Pretas - Não foi possível jogar este lance - Jogar %1$s, %2$s, %3$s por cento - Tabuleiro, posição inicial. %1$s em baixo. - Tabuleiro, posição depois de %1$s. %2$s em baixo. - Jogam as brancas - Jogam as pretas - O adversário joga - Os seus adversários jogam - depois de %1$s - início - %1$s, %2$s, %3$s, %4$s - Não foi possível calcular as continuações - Memória insuficiente para pesquisar nesta base - A calcular continuações… - Esta posição não ocorre nas partidas de %1$s - Pode continuar no tabuleiro ou retroceder - Todas as partidas terminaram aqui - Terminaram aqui: %1$s - Sem continuação normal: %1$s - Voltar à partida - Voltar aos jogadores - Escolha um lance - %1$s vitória%1$s vitórias%1$s vitórias - %1$s empate%1$s empates%1$s empates - %1$s derrota%1$s derrotas%1$s derrotas - Resultados desconhecidos: %1$d; excluídos das percentagens. - %1$s. %2$d de %3$s, %4$s por cento. Resultados de %5$s: %6$s, %7$s, %8$s; %9$s, %10$s e %11$s por cento. %12$s Jogar. - Jogar - mais %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-ru/strings.xml b/androidApp/app/src/main/res/values-ru/strings.xml index 83254ab..c782336 100644 --- a/androidApp/app/src/main/res/values-ru/strings.xml +++ b/androidApp/app/src/main/res/values-ru/strings.xml @@ -38,8 +38,6 @@ В начало Ход назад Ход вперёд - Предыдущий ход. Удерживайте для перехода в начало - Следующий ход. Удерживайте для перехода в конец линии В конец линии Дальше: Доска, позиция после %1$s @@ -223,16 +221,6 @@ Партии, скопированные в другом приложении В буфере нет партий в формате PGN Из буфера, %1$s - - %1$s партия в буфере обмена - %1$s партии в буфере обмена - %1$s партий в буфере обмена - %1$s партии в буфере обмена - - Сохранить PGN-партию и открыть её на доске? - Сохранить %1$s и открыть первую партию на доске? Все партии останутся в локальной копии. - Открыть - Буфер обмена Открываю файл… Файл не открылся В этом файле нет шахматных партий. @@ -245,10 +233,15 @@ Анализ партии Отчёт по партии Движок оценит каждую позицию основной линии. Сама партия не изменится. + Качество + Быстро + Обычно + Глубоко %d с %d мин Анализировать Дополнить + Анализировать заново Уже оценено позиций: %1$d из %2$d. Анализ партии · %1$d из %2$d Остановить анализ @@ -277,15 +270,13 @@ Оценки из PGN ([%eval]) !! и ! ставит только движок: в PGN есть лишь оценки В этом анализе !! и ! ещё не искали - Анализ сделан с прежними настройками движка - Обновить - Проанализировать движком Скрыть анализ График оценки Пауза: идёт анализ партии Лучшая линия · ход %1$d из %2$d Перейти к следующему такому ходу Показать лучшую линию на доске + Заново %1$s, оценка %2$s Начальная позиция @@ -687,71 +678,4 @@ %1$s, от %2$s до %3$s Сила Удалить дебютные книги - - - Игроки - Имя игрока - Не удалось прочитать игроков - Читаю игроков… - В этой базе нет именованных игроков - Игрок не найден - К партиям - Сбросить поиск - Подготовиться - Выберите цвет - Подготовиться к %1$s - Против белых - Против чёрных - Подготовиться к сопернику… - Подготовка к сопернику - Сначала закройте линию движка - - Поиск после учебного -- недоступен - Белыми - Чёрными - Не удалось сделать ход - Сыграть %1$s, %2$s, %3$s процентов - Доска, начальная позиция. Внизу %1$s. - Доска, позиция после %1$s. Внизу %2$s. - ход белых - ход чёрных - Соперник играет - Его оппоненты играют - после %1$s - начало - %1$s, %2$s, %3$s, %4$s - Не удалось посчитать продолжения - Недостаточно памяти для поиска по этой базе - Считаю продолжения… - В партиях %1$s этой позиции нет - Можно продолжить на доске или вернуться назад - Все партии здесь закончились - Здесь закончились: %1$s - Нет обычного продолжения: %1$s - К партии - К игрокам - Выберите ход - - %1$s победа - %1$s победы - %1$s побед - %1$s победы - - - %1$s ничья - %1$s ничьи - %1$s ничьих - %1$s ничьи - - - %1$s поражение - %1$s поражения - %1$s поражений - %1$s поражения - - Неизвестных исходов: %1$d; они не входят в знаменатель процентов. - %1$s. %2$d из %3$s, %4$s процентов. Результаты %5$s: %6$s, %7$s, %8$s; %9$s, %10$s и %11$s процентов. %12$s Сыграть. - Сыграть - ещё %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values-uz/strings.xml b/androidApp/app/src/main/res/values-uz/strings.xml index f3dcc0b..0051aef 100644 --- a/androidApp/app/src/main/res/values-uz/strings.xml +++ b/androidApp/app/src/main/res/values-uz/strings.xml @@ -37,8 +37,6 @@ Boshiga Bir yurish orqaga Bir yurish oldinga - Oldingi yurish. Boshiga oʻtish uchun bosib turing - Keyingi yurish. Liniya oxiriga oʻtish uchun bosib turing Liniya oxiriga Keyin: Taxta, %1$sdan keyingi pozitsiya @@ -216,14 +214,6 @@ Boshqa ilovada nusxalangan partiyalar Almashish buferida PGN partiyalar yoʻq Qoʻyildi: %1$s - - Almashish buferida partiya - Almashish buferida partiyalar - - Bu PGN partiyani saqlab, doskada ochish? - %1$s saqlab, birinchi partiyani doskada ochish? Barcha partiyalar mahalliy nusxada saqlanadi. - Ochish - Almashish buferi Fayl ochilmoqda… Faylni ochib boʻlmadi Bu faylda shaxmat partiyalari yoʻq. @@ -235,10 +225,15 @@ Partiya tahlili Partiya hisoboti Dvigatel asosiy liniyaning har bir pozitsiyasini baholaydi. Partiyaning oʻzi oʻzgarmaydi. + Sifat + Tez + Oddiy + Chuqur %d s %d daq. Tahlil qilish Toʻldirish + Qayta tahlil qilish %2$d ta pozitsiyadan %1$d tasi allaqachon baholangan. Partiya tahlili · %1$d / %2$d Tahlilni toʻxtatish @@ -267,15 +262,13 @@ PGNdagi baholar ([%eval]) !! va ! faqat dvigatel bilan: PGNda faqat baholar bor Bu tahlilda !! va ! hali qidirilmagan - Tahlil dvigatelning boshqa sozlamalari bilan qilingan - Yangilash - Dvigatel bilan tahlil qilish Tahlilni yashirish Baho grafigi Pauza: partiya tahlil qilinmoqda Yaxshiroq liniya · yurish %1$d / %2$d Keyingi shunday yurishga oʻtish Yaxshiroq liniyani taxtada koʻrsatish + Qaytadan boshlash %1$s, baho %2$s Boshlangʻich pozitsiya @@ -668,56 +661,4 @@ %1$s, %2$s dan %3$s gacha Kuch Debyut kitoblarini o‘chirish - - - Oʻyinchilar - Oʻyinchi ismi - Oʻyinchilarni oʻqib boʻlmadi - Oʻyinchilar oʻqilmoqda… - Bu bazada nomi koʻrsatilgan oʻyinchilar yoʻq - Oʻyinchi topilmadi - Partiyalarga qaytish - Qidiruvni tozalash - Tayyorlanish - Rangni tanlang - Raqibga tayyorlanish %1$s - Oqlarga qarshi - Qoralarga qarshi - Raqibga tayyorlanish… - Raqibga tayyorgarlik - Avval dvigatel chizigʻini yoping - - Oʻquv -- dan keyin qidirish mavjud emas - Oqlar - Qoralar - Bu yurishni bajarib boʻlmadi - %1$s yurish, %2$s, %3$s foiz - Doska, boshlangʻich pozitsiya. Pastda %1$s. - Doska, %1$s dan keyingi pozitsiya. Pastda %2$s. - Oqlar yurishi - Qoralar yurishi - Raqib yuradi - Uning raqiblari yuradi - %1$s dan keyin - boshlanishi - %1$s, %2$s, %3$s, %4$s - Davomlarni hisoblab boʻlmadi - Bu bazadan qidirish uchun xotira yetarli emas - Davomlar hisoblanmoqda… - %1$s partiyalarida bu pozitsiya yoʻq - Doskada davom etishingiz yoki orqaga qaytishingiz mumkin - Barcha partiyalar shu yerda tugagan - Shu yerda tugagan: %1$s - Oddiy davom yoʻq: %1$s - Partiyaga qaytish - Oʻyinchilarga qaytish - Yurishni tanlang - %1$s gʻalaba%1$s gʻalaba - %1$s durang%1$s durang - %1$s magʻlubiyat%1$s magʻlubiyat - Nomaʼlum natijalar: %1$d; ular foizlarga kiritilmaydi. - %1$s. %3$s dan %2$d tasi, %4$s foiz. %5$s natijalari: %6$s, %7$s, %8$s; %9$s, %10$s va %11$s foiz. %12$s Yurish. - Yurish - yana %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/main/res/values/strings.xml b/androidApp/app/src/main/res/values/strings.xml index 71a4a84..59b96f9 100644 --- a/androidApp/app/src/main/res/values/strings.xml +++ b/androidApp/app/src/main/res/values/strings.xml @@ -37,8 +37,6 @@ To the start Move back Move forward - Previous move. Hold for the first position - Next move. Hold for the end of the line To the end of the line Next: Board, position after %1$s @@ -218,14 +216,6 @@ Games copied in another app No PGN games in the clipboard Pasted %1$s - - Game in clipboard - Games in clipboard - - Save this PGN game and open it on the board? - Save %1$s and open the first game on the board? All games will be kept in the local copy. - Open - Clipboard Opening the file… Couldn’t open the file There are no chess games in this file. @@ -238,10 +228,15 @@ Game analysis Game report The engine evaluates every position of the main line. The game itself is not changed. + Quality + Fast + Normal + Deep %d s %d min Analyse Fill in + Analyse again %1$d of %2$d positions are evaluated already. Game analysis · %1$d of %2$d Stop the analysis @@ -270,15 +265,13 @@ Evaluations from the PGN ([%eval]) !! and ! need the engine: the PGN has evaluations only !! and ! were not looked for in this analysis - This analysis was made with other engine settings - Update - Analyse with the engine Hide analysis Evaluation graph Paused: the game is being analysed Better line · move %1$d of %2$d Go to the next such move Show the better line on the board + Start over %1$s, evaluation %2$s Start position @@ -673,65 +666,4 @@ %1$s, from %2$s to %3$s Strength Delete the opening books - - - Players - Player name - Could not read players - Reading players… - There are no named players in this database - Player not found - Back to games - Clear search - Prepare - Choose a color - Prepare against %1$s - Against White - Against Black - Prepare for opponent… - Opponent preparation - Close the engine line first - - Search after a teaching -- is unavailable - White - Black - Could not play this move - Play %1$s, %2$s, %3$s percent - Board, starting position. %1$s at the bottom. - Board, position after %1$s. %2$s at the bottom. - White to move - Black to move - Opponent plays - Their opponents play - after %1$s - start - %1$s, %2$s, %3$s, %4$s - Could not calculate continuations - Not enough memory to search this database - Calculating continuations… - This position does not occur in games by %1$s - You can continue on the board or go back - All games ended here - Ended here: %1$s - No normal continuation: %1$s - Back to game - Back to players - Choose a move - - %1$s win - %1$s wins - - - %1$s draw - %1$s draws - - - %1$s loss - %1$s losses - - Unknown results: %1$d; excluded from the percentages. - %1$s. %2$d of %3$s, %4$s percent. Results for %5$s: %6$s, %7$s, %8$s; %9$s, %10$s and %11$s percent. %12$s Play. - Play - more %1$s - +%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %% diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ClipboardIncomingTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ClipboardIncomingTest.kt deleted file mode 100644 index 215f6d1..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ClipboardIncomingTest.kt +++ /dev/null @@ -1,95 +0,0 @@ -package io.github.vrubelroman.chesspenguin - -import io.github.vrubelroman.chesspenguin.data.DbEntry -import io.github.vrubelroman.chesspenguin.data.Source -import kotlinx.coroutines.flow.MutableStateFlow -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Test - -class ClipboardIncomingTest { - @Test - fun `pasted existing copy ignores a previous empty filtered view`() { - val shown = hashMapOf("copy" to emptyList()) - val lastOpened = hashMapOf("copy" to ("not-found" to 0)) - - resetPastedView(shown, lastOpened, "copy") - - assertFalse(shown.containsKey("copy")) - assertFalse(lastOpened.containsKey("copy")) - } - - @Test - fun `uri and clipboard publish only their latest common request`() { - val requests = LatestIncoming() - val uri = requests.next() - val clipboard = requests.next() - - assertFalse(requests.isLatest(uri)) - assertTrue(requests.isLatest(clipboard)) - - val newerUri = requests.next() - assertFalse(requests.isLatest(clipboard)) - assertTrue(requests.isLatest(newerUri)) - } - - @Test - fun `stale request cannot publish after a newer request starts`() { - val requests = LatestIncoming() - val old = requests.next() - val current = requests.next() - var published: Long? = null - - assertFalse(requests.publish(old) { published = old }) - assertNull(published) - assertTrue(requests.publish(current) { published = current }) - assertEquals(current, published) - } - - @Test - fun `blank clipboard snapshot does not invalidate uri import`() { - val requests = LatestIncoming() - val uri = requests.next(IncomingOrigin.Uri) - - assertFalse(requests.invalidateClipboard()) - assertTrue(requests.isLatest(uri)) - } - - @Test - fun `clipboard snapshot invalidates active clipboard import`() { - val requests = LatestIncoming() - val clipboard = requests.next(IncomingOrigin.Clipboard) - - assertTrue(requests.invalidateClipboard()) - assertFalse(requests.isLatest(clipboard)) - } - - @Test - fun `failed dismiss compareAndSet cannot clear a newer opening`() { - val incoming = MutableStateFlow(Incoming.Failed(IllegalStateException("old"))) - val expected = incoming.value - incoming.value = Incoming.Opening - - assertFalse(incoming.compareAndSet(expected, null)) - assertEquals(Incoming.Opening, incoming.value) - } - - @Test - fun `stale collector cannot clear a newer incoming event`() { - val entry = DbEntry( - id = "copy", - name = "Clipboard", - source = Source.Copy, - location = "copy.pgn", - fileName = "clipboard.pgn", - ) - val incoming = MutableStateFlow(Incoming.Opened(entry)) - val expected = incoming.value - incoming.value = Incoming.Opening - - assertFalse(incoming.compareAndSet(expected, null)) - assertEquals(Incoming.Opening, incoming.value) - } -} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/ClipboardPromptGateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/ClipboardPromptGateTest.kt deleted file mode 100644 index 3a173a2..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/ClipboardPromptGateTest.kt +++ /dev/null @@ -1,135 +0,0 @@ -package io.github.vrubelroman.chesspenguin.data - -import org.junit.Assert.assertArrayEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNotEquals -import org.junit.Assert.assertNotNull -import org.junit.Assert.assertNull -import org.junit.Assert.assertSame -import org.junit.Assert.assertTrue -import org.junit.Test - -class ClipboardPromptGateTest { - @Test - fun `new offer is accepted once and same offer cannot be accepted twice`() { - val gate = ClipboardPromptGate() - val generation = gate.invalidate() - val offer = offer("same", generation) - assertTrue(gate.publish(offer)) - - val accepted = gate.accept(offer) - - assertNotNull(accepted) - assertNull(gate.accept(offer)) - assertTrue(gate.canPublish(accepted!!)) - } - - @Test - fun `blank snapshot invalidates offer and pending publication`() { - val gate = ClipboardPromptGate() - val generation = gate.invalidate() - val offer = offer("old", generation) - assertTrue(gate.publish(offer)) - val accepted = gate.accept(offer)!! - - gate.invalidate() - - assertFalse(gate.canPublish(accepted)) - assertFalse(gate.publish(offer)) - } - - @Test - fun `stale accept is ignored after snapshot changes`() { - val gate = ClipboardPromptGate() - val old = offer("old", gate.invalidate()) - assertTrue(gate.publish(old)) - gate.invalidate() - val current = offer("current", gate.invalidate()) - - assertNull(gate.accept(old)) - assertTrue(gate.publish(current)) - assertNotNull(gate.accept(current)) - } - - @Test - fun `changed snapshot forbids old import publication`() { - val gate = ClipboardPromptGate() - val accepted = gate.accept(offer("old", gate.invalidate()).also { gate.publish(it) })!! - - gate.invalidate() - - assertFalse(gate.canPublish(accepted)) - } - - @Test - fun `dismissed digest stays decided while changed text is allowed`() { - val gate = ClipboardPromptGate() - val dismissed = offer("dismissed", gate.invalidate()) - assertTrue(gate.publish(dismissed)) - assertTrue(gate.dismiss(dismissed)) - - assertFalse(gate.publish(dismissed.copy(generation = gate.invalidate()))) - assertTrue(gate.publish(offer("changed", gate.invalidate()))) - } - - @Test - fun `successful open persists digest only after entry and survives cold restoration`() { - var persisted = emptySet() - val first = ClipboardPromptGate(onDecide = { persisted = it }) - val offer = offer("sha256-of-opened-text", first.invalidate()) - assertTrue(first.publish(offer)) - val accepted = first.accept(offer)!! - assertTrue(persisted.isEmpty()) - - assertTrue(first.finish(accepted, true)) - - val restored = ClipboardPromptGate(decided = persisted) - assertFalse(restored.publish(offer.copy(generation = restored.invalidate()))) - assertTrue(restored.publish(offer.copy(digest = "new-text", generation = restored.invalidate()))) - } - - @Test - fun `failed import does not persist digest and retries after cold start`() { - var persisted = emptySet() - val first = ClipboardPromptGate(onDecide = { persisted = it }) - val offer = offer("retry-digest", first.invalidate()) - assertTrue(first.publish(offer)) - val accepted = first.accept(offer)!! - assertTrue(persisted.isEmpty()) - - assertTrue(first.finish(accepted, false)) - - val restored = ClipboardPromptGate(decided = persisted) - assertTrue(restored.publish(offer.copy(generation = restored.invalidate()))) - } - - @Test - fun `one UTF8 snapshot preserves BOM CRLF unicode and import bytes`() { - val text = "\uFEFF[Event \"Партия 😀\"]\r\n1. e4 e5\r\n*" - val bytes = clipboardUtf8(text) - val gate = ClipboardPromptGate() - val offer = ClipboardOffer(bytes, 1, clipboardSha256(bytes), gate.invalidate()) - assertTrue(gate.publish(offer)) - - val accepted = gate.accept(offer)!! - - assertArrayEquals(text.toByteArray(Charsets.UTF_8), accepted.bytes) - assertSame(bytes, accepted.bytes) - assertNotEquals( - clipboardSha256(bytes), - clipboardSha256(clipboardUtf8(text.replace("\r\n", "\n"))), - ) - } - - @Test - fun `clipboard size limit includes eight MiB and rejects one byte more`() { - assertTrue(clipboardPgnLengthMayFit("a".repeat(CLIPBOARD_PGN_MAX_BYTES))) - assertFalse(clipboardPgnLengthMayFit("a".repeat(CLIPBOARD_PGN_MAX_BYTES + 1))) - assertTrue(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES - 1)) - assertTrue(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES)) - assertFalse(clipboardPgnWithinLimit(CLIPBOARD_PGN_MAX_BYTES + 1)) - } - - private fun offer(digest: String, generation: Long, games: Int = 1): ClipboardOffer = - ClipboardOffer(byteArrayOf(1), games, digest, generation) -} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/LibraryClipboardTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/LibraryClipboardTest.kt deleted file mode 100644 index 1495074..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/data/LibraryClipboardTest.kt +++ /dev/null @@ -1,47 +0,0 @@ -package io.github.vrubelroman.chesspenguin.data - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNull -import org.junit.Assert.assertSame -import org.junit.Assert.assertTrue -import org.junit.Test - -class LibraryClipboardTest { - @Test - fun `first valid record is accepted even when a later record is malformed`() { - assertTrue(firstPgnGameIsMeaningful(count = 2, tags = 1, nodes = 1)) - assertTrue(firstPgnGameIsMeaningful(count = 2, tags = 0, nodes = 2)) - } - - @Test - fun `first malformed record is rejected even when a later record is valid`() { - assertFalse(firstPgnGameIsMeaningful(count = 2, tags = 0, nodes = 1)) - } - - @Test - fun `multiple empty records and zero records are rejected`() { - assertFalse(firstPgnGameIsMeaningful(count = 3, tags = 0, nodes = 1)) - assertFalse(firstPgnGameIsMeaningful(count = 0, tags = 0, nodes = 0)) - } - - @Test - fun `tag only first record is accepted by the shared addCopy rule`() { - assertTrue(firstPgnGameIsMeaningful(count = 1, tags = 1, nodes = 1)) - } - - @Test - fun `final digest lookup reuses an existing copy after concurrent parsing`() { - val existing = DbEntry( - id = "existing", - name = "Clipboard", - source = Source.Copy, - location = "existing.pgn", - fileName = "clipboard.pgn", - sha256 = "same-digest", - ) - val other = existing.copy(id = "other", sha256 = "other-digest") - - assertSame(existing, copyWithDigest(listOf(other, existing), "same-digest")) - assertNull(copyWithDigest(listOf(other, existing), "new-digest")) - } -} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/BoardArrowHitTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/BoardArrowHitTest.kt deleted file mode 100644 index daa6fd9..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/BoardArrowHitTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import androidx.compose.ui.geometry.Offset -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Test - -class BoardArrowHitTest { - @Test - fun `flip changes the hit point but not UCI`() { - val move = BoardArrowMove("e2e4", "e2", "e4", "e4") - val square = 40f - val center = Offset(square / 2, square / 2) - val target = squareIndex("e4")!! - val normal = boardCell(target, square, false) + center - val flipped = boardCell(target, square, true) + center - - assertEquals(listOf("e2e4"), arrowHits(normal, square, false, listOf(move), 24f).map { it.uci }) - assertTrue(arrowHits(normal, square, true, listOf(move), 24f).isEmpty()) - assertEquals(listOf("e2e4"), arrowHits(flipped, square, true, listOf(move), 24f).map { it.uci }) - } - - @Test - fun `overlapping targets return every conflicting UCI`() { - val square = 35f - val center = Offset(square / 2, square / 2) - val target = boardCell(squareIndex("e8")!!, square, false) + center - val moves = listOf( - BoardArrowMove("e7e8q", "e7", "e8", "queen"), - BoardArrowMove("e7e8n", "e7", "e8", "knight"), - ) - - assertEquals(listOf("e7e8q", "e7e8n"), arrowHits(target, square, false, moves, 24f).map { it.uci }) - } - - @Test - fun `points outside the board never activate an arrow`() { - val move = BoardArrowMove("e2e4", "e2", "e4", "e4") - assertTrue(arrowHits(Offset(-1f, 10f), 40f, false, listOf(move), 24f).isEmpty()) - } -} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/GameBarStateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/GameBarStateTest.kt deleted file mode 100644 index c424c18..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/GameBarStateTest.kt +++ /dev/null @@ -1,54 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class GameBarStateTest { - @Test - fun `loaded game can start or open its report`() { - assertTrue(enabled()) - assertTrue(enabled(hasData = true, running = true)) - } - - @Test - fun `review is unavailable during computer play and without moves`() { - assertFalse(enabled(gameOn = true, sessionGame = true)) - assertFalse(enabled(hasMoves = false)) - } - - @Test - fun `database game waits for its review state`() { - assertFalse(enabled(loaded = false)) - assertTrue(enabled(sessionGame = true, loaded = false)) - } - - @Test - fun `first running database analysis disables duplicate start`() { - assertFalse(enabled(running = true)) - } - - @Test - fun `session game cannot duplicate its first run`() { - assertFalse(enabled(sessionGame = true, loaded = true, running = true)) - assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true)) - } - - @Test - fun `report wins over running while an empty run waits`() { - assertEquals(ReviewAction.Start, reviewAction(hasData = false, running = false)) - assertEquals(ReviewAction.Wait, reviewAction(hasData = false, running = true)) - assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = false)) - assertEquals(ReviewAction.Report, reviewAction(hasData = true, running = true)) - } - - private fun enabled( - hasMoves: Boolean = true, - gameOn: Boolean = false, - sessionGame: Boolean = false, - loaded: Boolean = true, - hasData: Boolean = false, - running: Boolean = false, - ) = reviewEnabled(hasMoves, gameOn, sessionGame, loaded, hasData, running) -} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PlayersStateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PlayersStateTest.kt deleted file mode 100644 index a3a8321..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PlayersStateTest.kt +++ /dev/null @@ -1,46 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Test - -class PlayersStateTest { - @Test - fun `two available colors always require an explicit choice`() { - val blackMoreOften = player(white = 2, black = 3) - val whiteMoreOften = player(white = 9, black = 1) - - assertTrue(playerNeedsColorChoice(blackMoreOften)) - assertTrue(playerNeedsColorChoice(whiteMoreOften)) - assertNull(solePlayerColor(blackMoreOften)) - assertNull(solePlayerColor(whiteMoreOften)) - } - - @Test - fun `exactly one available color is the direct action`() { - val whiteOnly = player(white = 2, black = 0) - val blackOnly = player(white = 0, black = 1) - - assertTrue(solePlayerColor(whiteOnly) == true) - assertTrue(solePlayerColor(blackOnly) == false) - assertFalse(playerNeedsColorChoice(whiteOnly)) - assertFalse(playerNeedsColorChoice(blackOnly)) - } - - @Test - fun `zero colors do not become an action`() { - val empty = player(white = 0, black = 0) - - assertNull(solePlayerColor(empty)) - assertFalse(playerNeedsColorChoice(empty)) - } - - private fun player(white: Int, black: Int) = PlayerSummary( - id = 1, - name = "Player", - total = 100, - whiteGames = white, - blackGames = black, - ) -} diff --git a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PrepLineStateTest.kt b/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PrepLineStateTest.kt deleted file mode 100644 index bb9491b..0000000 --- a/androidApp/app/src/test/java/io/github/vrubelroman/chesspenguin/ui/PrepLineStateTest.kt +++ /dev/null @@ -1,101 +0,0 @@ -package io.github.vrubelroman.chesspenguin.ui - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertNull -import org.junit.Assert.assertTrue -import org.junit.Test - -class PrepLineStateTest { - @Test - fun `back and forward follow the same continuation`() { - val line = line("e2e4", "e7e5", "g1f3") - - val back = line.back().back() - assertEquals(1, back.cursor) - assertEquals("e2e4", back.last?.uci) - assertTrue(back.canForward) - - val forward = back.forward() - assertEquals("e7e5", forward.last?.uci) - assertEquals("g1f3", forward.forward().last?.uci) - } - - @Test - fun `long actions jump without an extra step`() { - val line = line("e2e4", "e7e5", "g1f3") - assertEquals(0, line.start().cursor) - assertEquals(line.steps.size, line.start().end().cursor) - assertEquals(line, line.end()) - assertEquals(line.start(), line.start().start()) - } - - @Test - fun `a played line replaces only the temporary future`() { - val original = line("e2e4", "e7e5", "g1f3").back().back() - val prefix = original.steps.take(original.cursor) - val replacement = step("c7c5", 2, "c5") - val changed = original.replaceVisibleLine(prefix + replacement, replacement.node) - - assertEquals(listOf("e2e4", "c7c5"), changed.moves) - assertEquals(2, changed.cursor) - assertFalse(changed.canForward) - assertEquals(listOf("e2e4", "e7e5", "g1f3"), original.moves) - } - - @Test - fun `opponent color puts the user at the bottom`() { - assertTrue(prepBoardStartsFlipped(opponentWhite = true)) - assertFalse(prepBoardStartsFlipped(opponentWhite = false)) - } - - @Test - fun `side and number come from FEN rather than parity`() { - val black = "8/8/8/8/8/8/4k3/4K3 b - - 0 0" - assertEquals(false, prepWhiteToMove(black)) - assertEquals("0…Kd2", moveLabel(black, "Kd2")) - assertEquals("12.Nf3", moveLabel(STANDARD_START.substringBeforeLast(" 1") + " 12", "Nf3")) - assertNull(prepWhiteToMove("not a fen")) - } - - @Test - fun `frequency and WDL have separate denominators`() { - val move = PrepContinuation("e7e5", "e5", games = 4, wins = 2, draws = 0, losses = 1, unknown = 1) - assertEquals("40", frequencyPercent(move.games, 10)) - assertEquals(Triple("67", "0", "33"), outcomePercents(move)) - assertEquals("<1", frequencyPercent(1, 113)) - assertEquals("0", frequencyPercent(0, 113)) - assertEquals(Triple("—", "—", "—"), outcomePercents(move.copy(wins = 0, losses = 0))) - } - - @Test - fun `continuations are sorted by games then SAN without hiding rare moves`() { - val position = PrepPosition( - games = 5, - continuations = listOf( - PrepContinuation("g1f3", "Nf3", 1, 1, 0, 0), - PrepContinuation("e2e4", "e4", 3, 1, 1, 1), - PrepContinuation("d2d4", "d4", 1, 0, 1, 0), - ), - ) - assertEquals(listOf("e4", "Nf3", "d4"), sortedContinuations(position).map { it.san }) - } - - private fun line(vararg moves: String): PrepLineState = PrepLineState( - startFen = STANDARD_START, - rootFen = STANDARD_START, - steps = moves.mapIndexed { i, uci -> step(uci, i + 1, uci.take(4)) }, - cursor = moves.size, - ) - - private fun step(uci: String, node: Int, san: String) = PrepLineStep( - node = node, - uci = uci, - san = san, - moveNumber = (node + 1) / 2, - white = node % 2 == 1, - fen = STANDARD_START, - from = uci.take(2), - to = uci.substring(2, 4), - ) -} diff --git a/apps/desktop/Cargo.toml b/apps/desktop/Cargo.toml index 4e5ae2c..99350c0 100644 --- a/apps/desktop/Cargo.toml +++ b/apps/desktop/Cargo.toml @@ -9,22 +9,10 @@ edition.workspace = true rust-version.workspace = true license.workspace = true -# The interface, shared with the web version (apps/web); src/main.rs starts it in a -# window. -[lib] -name = "chesspenguin_app" -path = "src/lib.rs" - -[[bin]] -name = "chesspenguin" -path = "src/main.rs" - [dependencies] chess-core.workspace = true -chess-openings.workspace = true maia.workspace = true game-review.workspace = true -prep.workspace = true chess-import.workspace = true shakmaty.workspace = true uci.workspace = true @@ -32,16 +20,23 @@ egui.workspace = true eframe.workspace = true egui_extras.workspace = true image.workspace = true +rfd.workspace = true +arboard.workspace = true +rodio.workspace = true directories.workspace = true trainer.workspace = true play.workspace = true serde.workspace = true serde_json.workspace = true -thiserror.workspace = true online-games.workspace = true -web-time.workspace = true +releases.workspace = true +# Downloading the official Stockfish on request (decision 14). +ureq = "3.4" +flate2 = "1.1" +tar = "0.4" sha2 = "0.11" zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs"] } + # The system language for the first start. sys-locale = "0.3" whatlang = "0.18.0" @@ -53,42 +48,6 @@ log = "0.4" base64 = "0.22" form_urlencoded = "1" -# The desktop program: native dialogs, the clipboard, sound, the network (updates, -# engines and Maia on request, online games, translation). -[target.'cfg(not(target_family = "wasm"))'.dependencies] -rfd.workspace = true -arboard.workspace = true -rodio.workspace = true -releases.workspace = true -# Downloading the official Stockfish on request (decision 14). -ureq = "3.4" -flate2 = "1.1" -tar = "0.4" - -# The web version: the page, its files and storage (apps/web starts it). -[target.'cfg(target_family = "wasm")'.dependencies] -# The reader worker gives the page a database's index (platform::web::import). -chess-core = { workspace = true, features = ["serde"] } -getrandom = { version = "0.3", features = ["wasm_js"] } -# The browser's languages for the first start. -sys-locale = { version = "0.3", features = ["js"] } -# Today's date from the browser's clock. -chrono = { version = "0.4", default-features = false, features = ["clock", "std", "wasmbind"] } -wasm-bindgen = "0.2.129" -wasm-bindgen-futures = "0.4" -js-sys = "0.3" -web-sys = { version = "0.3", features = [ - "Window", "Document", "Element", "HtmlElement", "HtmlInputElement", "HtmlAnchorElement", - "File", "FileList", "Blob", "BlobPropertyBag", "Url", "Event", "Location", "Navigator", - "Storage", "UrlSearchParams", "EventTarget", "CssStyleDeclaration", "Clipboard", - "IdbFactory", "IdbDatabase", "IdbOpenDbRequest", "IdbRequest", "IdbTransaction", - "IdbTransactionMode", "IdbObjectStore", "DomStringList", "HtmlAudioElement", - "HtmlMediaElement", "HtmlCanvasElement", "console", "CacheStorage", "Cache", - "Request", "Response", "ResponseInit", "Headers", "ReadableStream", - "ReadableStreamDefaultReader", "StorageManager", "StorageEstimate", "History", - "BeforeUnloadEvent", "WorkerOptions", "WorkerType", -] } - [build-dependencies] winresource = "0.1" diff --git a/apps/desktop/assets/repertoires/queens-gambit-white.pgn b/apps/desktop/assets/repertoires/queens-gambit-white.pgn deleted file mode 100644 index fa324df..0000000 --- a/apps/desktop/assets/repertoires/queens-gambit-white.pgn +++ /dev/null @@ -1,12 +0,0 @@ -[Event "ChessPenguin: Queen's Gambit for White"] -[White "Repertoire"] -[Black "?"] -[Result "*"] -[ECO "D37"] - -{Queen's Gambit for White: the Queen's Gambit Declined with 5.Bf4, plus answers to the Queen's Gambit Accepted and the Slav Defence.} -1. d4 d5 2. c4 {White offers a pawn to deflect Black's d-pawn from the centre.} -2... e6 (2... dxc4 {Queen's Gambit Accepted.} 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 8. Qxd8+ Kxd8 {White keeps a small, risk-free edge in the endgame.}) -(2... c6 {Slav Defence.} 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O {White has a central space advantage and easy development.}) -3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 {The modern main line: the bishop is active and safe from ...h6 and ...Ne4.} -5... O-O 6. e3 c5 7. dxc5 Bxc5 8. a3 Nc6 9. Qc2 Qa5 10. Rd1 Re8 11. Nd2 {White plays against the isolated pawn that may appear after ...dxc4 or cxd5.} * diff --git a/apps/desktop/assets/repertoires/queens-gambit-white.ru.pgn b/apps/desktop/assets/repertoires/queens-gambit-white.ru.pgn deleted file mode 100644 index 61c219b..0000000 --- a/apps/desktop/assets/repertoires/queens-gambit-white.ru.pgn +++ /dev/null @@ -1,12 +0,0 @@ -[Event "ChessPenguin: Ферзевый гамбит за белых"] -[White "Repertoire"] -[Black "?"] -[Result "*"] -[ECO "D37"] - -{Ферзевый гамбит за белых: отказанный ферзевый гамбит с 5.Bf4, а также ответы на принятый ферзевый гамбит и Славянскую защиту.} -1. d4 d5 2. c4 {Белые предлагают пешку, чтобы отвлечь пешку d5 из центра.} -2... e6 (2... dxc4 {Принятый ферзевый гамбит.} 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 8. Qxd8+ Kxd8 {Белые сохраняют небольшой безрисковый перевес в эндшпиле.}) -(2... c6 {Славянская защита.} 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O {У белых перевес в пространстве в центре и удобное развитие.}) -3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 {Современная основная система: слон активен и не попадает под ...h6 и ...Ne4.} -5... O-O 6. e3 c5 7. dxc5 Bxc5 8. a3 Nc6 9. Qc2 Qa5 10. Rd1 Re8 11. Nd2 {Белые играют против изолированной пешки, которая может возникнуть после ...dxc4 или cxd5.} * diff --git a/apps/desktop/assets/repertoires/sicilian-black.pgn b/apps/desktop/assets/repertoires/sicilian-black.pgn deleted file mode 100644 index a050f88..0000000 --- a/apps/desktop/assets/repertoires/sicilian-black.pgn +++ /dev/null @@ -1,11 +0,0 @@ -[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/sicilian-black.ru.pgn b/apps/desktop/assets/repertoires/sicilian-black.ru.pgn deleted file mode 100644 index 42f4a82..0000000 --- a/apps/desktop/assets/repertoires/sicilian-black.ru.pgn +++ /dev/null @@ -1,11 +0,0 @@ -[Event "ChessPenguin: Сицилианская защита, вариант Найдорфа за чёрных"] -[White "?"] -[Black "Repertoire"] -[Result "*"] -[ECO "B90"] - -{Сицилианская защита, вариант Найдорфа за чёрных: ответы на 6.Be3, 6.Bg5 и вариант Алапина 2.c3.} -1. e4 c5 2. Nf3 (2. c3 {Вариант Алапина.} 2... Nf6 3. e5 Nd5 4. d4 cxd4 5. Nf3 Nc6 6. cxd4 d6 {Чёрные сразу атакуют пешку e5.}) -2... d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 {Вариант Найдорфа: ...a6 контролирует b5 и готовит ...e5 или ...b5.} -6. Be3 (6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 {Чёрные сохраняют прочную позицию и готовят ...b5.}) -6... e5 7. Nb3 Be6 8. f3 Be7 9. Qd2 O-O 10. O-O-O Nbd7 11. g4 b5 {Английская атака: обе стороны наступают на противоположных флангах.} * diff --git a/apps/desktop/assets/repertoires/spanish-white.pgn b/apps/desktop/assets/repertoires/spanish-white.pgn deleted file mode 100644 index c1d8739..0000000 --- a/apps/desktop/assets/repertoires/spanish-white.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[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/assets/repertoires/spanish-white.ru.pgn b/apps/desktop/assets/repertoires/spanish-white.ru.pgn deleted file mode 100644 index 48ff6ac..0000000 --- a/apps/desktop/assets/repertoires/spanish-white.ru.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[Event "ChessPenguin: Испанская партия за белых"] -[White "Repertoire"] -[Black "?"] -[Result "*"] -[ECO "C84"] - -{Испанская партия за белых: закрытая основная система, атака Маршалла и Берлинская защита.} -1. e4 e5 2. Nf3 Nc6 3. Bb5 {Испанский слон давит на коня, защищающего e5.} -3... a6 (3... Nf6 {Берлинская защита.} 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 -8. Qxd8+ Kxd8 {Берлинский эндшпиль: у белых более здоровое пешечное большинство.}) -4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 (7... O-O 8. c3 d5 {Атака Маршалла.} -9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 {Белые пока сохраняют лишнюю пешку, а при необходимости вернут материал позже.}) -8. c3 O-O 9. h3 {Не допускает ...Bg4 и готовит d4.} 9... Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 {Вариант Чигорина: конь идёт на f1 и g3.} * diff --git a/apps/desktop/assets/repertoires/triangle-black.pgn b/apps/desktop/assets/repertoires/triangle-black.pgn deleted file mode 100644 index 36a8851..0000000 --- a/apps/desktop/assets/repertoires/triangle-black.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[Event "ChessPenguin: Semi-Slav Triangle for Black"] -[White "?"] -[Black "Repertoire"] -[Result "*"] -[ECO "D47"] - -{Semi-Slav (Triangle) for Black: the Meran main line, with answers to 5.Bg5, the Exchange Variation and the quiet 4.e3.} -1. d4 d5 2. c4 c6 3. Nf3 e6 {The triangle c6-d5-e6 makes the centre very solid.} -4. Nc3 (4. e3 Nf6 5. Bd3 Nbd7 6. O-O Bd6 7. Nbd2 O-O 8. e4 dxe4 9. Nxe4 Nxe4 10. Bxe4 e5 {Black frees the position with the central break.}) -(4. cxd5 exd5 5. Nc3 Nf6 6. Bg5 Be7 7. e3 Bf5 {Exchange Variation: the c8-bishop gets outside the pawn chain.}) -4... Nf6 5. e3 (5. Bg5 h6 6. Bh4 dxc4 7. e4 g5 8. Bg3 b5 {Moscow Variation: Black grabs the pawn and keeps it with ...b5.}) -5... Nbd7 6. Bd3 dxc4 7. Bxc4 b5 {The Meran: Black gains space on the queenside with tempo.} -8. Bd3 Bb7 9. O-O a6 10. e4 c5 11. d5 Qc7 {Black attacks the centre and is ready to castle.} * diff --git a/apps/desktop/assets/repertoires/triangle-black.ru.pgn b/apps/desktop/assets/repertoires/triangle-black.ru.pgn deleted file mode 100644 index 13287b2..0000000 --- a/apps/desktop/assets/repertoires/triangle-black.ru.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[Event "ChessPenguin: Полуславянская защита (треугольник) за чёрных"] -[White "?"] -[Black "Repertoire"] -[Result "*"] -[ECO "D47"] - -{Полуславянская защита (треугольник) за чёрных: основная система Меран и ответы на 5.Bg5, разменный вариант и спокойное 4.e3.} -1. d4 d5 2. c4 c6 3. Nf3 e6 {Треугольник c6-d5-e6 делает центр очень прочным.} -4. Nc3 (4. e3 Nf6 5. Bd3 Nbd7 6. O-O Bd6 7. Nbd2 O-O 8. e4 dxe4 9. Nxe4 Nxe4 10. Bxe4 e5 {Чёрные освобождают игру центральным подрывом.}) -(4. cxd5 exd5 5. Nc3 Nf6 6. Bg5 Be7 7. e3 Bf5 {Разменный вариант: слон c8 выходит за пешечную цепь.}) -4... Nf6 5. e3 (5. Bg5 h6 6. Bh4 dxc4 7. e4 g5 8. Bg3 b5 {Московский вариант: чёрные берут пешку и удерживают её ходом ...b5.}) -5... Nbd7 6. Bd3 dxc4 7. Bxc4 b5 {Меран: чёрные с темпом захватывают пространство на ферзевом фланге.} -8. Bd3 Bb7 9. O-O a6 10. e4 c5 11. d5 Qc7 {Чёрные атакуют центр и готовы рокироваться.} * diff --git a/apps/desktop/build.rs b/apps/desktop/build.rs index 3c834bf..5219d5b 100644 --- a/apps/desktop/build.rs +++ b/apps/desktop/build.rs @@ -1,12 +1,5 @@ +// Embeds the application icon into the Windows executable. fn main() { - // `cfg(web)`: WebAssembly in a browser (the web version, apps/web). - println!("cargo::rustc-check-cfg=cfg(web)"); - if std::env::var("CARGO_CFG_TARGET_FAMILY").as_deref() == Ok("wasm") - && std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("unknown") - { - println!("cargo::rustc-cfg=web"); - } - // Embeds the application icon into the Windows executable. if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") { let mut res = winresource::WindowsResource::new(); res.set_icon("../../packaging/windows/chesspenguin.ico"); diff --git a/apps/desktop/src/adjourned.rs b/apps/desktop/src/adjourned.rs index dfa318d..718df2d 100644 --- a/apps/desktop/src/adjourned.rs +++ b/apps/desktop/src/adjourned.rs @@ -124,7 +124,6 @@ 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/analysis.rs b/apps/desktop/src/analysis.rs index 339ed8f..d0be947 100644 --- a/apps/desktop/src/analysis.rs +++ b/apps/desktop/src/analysis.rs @@ -1,7 +1,7 @@ -//! Engine analysis controller: owns the engine (a UCI process; in a browser a Web -//! Worker), binds results to the analysed position. +//! Engine analysis controller: owns the UCI process, binds results to the analysed position. use crate::i18n::{tr, trf}; +use std::sync::mpsc::{Receiver, channel}; use shakmaty::san::SanPlus; use shakmaty::uci::UciMove; @@ -38,39 +38,9 @@ struct Target { engine_pos: EnginePosition, } -/// An engine on its way: its process started on a thread of its own (the handshake -/// blocks for up to ~20 s); in a browser its worker, the handshake by its messages. -enum Launch { - #[cfg(not(web))] - Thread(std::sync::mpsc::Receiver>), - /// The worker and the options to set once it answered. - #[cfg(web)] - Worker(uci::Starting, EngineConfig), -} - -impl Launch { - /// The engine once it answered, its options set (or why it did not answer). - fn poll(&mut self) -> Option> { - match self { - #[cfg(not(web))] - Launch::Thread(rx) => rx.try_recv().ok(), - #[cfg(web)] - Launch::Worker(s, cfg) => s.poll().map(|r| r.inspect(|h| set_options(h, cfg))), - } - } -} - -/// Threads, hash and lines of `cfg` (unknown options are not fatal: some engines lack -/// Threads/Hash/MultiPV). -fn set_options(h: &EngineHandle, cfg: &EngineConfig) { - let _ = h.set_threads(cfg.threads); - let _ = h.set_hash_mb(cfg.hash_mb); - let _ = h.set_multipv(cfg.multipv.max(1)); -} - pub struct Analysis { engine: Option, - spawning: Option, + spawning: Option>>, pub status: Status, pub engine_name: String, next_id: u64, @@ -86,7 +56,7 @@ pub struct Analysis { /// The current search ended (time limit reached); lines stay as the final result. pub finished: bool, /// Executable of the running engine (to detect a switch of the active engine). - pub engine_path: Option, + pub engine_path: Option, } impl Analysis { @@ -120,7 +90,7 @@ impl Analysis { matches!(self.status, Status::Starting | Status::Running) } - /// Starts the engine in the background: its options are set once it answered. + /// Starts the engine in a background thread (handshake blocks for up to ~20 s). pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) { self.stop(); let Some(path) = cfg.executable() else { @@ -128,32 +98,48 @@ impl Analysis { Status::Failed(tr("The built-in engine is not part of this build").into()); return; }; + let (tx, rx) = channel(); + let ctx_w = ctx.clone(); + let ctx_done = ctx.clone(); + let cfg = cfg.clone(); self.engine_name = cfg.name.clone(); self.multipv = cfg.multipv.max(1); self.limit = cfg.search_secs; self.engine_path = Some(path.clone()); - match launch(path, cfg.clone(), ctx) { - Ok(l) => { - self.spawning = Some(l); + let spawned = std::thread::Builder::new() + .name("engine-spawn".into()) + .spawn(move || { + let res = uci::Engine::spawn_with( + uci::EngineConfig::new(&path), + Box::new(move || ctx_w.request_repaint()), + ) + .inspect(|h| { + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = h.set_threads(cfg.threads); + let _ = h.set_hash_mb(cfg.hash_mb); + let _ = h.set_multipv(cfg.multipv.max(1)); + }); + let _ = tx.send(res); + ctx_done.request_repaint(); + }); + match spawned { + Ok(_) => { + self.spawning = Some(rx); self.status = Status::Starting; } - Err(e) => self.status = Status::Failed(e), + Err(e) => self.status = Status::Failed(e.to_string()), } } - /// Stops analysis and terminates the engine. + /// Stops analysis and terminates the engine process. pub fn stop(&mut self) { if let Some(e) = self.engine.take() { - // quit() may wait up to the quit timeout; do it off the UI thread. A worker - // stops at once. - #[cfg(not(web))] + // quit() may wait up to the quit timeout; do it off the UI thread. let _ = std::thread::Builder::new() .name("engine-quit".into()) .spawn(move || { e.quit(); }); - #[cfg(web)] - e.quit(); } self.spawning = None; self.current = None; @@ -226,7 +212,9 @@ impl Analysis { /// Drains engine events; call once per frame. pub fn poll(&mut self) { - if let Some(res) = self.spawning.as_mut().and_then(Launch::poll) { + if let Some(rx) = &self.spawning + && let Ok(res) = rx.try_recv() + { self.spawning = None; match res { Ok(h) => { @@ -293,49 +281,6 @@ impl Analysis { } } -/// Starts the engine of `cfg` at `path` with its options. -#[cfg(not(web))] -fn launch( - location: crate::engines::EngineLocation, - cfg: EngineConfig, - ctx: &egui::Context, -) -> Result { - let crate::engines::EngineLocation::Program(path) = location; - let (tx, rx) = std::sync::mpsc::channel(); - let ctx_w = ctx.clone(); - let ctx_done = ctx.clone(); - std::thread::Builder::new() - .name("engine-spawn".into()) - .spawn(move || { - let res = uci::Engine::spawn_with( - uci::EngineConfig::new(&path), - Box::new(move || ctx_w.request_repaint()), - ) - .inspect(|h| set_options(h, &cfg)); - let _ = tx.send(res); - ctx_done.request_repaint(); - }) - .map(|_| Launch::Thread(rx)) - .map_err(|e| e.to_string()) -} - -/// Starts the engine of `cfg` in its Web Worker. -#[cfg(web)] -fn launch( - location: crate::engines::EngineLocation, - cfg: EngineConfig, - ctx: &egui::Context, -) -> Result { - let crate::engines::EngineLocation::Worker(script) = location; - let ctx = ctx.clone(); - uci::Engine::start_worker( - uci::WorkerConfig::new(script), - Box::new(move || ctx.request_repaint()), - ) - .map(|s| Launch::Worker(s, cfg)) - .map_err(|e| e.to_string()) -} - impl Drop for Analysis { fn drop(&mut self) { self.stop(); diff --git a/apps/desktop/src/app.rs b/apps/desktop/src/app.rs index 7c7f185..1a60d7b 100644 --- a/apps/desktop/src/app.rs +++ b/apps/desktop/src/app.rs @@ -17,49 +17,18 @@ use crate::own_db::{ self, Answer, ChooserFor, ChooserOutcome, EditorMode, EditorOutcome, NewBaseOutcome, QuestionKind, }; -use crate::prep_ui::{DialogOutcome, PrepAction, PrepDialog, PrepScreen}; use crate::settings::{EngineConfig, Settings}; use crate::settings_ui::{SettingsAction, SettingsWindow, Tab}; use crate::sound::SoundPlayer; /// Results of work done off the UI thread (file dialogs, engine checks). enum Async { - /// Databases chosen in a dialog (none: it was cancelled). DatabasesPicked(Vec), - /// Databases dropped on the window. - DatabasesDropped(Vec), - /// Files dropped on the window that are no longer there (their names). - Missing(Vec), - /// Files not opened: too big for a browser (name, bytes). - #[cfg(web)] - TooBig(Vec<(String, u64)>), SavePicked(PathBuf), SaveCancelled, EngineChecked(Result<(PathBuf, String), String>), /// The folder for new databases (`None`: the dialog was cancelled). FolderPicked(Option), - /// A remembered file the browser let the page read again. - #[cfg(web)] - ReadAllowed(PathBuf), - /// ChessBase databases not all files of which were chosen (their `.cbh` names). - #[cfg(web)] - Incomplete(Vec), - /// A folder was chosen (or dropped) with no database in it. - EmptyFolder, - /// Files dropped on the window that are no databases (their names). - NotDatabases(Vec), - /// A copy of the visit's database `.0` kept in the browser, or why not. - #[cfg(web)] - CopyKept(PathBuf, Result), -} - -/// What the web version tells in a window of its own about the files chosen. -#[cfg(web)] -enum WebNotice { - /// Databases too big for a browser (name, bytes). - TooBig(Vec<(String, u64)>), - /// A ChessBase database's `.cbh` chosen without its other files (its name). - Incomplete(String), } /// A passing message at the bottom; `undo`: with the button that puts a deleted game back. @@ -245,30 +214,19 @@ pub struct App { play_next: Option, tx: Sender, rx: Receiver, - /// «Paste PGN»: the clipboard being read. - pasting: Option, - /// A file of the last visit being chosen again (a browser's). - choosing_again: Option, - /// The web version's draft of an unsaved game: the one left at the last visit - /// (offered), and when this visit's was last written (egui time; `None`: none). - #[cfg(web)] - draft_offer: Option, - #[cfg(web)] - draft_at: Option, - #[cfg(web)] - web_notice: Option, confirm_close: Option, /// Close the game once the pending "save as" succeeds. close_after_save: Option, /// The offer to download Stockfish when an action needs an engine. engine_offer: crate::engine_offer::EngineOffer, - /// What waits for an engine of the user's to be probed (`review_engine`): at most - /// one game analysis and one search for opening errors. - review_wait: Vec, offer_hook_done: bool, - /// What only the desktop program has: online games, updates. - #[cfg(not(web))] - desktop: Desktop, + /// Lichess / Chess.com: which answered at start, and the download window. + online_probe: crate::online::Probe, + /// When the online databases were last updated on their own (egui time, s), and + /// whether the window had the focus in the last frame. + online_updated_at: f64, + was_focused: bool, + online: crate::online_ui::OnlineDialog, /// Translating comments: the setup and consent windows, the ChatGPT sign-in. translation: crate::translate_ui::Hub, /// A position to find in a database once the game is closed. @@ -278,86 +236,17 @@ pub struct App { previous_games: Vec, /// The last game showed the reference tab: the next one opens with it too. reference_tab: bool, - /// The executable to start after quitting (a restart into the new version). - restart_to: Option, - /// The reference tab of games (kept across games: its results stay cached). - reference: crate::reference::Reference, - /// Preparing against an opponent: the dialog, and the report screen in the stack - /// between the library and the game (opponent-prep.md §3.1). - prep_dialog: Option, - prep: Option, - /// The library's «Preparations» window, and a saved preparation waiting for its - /// database to be read. - prep_list: Option, - /// The names of its player, found again in the database once it is read. - prep_waiting: Option<(crate::prep_ui::PrepStart, Vec)>, - /// Quitting while the opening errors are searched: asked first; «Quit» answered. - prep_quit_ask: bool, - prep_quit_ok: bool, - allow_quit: bool, - #[cfg(not(web))] - repertoire: Option, - #[cfg(not(web))] - toast_repertoire: Option<(trainer::repertoire::RepertoireId, String)>, - /// The database a copy of chosen games made: the toast's «Open». - toast_open_db: Option, - /// The search for great moves (task 27): its question, the list and conditions of - /// the pass under way, and its summary. - brilliant_start: Option, - brilliant_pass: Option, - brilliant_summary: Option, - /// A pass asked for while Stockfish 19 is fetched or checked: it starts after. - brilliant_waiting: Option, - /// The plies of the games the pass under way analyses, for its time left. - brilliant_plies: std::collections::HashMap, - applied_dark: Option, - debug: DebugStartup, -} - -/// What only the desktop program has. -#[cfg(not(web))] -struct Desktop { - /// Lichess / Chess.com: which answered at start, and the download window. - online_probe: crate::online::Probe, - /// When the online databases were last updated on their own (egui time, s), and - /// whether the window had the focus in the last frame. - online_updated_at: f64, - was_focused: bool, - online: crate::online_ui::OnlineDialog, - /// Updates: the release check, how this copy is installed, the window. + /// Updates: the release check, how this copy is installed, the window, and the + /// executable to start after quitting (a restart into the new version). update_check: crate::update::Check, update_kind: crate::update::Install, update_ui: crate::update_ui::UpdateDialog, -} - -#[cfg(not(web))] -impl Desktop { - fn new(ctx: &egui::Context, settings: &Settings) -> Desktop { - let online_dbs: Vec = settings - .databases - .iter() - .filter(|p| crate::online::is_online(p)) - .cloned() - .collect(); - Desktop { - online_probe: crate::online::Probe::start(ctx), - online_updated_at: 0.0, - was_focused: true, - online: { - // Every downloaded database gets the games played since, at each start. - let mut d = crate::online_ui::OnlineDialog::from_env(); - d.update_quietly(online_dbs); - d - }, - update_check: if settings.check_updates { - crate::update::Check::start(ctx) - } else { - crate::update::Check::idle() - }, - update_kind: crate::update::detect(), - update_ui: crate::update_ui::UpdateDialog::from_env(), - } - } + restart_to: Option, + /// The reference tab of games (kept across games: its results stay cached). + reference: crate::reference::Reference, + allow_quit: bool, + applied_dark: Option, + debug: DebugStartup, } /// Dev-only startup automation for screenshots/manual QA (see docs/dev/desktop.md): @@ -380,9 +269,6 @@ struct DebugStartup { screenshot_delay: f64, screenshot_requested: bool, open_settings: bool, - /// `CP_SETTINGS_CLICK=x,y`: one primary click in viewport points, after opening. - #[cfg(all(debug_assertions, not(web)))] - settings_click: Option, /// `CP_OWN=new|chooser|data|save|delete`: that dialog of the own databases /// (own_db.rs) after a short delay; `delete` and `chooser` without a game: the /// record `CP_OPEN` (default 0) of the first database. @@ -393,9 +279,6 @@ struct DebugStartup { next_key: f64, /// `CP_TYPE=`: typed into the field that has the keyboard, 2.5 s after start. typed: Option, - /// `CP_PREP=`: «Prepare against…» for this name in the first database - /// (`CP_PREP_OPEN=1` presses «Open report», `CP_PREP_TAB`). - prep: Option, } impl DebugStartup { @@ -413,11 +296,6 @@ impl DebugStartup { .unwrap_or(4.0), screenshot_requested: false, open_settings: false, - #[cfg(all(debug_assertions, not(web)))] - settings_click: std::env::var("CP_SETTINGS_CLICK").ok().and_then(|coords| { - let (x, y) = coords.split_once(',')?; - Some(egui::pos2(x.parse().ok()?, y.parse().ok()?)) - }), own: std::env::var("CP_OWN").ok(), play: std::env::var("CP_PLAY").ok(), keys: std::env::var("CP_KEYS") @@ -443,7 +321,6 @@ impl DebugStartup { .collect(), next_key: 2.0, typed: std::env::var("CP_TYPE").ok(), - prep: std::env::var("CP_PREP").ok(), } } } @@ -451,68 +328,27 @@ impl DebugStartup { impl App { pub fn new(ctx: &egui::Context) -> Self { let mut settings = Settings::load(); - let repertoire_migrated = settings.migrate_repertoire_flow(); - #[cfg(not(web))] - { - if let Ok(language) = std::env::var("CP_LANG") - && let Some(language) = crate::i18n::Lang::from_locale(&language) - { - settings.language = language; - } - if let Ok(dark) = std::env::var("CP_DARK") { - settings.dark_mode = dark != "0"; - } - // Dev hook (screenshots, tests): `CP_HINT_RESET=1` shows the one-time hints anew. - if std::env::var("CP_HINT_RESET").as_deref() == Ok("1") { - settings.hints = Default::default(); - } - } // Before the samples, which are named in this language. crate::i18n::set_lang(settings.language); crate::engine_download::clean_leftovers(); - // Temporary files of copies of chosen games left by a crash: in the folders of the - // databases, away from the window's thread (a network drive may be slow). - #[cfg(not(web))] - { - let mut dirs: Vec = settings - .databases - .iter() - .filter_map(|p| p.parent().map(|d| d.to_path_buf())) - .collect(); - dirs.push(own_db::default_base_dir( - settings.new_database_dir.as_deref(), - )); - dirs.sort(); - dirs.dedup(); - let _ = std::thread::Builder::new() - .name("copy-leftovers".into()) - .spawn(move || crate::batch_copy::clean_orphans(&dirs)); - } + crate::update::clean_leftovers(); + let settings_check_updates = settings.check_updates; + // "Updated to …" once, when this version runs for the first time after another. let current = env!("CARGO_PKG_VERSION"); - #[cfg(not(web))] - let updated_from = { - crate::update::clean_leftovers(); - // "Updated to …" once, when this version runs for the first time after another. - let from = settings.last_version.clone().filter(|v| { - crate::update::parse_version(v) < crate::update::parse_version(current) - }); - if settings.install_id.is_empty() { - settings.install_id = crate::update::new_install_id(); - } - crate::update::set_install_id(&settings.install_id); - from - }; + let updated_from = settings + .last_version + .clone() + .filter(|v| crate::update::parse_version(v) < crate::update::parse_version(current)); + if settings.install_id.is_empty() { + settings.install_id = crate::update::new_install_id(); + } + crate::update::set_install_id(&settings.install_id); if settings.last_version.as_deref() != Some(current) { settings.last_version = Some(current.to_owned()); let _ = settings.save(); } let engines_found = crate::engines::first_run_setup(&mut settings); - if crate::examples::setup(&mut settings) || engines_found { - let _ = settings.save(); - } - // After the samples: a new library opens on the classics. - #[cfg(web)] - if crate::my_games::setup(&mut settings) { + if crate::examples::first_run_setup(&mut settings) || engines_found { let _ = settings.save(); } // PGN files passed on the command line (e.g. "Open with…") join the library, first one selected. @@ -528,8 +364,12 @@ impl App { if !args.is_empty() { let _ = settings.save(); } - #[cfg(not(web))] - let desktop = Desktop::new(ctx, &settings); + let online_dbs: Vec = settings + .databases + .iter() + .filter(|p| crate::online::is_online(p)) + .cloned() + .collect(); let (tx, rx) = channel(); let mut library = Library::new(ctx); // Read in the background: a missing file says so there (a lost network drive @@ -539,7 +379,7 @@ impl App { } let mut app = Self { settings, - settings_dirty: repertoire_migrated, + settings_dirty: false, sound: SoundPlayer::new(), library, game: None, @@ -556,50 +396,37 @@ impl App { play_next: None, tx, rx, - pasting: None, - choosing_again: None, - #[cfg(web)] - draft_offer: crate::my_games::read_draft(), - #[cfg(web)] - draft_at: None, - #[cfg(web)] - web_notice: None, confirm_close: None, close_after_save: None, find_after_close: None, previous_games: Vec::new(), reference_tab: false, + update_check: if settings_check_updates { + crate::update::Check::start(ctx) + } else { + crate::update::Check::idle() + }, + update_kind: crate::update::detect(), + update_ui: crate::update_ui::UpdateDialog::from_env(), restart_to: None, reference: Default::default(), - prep_dialog: None, - prep: None, - prep_list: None, - prep_waiting: None, - prep_quit_ask: false, - prep_quit_ok: false, engine_offer: crate::engine_offer::EngineOffer::new(), - review_wait: Vec::new(), offer_hook_done: false, - #[cfg(not(web))] - desktop, + online_probe: crate::online::Probe::start(ctx), + online_updated_at: 0.0, + was_focused: true, + online: { + // Every downloaded database gets the games played since, at each start. + let mut d = crate::online_ui::OnlineDialog::from_env(); + d.update_quietly(online_dbs); + d + }, translation: Default::default(), allow_quit: false, - #[cfg(not(web))] - repertoire: None, - #[cfg(not(web))] - toast_repertoire: None, - toast_open_db: None, - brilliant_start: None, - brilliant_pass: None, - brilliant_summary: None, - brilliant_waiting: None, - brilliant_plies: std::collections::HashMap::new(), applied_dark: None, debug: DebugStartup::from_env(), } .with_debug_settings(); - crate::review_engine::set_candidates(&app.settings); - #[cfg(not(web))] if let Some(from) = updated_from { let msg = trf( "ChessPenguin is updated: {from} → {to}", @@ -785,15 +612,7 @@ impl App { }; let now = ctx.input(|i| i.time); if !self.debug.screenshot_requested { - let size = std::env::var("CP_SCREENSHOT_SIZE").ok().and_then(|size| { - let (width, height) = size.split_once('x')?; - Some(egui::vec2(width.parse().ok()?, height.parse().ok()?)) - }); - if let Some(size) = size { - ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(false)); - ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(size)); - } else if ctx.cumulative_frame_nr() == 1 { + if ctx.cumulative_frame_nr() == 1 { ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(true)); } if now >= self.debug.screenshot_delay { @@ -823,106 +642,6 @@ impl App { } fn debug_step(&mut self, ctx: &egui::Context) { - #[cfg(not(web))] - if let Ok(what) = std::env::var("CP_REPERTOIRE") { - static OPEN: std::sync::Once = std::sync::Once::new(); - OPEN.call_once(|| { - self.repertoire = Some(crate::repertoire_ui::RepertoireUi::new()); - if let Some(screen) = self.repertoire.as_mut() { - screen.debug_open(&what, &mut self.settings); - } - }); - } - #[cfg(not(web))] - if let Ok(path) = std::env::var("CP_REPERTOIRE_IMPORT_FILE") { - static IMPORT: std::sync::Once = std::sync::Once::new(); - IMPORT.call_once(|| { - if let Some(screen) = self.repertoire.as_mut() { - screen.debug_import(PathBuf::from(path)); - } - }); - } - #[cfg(not(web))] - if std::env::var_os("CP_REPERTOIRE_EXPORT").is_some() { - static EXPORT: std::sync::Once = std::sync::Once::new(); - EXPORT.call_once(|| { - if let Some(screen) = self.repertoire.as_mut() { - screen.debug_export(); - } - }); - } - #[cfg(not(web))] - if std::env::var_os("CP_REPERTOIRE_CONFIRM_IMPORT").is_some() - && let Some(screen) = self.repertoire.as_mut() - { - screen.debug_confirm_import(&self.settings); - } - #[cfg(not(web))] - if let Ok(name) = std::env::var("CP_REPERTOIRE_RENAME") { - static RENAME: std::sync::Once = std::sync::Once::new(); - if !RENAME.is_completed() { - let mut done = false; - if let Some(screen) = self.repertoire.as_mut() { - done = screen.debug_rename(name, &self.settings); - } - if done { - RENAME.call_once(|| {}); - } - } - } - #[cfg(not(web))] - if std::env::var_os("CP_REPERTOIRE_DELETE").is_some() { - static DELETE: std::sync::Once = std::sync::Once::new(); - if !DELETE.is_completed() { - let mut done = false; - if let Some(screen) = self.repertoire.as_mut() { - done = screen.debug_delete(&self.settings); - } - if done { - DELETE.call_once(|| {}); - } - } - } - #[cfg(not(web))] - if let Ok(moves) = std::env::var("CP_REPERTOIRE_MOVES") { - static MOVES: std::sync::Once = std::sync::Once::new(); - MOVES.call_once(|| { - if let Some(screen) = self.repertoire.as_mut() { - screen.debug_moves(&moves); - } - }); - } - #[cfg(not(web))] - if std::env::var_os("CP_REPERTOIRE_HINT").is_some() { - static HINT: std::sync::Once = std::sync::Once::new(); - HINT.call_once(|| { - if let Some(screen) = self.repertoire.as_mut() { - screen.debug_hint(); - } - }); - } - if self.debug.prep.is_some() - && let Some(path) = self.settings.databases.first().cloned() - && self.library.database(&path).is_some() - { - let query = self.debug.prep.take().unwrap_or_default(); - let side = match std::env::var("CP_PREP_COLOR").as_deref() { - Ok("white") => chess_import::chessbase::base::Side::White, - Ok("black") => chess_import::chessbase::base::Side::Black, - _ => chess_import::chessbase::base::Side::Any, - }; - let entry = crate::prep_ui::PrepEntry { - query, - exact: None, - side, - }; - self.prep_dialog = Some(PrepDialog::new(path, entry)); - } - // `CP_PREP_LIST=1`: the «Preparations» window at the start (screenshots). - if self.prep_list.is_none() && std::env::var_os("CP_PREP_LIST").is_some() { - static SHOWN: std::sync::Once = std::sync::Once::new(); - SHOWN.call_once(|| self.prep_list = Some(crate::prep_ui::PrepList::new())); - } let Some(index) = self.debug.open else { return }; let Some(path) = self.settings.databases.first().cloned() else { return; @@ -987,42 +706,12 @@ impl App { g.debug_show_report(); } if let Some(k) = std::env::var("CP_BEST").ok().and_then(|v| v.parse().ok()) { - // `CP_BEST_DELAY=`: the line opens that long after the notation is first - // drawn (`CP_BEST_EXIT_AFTER=`: and closes that long after it opened). - let ms = |name| { - std::env::var(name) - .ok() - .and_then(|v| v.parse::().ok()) - .map(|ms| ms as f64 / 1000.0) - }; - match ms("CP_BEST_DELAY") { - Some(delay) => g.debug_best_line_later(k, delay, ms("CP_BEST_EXIT_AFTER")), - None => g.debug_best_line(k), - } + g.debug_best_line(k); } - // CP_REVIEW=ask presses «Analyse», any other value starts the analysis. + // CP_REVIEW=dialog opens the game-analysis dialog, =ask presses «Analyse», any + // other value starts the analysis. if let Ok(v) = std::env::var("CP_REVIEW") { - g.debug_review(ctx, &v); - } - } - #[cfg(not(web))] - { - static ADD_REPERTOIRE: std::sync::Once = std::sync::Once::new(); - if let Ok(name) = std::env::var("CP_ADD_REPERTOIRE") - && !ADD_REPERTOIRE.is_completed() - && let Some((game, at)) = - self.game.as_ref().and_then(|g| g.debug_repertoire_source()) - { - ADD_REPERTOIRE.call_once(|| {}); - let title = self.game.as_ref().map(GameView::title).unwrap_or_default(); - if let Some(game_view) = self.game.as_mut() { - game_view.suspend(); - } - self.analysis.stop(); - self.repertoire = Some(crate::repertoire_ui::RepertoireUi::new()); - if let Some(screen) = self.repertoire.as_mut() { - screen.debug_add_from_game(game, at, title, name); - } + g.debug_review(&self.settings, ctx, &v); } } if let Some(start) = self.debug.play_from.take() { @@ -1047,258 +736,8 @@ impl App { self.toast_for(ctx, msg, 3.5); } - /// The shelf as the reference tab and the preparation see it. - fn shelf_dbs(&self) -> Vec { - self.settings - .databases - .iter() - .filter(|p| self.library.files.exists(p)) - .map(|p| crate::reference::RefDb { - path: p.clone(), - name: p - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(), - db: self.library.database(p), - failed: self.library.failure(p).map(str::to_owned), - bytes: self.library.file_size(p), - }) - .collect() - } - - // ----- preparing against an opponent (docs/design/opponent-prep.md) ------------ - - /// «Open report»: the report of the same player as it was, else a new one. - fn open_prep(&mut self, ctx: &egui::Context, start: crate::prep_ui::PrepStart) { - let Some(db) = self.library.database(&start.path) else { - return; - }; - if let Some(p) = self.prep.as_mut() - && p.matches(&start.path, &start.player) - { - // The report as it was, with the colour of the dialog. - p.reopen(start.side); - return; - } - if let Some(mut old) = self.prep.take() { - old.save(); - } - self.prep = Some(PrepScreen::new(start, db, &self.settings, ctx)); - } - - /// «Opening errors are being searched. Quit and stop?» - fn prep_quit_question(&mut self, ctx: &egui::Context) { - if !self.prep_quit_ask { - return; - } - let mut choice = None; - egui::Modal::new(egui::Id::new("prep_quit")).show(ctx, |ui| { - ui.set_width(400.0); - ui.label(tr("Opening errors are being searched. Quit and stop?")); - ui.label(RichText::new(tr("What was found is kept.")).weak()); - ui.add_space(8.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Cancel")).clicked() { - choice = Some(false); - } - if crate::widgets::primary(ui, tr("Quit")).clicked() { - choice = Some(true); - } - }); - }); - if choice.is_none() && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { - choice = Some(false); - } - match choice { - Some(true) => { - self.prep_quit_ask = false; - self.prep_quit_ok = true; - if let Some(p) = self.prep.as_mut() { - p.stop(); - } - // The usual way out from here (unsaved games are asked about). - ctx.send_viewport_cmd(egui::ViewportCommand::Close); - } - Some(false) => self.prep_quit_ask = false, - None => {} - } - } - - /// «🗐 Preparations», and a saved preparation opened once its database is read. - fn prep_list(&mut self, ctx: &egui::Context) { - if let Some((mut start, names)) = self.prep_waiting.take() { - if let Some(db) = self.library.database(&start.path) { - // The player by his names: the database's ids of them may have changed. - let mut ids = Vec::new(); - let mut missing = None; - for name in &names { - // Every id of the name (a ChessBase database can have two). - let (found, _) = prep::candidates(&db, name, 50); - let before = ids.len(); - ids.extend(found.iter().filter(|c| c.name == *name).map(|c| c.id)); - if ids.len() == before { - missing = Some(name.clone()); - } - } - match missing { - Some(name) => self.toast( - ctx, - trf( - "The player is not in the database: {name}", - &[("name", &name)], - ), - ), - None => { - start.player = prep::Player::new(ids); - self.open_prep(ctx, start); - } - } - } else if let Some(e) = self.library.failure(&start.path) { - let e = e.to_owned(); - self.toast( - ctx, - trf("This database cannot be opened: {e}", &[("e", &e)]), - ); - } else { - self.prep_waiting = Some((start, names)); - } - } - let Some(list) = self.prep_list.as_mut() else { - return; - }; - let can_new = !self.settings.databases.is_empty(); - match list.show(ctx, can_new) { - Some(crate::prep_ui::ListOutcome::Close) => self.prep_list = None, - Some(crate::prep_ui::ListOutcome::New) => { - self.prep_list = None; - let (path, entry) = match self.library.prep_entry() { - Some((path, entry)) => (path, entry.unwrap_or_default()), - None => match self.settings.databases.first() { - Some(p) => (p.clone(), Default::default()), - None => return, - }, - }; - self.prep_dialog = Some(PrepDialog::new(path, entry)); - } - Some(crate::prep_ui::ListOutcome::Open(id)) => { - let Some(meta) = crate::prep_saved::dir() - .as_deref() - .and_then(|d| crate::prep_saved::get(d, &id)) - else { - return; - }; - self.prep_list = None; - if !self.settings.databases.contains(&meta.path) { - self.settings.touch_database(&meta.path); - self.settings_dirty = true; - } - let start = crate::prep_ui::PrepStart { - path: meta.path, - player: meta.player, - side: meta.color, - }; - if self.library.database(&start.path).is_none() { - self.library.load(&start.path, ctx); - self.toast(ctx, tr("Opening the database…")); - } - self.prep_waiting = Some((start, meta.names)); - ctx.request_repaint(); - } - None => {} - } - } - - /// The preparation's dialog, when it is open. - fn prep_dialog(&mut self, ctx: &egui::Context) { - if self.prep_dialog.is_none() { - return; - } - let dbs = self.shelf_dbs(); - let Some(d) = self.prep_dialog.as_mut() else { - return; - }; - d.dbs = dbs; - let outcome = d.show(ctx, &mut self.settings); - match outcome { - Some(DialogOutcome::Open(start)) => { - self.prep_dialog = None; - self.settings_dirty = true; - self.open_prep(ctx, start); - } - Some(DialogOutcome::Cancel) => self.prep_dialog = None, - Some(DialogOutcome::LoadDb(p)) - if !self.library.loading(&p) && self.library.database(&p).is_none() => - { - self.library.load(&p, ctx); - } - Some(DialogOutcome::LoadDb(_)) | None => {} - } - } - - fn prep_actions(&mut self, ctx: &egui::Context, actions: Vec) { - for a in actions { - match a { - PrepAction::Back => { - if let Some(p) = self.prep.as_mut() { - p.shown = false; - p.save(); - } - } - PrepAction::OpenSettings => self.settings_ui.open = !self.settings_ui.open, - PrepAction::OpenGame { path, index, ply } => { - let title = self.prep.as_ref().map(|p| p.title()); - self.open_game(ctx, path, index, None); - if let Some(g) = self.game.as_mut() { - g.previous = title; - g.previous_prep = true; - g.goto_ply(ply); - } - } - // One engine job for the whole program: the live engine is off while - // the report is on the screen anyway (no game is open then). - PrepAction::EngineStarted => { - self.analysis.stop(); - self.live_paused = false; - } - PrepAction::EngineEnded => {} - PrepAction::NeedEngine => { - if let Some(prep) = self.prep.as_ref().map(|p| p.serial) { - let pending = crate::engine_offer::Pending::OpeningErrors { prep }; - self.need_review_engine(ctx, pending); - } - } - PrepAction::SettingsChanged => self.settings_dirty = true, - PrepAction::Toast(m) => self.toast(ctx, m), - PrepAction::CopyText(text, msg) => { - ctx.copy_text(text); - self.toast(ctx, msg); - } - PrepAction::OpenPgn(text) => { - let title = self.prep.as_ref().map(|p| p.title()); - self.open_pgn_text(ctx, text, true); - if let Some(g) = self.game.as_mut() { - g.previous = title; - g.previous_prep = true; - } - } - PrepAction::FindPosition(path, start, line, flipped) => { - if let Some(p) = self.prep.as_mut() { - p.shown = false; - } - self.library.show_position(&path, start, line, flipped, ctx); - } - PrepAction::PlayFrom(from) => self.play_new(ctx, PlayNext::Dialog(Some(from))), - } - } - } - /// A message said once and seldom (a database made for the player): longer in view. fn toast_for(&mut self, ctx: &egui::Context, msg: impl Into, secs: f64) { - #[cfg(not(web))] - { - self.toast_repertoire = None; - } - self.toast_open_db = None; self.toast = Some(Toast { text: msg.into(), until: ctx.input(|i| i.time) + secs, @@ -1323,16 +762,6 @@ impl App { let target = self.current_target(); let Some(g) = &self.game else { return }; self.own.then_close = then_close; - // The web version keeps the user's games in «My games»: a game from anywhere - // else (a file, which is only read, a sample, a new one) goes there, no question. - #[cfg(web)] - if !matches!(&g.source, Some(src) if src.block.is_none()) { - if crate::platform::web::storage::persisted() != Some(true) { - crate::platform::web::storage::persist(|_| {}); - } - self.add_current_to(ctx, crate::my_games::path()); - return; - } match &g.source { Some(src) if src.block.is_none() => { if !g.game.is_modified() { @@ -1380,7 +809,7 @@ impl App { }; let Some(pgn) = db.as_pgn() else { return }; let text = g.game.to_pgn(); - match crate::platform::pgn_store::replace(pgn, &src.path, src.index, &text) { + match chess_core::pgn::store::replace(pgn, src.index, &text) { Ok(()) => { let name = own_db::base_name(&src.path); if let Some(g) = self.game.as_mut() { @@ -1507,7 +936,10 @@ impl App { /// The PGN text of record `index` of a database, as `current_pgn` would give it. fn record_pgn(&self, from: &std::path::Path, index: usize) -> Option { let db = self.library.database(from)?; - crate::batch_copy::record_text(&db, index) + match db.as_pgn() { + Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index), + _ => db.load_game(index).map(|p| p.game.to_pgn()), + } } fn append_current(&mut self, ctx: &egui::Context, target: PathBuf) { @@ -1518,7 +950,7 @@ impl App { return; }; let Some(pgn) = db.as_pgn() else { return }; - match crate::platform::pgn_store::append(pgn, &target, &text) { + match chess_core::pgn::store::append(pgn, &text) { Ok(_) => { let index = pgn.len(); let name = own_db::base_name(&target); @@ -1557,7 +989,7 @@ impl App { return; }; let Some(pgn) = db.as_pgn() else { return }; - match crate::platform::pgn_store::replace(pgn, &target, index, &text) { + match chess_core::pgn::store::replace(pgn, index, &text) { Ok(()) => { let name = own_db::base_name(&target); if let Some(g) = self.game.as_mut() { @@ -1652,7 +1084,7 @@ impl App { return; }; let Some(pgn) = db.as_pgn() else { return }; - match crate::platform::pgn_store::append(pgn, &target, &text) { + match chess_core::pgn::store::append(pgn, &text) { Ok(_) => { let n = pgn.len(); let name = own_db::base_name(&target); @@ -1698,7 +1130,7 @@ impl App { return; }; let Some(pgn) = db.as_pgn() else { return }; - match crate::platform::pgn_store::replace(pgn, &target, at, &text) { + match chess_core::pgn::store::replace(pgn, at, &text) { Ok(()) => { let name = own_db::base_name(&target); self.settings.last_target = Some(target.clone()); @@ -1853,7 +1285,7 @@ impl App { return; }; let Some(pgn) = db.as_pgn() else { return }; - match crate::platform::pgn_store::remove(pgn, &path, index) { + match chess_core::pgn::store::remove(pgn, index) { Ok(removed) => { // Games open from this file: their records moved up by one. let mut open = None; @@ -1910,7 +1342,7 @@ impl App { return; }; let Some(pgn) = db.as_pgn() else { return }; - match crate::platform::pgn_store::restore(pgn, &undo.path, &undo.removed) { + match chess_core::pgn::store::restore(pgn, &undo.removed) { Ok(()) => { let index = undo.removed.index; for g in self.game.iter_mut().chain(self.previous_games.iter_mut()) { @@ -1970,420 +1402,6 @@ impl App { self.own.new_base = Some(own_db::NewBaseDialog::new(dir, after)); } - /// Why the engine cannot take the search for great moves now, if it cannot (one engine - /// job in the program, task 27 §4.5). - fn engine_job_busy(&self) -> Option { - if self.prep.as_ref().is_some_and(|p| p.running()) { - return Some( - tr("The engine is busy searching opening errors in a preparation: wait or stop it") - .to_owned(), - ); - } - if let Some(g) = self.game.as_ref().filter(|g| g.review_running()) { - return Some(trf( - "The engine is busy reviewing {game}", - &[("game", &g.title())], - )); - } - None - } - - /// While the search for great moves runs, what cannot start says why. - fn pass_busy(&self) -> Option { - let job = self.library.pass.as_ref()?; - Some(trf( - "Searching for great moves in «{db}»: {i} of {n}. Stop it in the library", - &[ - ("db", &own_db::base_name(&job.source)), - ("i", &job.done()), - ("n", &job.records.len()), - ], - )) - } - - /// «!! Find great moves»: the question first (or the summary, when every game is - /// analysed already). - fn ask_great_moves( - &mut self, - ctx: &egui::Context, - path: PathBuf, - records: Vec, - filter: chess_import::chessbase::base::Filter, - about: String, - selected: Option, - ) { - if self.library.pass.is_some() { - return; - } - if let Some(why) = self.engine_job_busy() { - self.toast(ctx, why); - return; - } - let (Some(db), Some(cache)) = (self.library.database(&path), crate::review::cache_dir()) - else { - return; - }; - let index = self.library.marks(&path); - let mut dialog = crate::brilliant_ui::StartDialog::new( - ctx, path, db, records, filter, about, selected, cache, index, - ); - // `CP_BRILLIANT_RUN=1`: no question. - if std::env::var_os("CP_BRILLIANT_RUN").is_some() { - let cancel = std::sync::atomic::AtomicBool::new(false); - if let (Some(db), Some(cache)) = ( - self.library.database(&dialog.source), - crate::review::cache_dir(), - ) { - let index = self.library.marks(&dialog.source); - dialog.counted = Some(crate::brilliant_ui::count( - &db, - &dialog.records, - &dialog.filter, - &cache, - &index, - &cancel, - )); - } - self.start_great_moves(ctx, dialog); - return; - } - self.brilliant_start = Some(dialog); - } - - /// Starts the pass of `dialog` over its games not analysed yet (a browser has none: - /// `CAPS.great_moves`). - #[cfg(web)] - fn start_great_moves( - &mut self, - _ctx: &egui::Context, - _dialog: crate::brilliant_ui::StartDialog, - ) { - } - - /// Starts the pass of `dialog` over its games not analysed yet. - #[cfg(not(web))] - fn start_great_moves(&mut self, ctx: &egui::Context, dialog: crate::brilliant_ui::StartDialog) { - let mut dialog = dialog; - let Some(counted) = dialog.counted.take() else { - return; - }; - let Some(crate::engines::EngineLocation::Program(engine)) = crate::review_engine::engine() - else { - // The offer of «Analyse game»: download Stockfish 19 (or check the user's); - // the pass starts after it. - dialog.counted = Some(counted); - self.brilliant_waiting = Some(dialog); - self.need_review_engine(ctx, crate::engine_offer::Pending::GreatMoves); - return; - }; - let (Some(db), Some(cache)) = ( - self.library.database(&dialog.source), - crate::review::cache_dir(), - ) else { - return; - }; - // One engine job: the live analysis stops. - if self.analysis.is_on() { - self.analysis.stop(); - self.live_paused = false; - } - let path = engine.clone(); - let engine = crate::brilliant::Engine { - config: crate::review::engine_config(&engine), - settings: game_review::JobSettings::new(crate::review::processes(), None), - fits: Box::new(move |name| crate::review_engine::name_fits(&path, name)), - pause: if std::env::var_os("CP_BRILLIANT_SLOW").is_some() { - std::time::Duration::from_millis(1500) - } else { - std::time::Duration::ZERO - }, - }; - let index = self.library.marks(&dialog.source); - // The list in the table's order: the analysed ones are taken first (at once). - let mut list = counted.reviewed.clone(); - list.extend(&counted.left); - self.brilliant_plies = counted - .left - .iter() - .copied() - .zip(counted.plies_left.iter().copied()) - .collect(); - let order: std::collections::HashMap = dialog - .records - .iter() - .enumerate() - .map(|(i, r)| (*r, i)) - .collect(); - list.sort_by_key(|r| order.get(r).copied().unwrap_or(usize::MAX)); - match crate::brilliant::PassJob::start( - ctx, - dialog.source.clone(), - db, - list, - dialog.filter.clone(), - dialog.selected, - index, - cache, - engine, - ) { - Ok(job) => { - self.library.set_pass_error(&dialog.source, None); - self.library.pass = Some(job); - self.brilliant_pass = Some(( - dialog.filter.clone(), - dialog.about.clone(), - dialog.selected, - counted.skipped, - )); - } - Err(e) => self.toast(ctx, e.to_string()), - } - } - - /// The summary of `records` of `source`. - #[allow(clippy::too_many_arguments)] - fn great_moves_summary( - &mut self, - source: &std::path::Path, - records: &[u32], - sides: &crate::brilliant::Sides, - filter: &chess_import::chessbase::base::Filter, - about: String, - selected: Option, - stopped: Option<(usize, usize)>, - skipped: Vec<(u32, crate::brilliant::Skip)>, - ) { - let Some(db) = self.library.database(source) else { - return; - }; - let index = self.library.marks(source); - let Ok(index) = index.lock() else { - return; - }; - self.brilliant_summary = Some(crate::brilliant_ui::Summary::new( - source, &db, &index, records, sides, filter, about, selected, stopped, skipped, - )); - } - - /// Every frame: the pass's state in the conditions lines, its end, the question and - /// the summary; and the engine taken by the pass for everything else. - fn great_moves_frame(&mut self, ctx: &egui::Context) { - let busy = self.engine_job_busy(); - self.library.set_engine_busy(busy); - let pass_busy = self.pass_busy(); - if let Some(p) = self.prep.as_mut() { - p.engine_blocked = pass_busy; - } - let plies = &self.brilliant_plies; - let estimate = |rest: &[u32]| { - crate::brilliant::estimate_secs( - rest.iter().filter_map(|r| plies.get(r).copied()), - crate::review::processes(), - ) - }; - self.library.show_pass(estimate); - // `CP_BRILLIANT_STOP_AFTER=`: «Stop» pressed that long after the start. - if let Some(ms) = std::env::var("CP_BRILLIANT_STOP_AFTER") - .ok() - .and_then(|ms| ms.parse::().ok()) - && let Some(job) = self.library.pass.as_mut() - && !job.stopping - && job.started.elapsed() >= std::time::Duration::from_millis(ms) - { - job.stop(); - } - if let Some(job) = self.library.pass.as_ref() - && let Some((end, sides)) = job.poll() - { - let job = self.library.pass.take().expect("pass"); - let (filter, about, selected, mut skipped) = - self.brilliant_pass.take().unwrap_or_default(); - skipped.extend(end.skipped.iter().copied()); - skipped.sort_unstable_by_key(|(r, _)| *r); - skipped.dedup(); - let reviewed = end.reviewed.len(); - let total = job.records.len(); - match &end.outcome { - crate::brilliant::Outcome::Finished => self.great_moves_summary( - &job.source, - &job.records, - &sides, - &filter, - about, - selected, - None, - skipped, - ), - crate::brilliant::Outcome::Stopped if reviewed == 0 => { - self.toast(ctx, tr("Search stopped: no game was reviewed")); - } - crate::brilliant::Outcome::Stopped => self.great_moves_summary( - &job.source, - &job.records, - &sides, - &filter, - about, - selected, - Some((reviewed, total)), - skipped, - ), - crate::brilliant::Outcome::EngineFailed(why) => { - let text = trf( - "The engine failed: {reason}. {i} of {n} reviewed", - &[("reason", why), ("i", &reviewed), ("n", &total)], - ); - self.library.set_pass_error(&job.source, Some(text)); - } - crate::brilliant::Outcome::SourceChanged => { - let text = trf( - "«{db}» changed; the search stopped. {i} of {n} reviewed", - &[ - ("db", &own_db::base_name(&job.source)), - ("i", &reviewed), - ("n", &total), - ], - ); - self.library.set_pass_error(&job.source, Some(text)); - } - } - } - if let Some(dialog) = self.brilliant_start.as_mut() - && let Some(outcome) = dialog.show(ctx) - { - let dialog = self.brilliant_start.take().expect("dialog"); - match outcome { - crate::brilliant_ui::StartOutcome::Cancel => {} - crate::brilliant_ui::StartOutcome::Start => self.start_great_moves(ctx, dialog), - crate::brilliant_ui::StartOutcome::Summary => { - if let Some(c) = &dialog.counted { - let reviewed = c.reviewed.clone(); - self.great_moves_summary( - &dialog.source, - &reviewed, - &c.sides, - &dialog.filter, - dialog.about.clone(), - dialog.selected, - None, - c.skipped.clone(), - ); - } - } - } - } - if self.game.is_none() - && let Some(summary) = self.brilliant_summary.as_mut() - && let Some(action) = summary.show(ctx) - { - let source = summary.source.clone(); - let summary_about = summary.about.clone(); - let summary_selected = summary.selected_games; - use crate::brilliant_ui::SummaryAction; - match action { - SummaryAction::Close => self.brilliant_summary = None, - SummaryAction::Select(record) => { - self.library.choose_only(&source, record as usize); - } - SummaryAction::Sort => self.library.sort_by_marks(&source), - SummaryAction::Continue { records, filter } => { - self.brilliant_summary = None; - let about = summary_about.clone(); - self.ask_great_moves(ctx, source, records, *filter, about, summary_selected); - } - SummaryAction::Open { record, ply } => { - self.brilliant_summary = None; - let at = self.library.database(&source).and_then(|db| { - let game = db.load_game(record as usize)?.game; - let node = *game.mainline().get(ply as usize)?; - Some(game.node(node)?.position().clone()) - }); - self.library.choose_only(&source, record as usize); - self.open_game(ctx, source, record as usize, at); - if let Some(g) = self.game.as_mut() { - g.show_report(); - } - } - } - } - } - - /// Starts the copy of the chosen records of the new-database dialog into `path` - /// (task 42): the file appears only when the copy is whole; the user stays in the - /// source database. - fn start_copy(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> { - let Some(own_db::AfterCreate::CopySelection { - path: from, - records, - sort, - ascending, - .. - }) = self.own.new_base.as_ref().map(|d| d.after.clone()) - else { - return Ok(()); - }; - if path.exists() { - return Err(tr("A file with this name is already there.").to_owned()); - } - if self - .library - .start_batch(ctx, &from, records, sort, ascending, path) - { - Ok(()) - } else { - Err(tr("Another copy is being written: wait until it finishes").to_owned()) - } - } - - /// The end of a copy of chosen records: a toast, and the new database on the shelf. - fn batch_ended(&mut self, ctx: &egui::Context, end: crate::library::BatchEnd) { - use crate::library::BatchEnd; - match end { - BatchEnd::Done { target, report } => { - let name = own_db::base_name(&target); - // At the end of the shelf: the cards stay where they are; «Open» brings it - // to the front. - self.settings.add_database_last(&target); - self.settings_dirty = true; - self.toast_for(ctx, crate::batch_copy::summary(&name, &report), 8.0); - self.toast_open_db = Some(target); - } - BatchEnd::Cancelled { target } => { - let name = own_db::base_name(&target); - self.toast( - ctx, - trf( - "Copying cancelled: «{name}» was not created", - &[("name", &name)], - ), - ); - } - BatchEnd::Failed { - source, - target, - error, - } => { - let text = match error { - crate::batch_copy::CopyError::SourceChanged => { - self.library.clear_selection(&source); - trf( - "«{src}» changed while copying. Nothing was written", - &[("src", &own_db::base_name(&source))], - ) - } - e => trf( - "Could not write «{name}»: {reason}. Nothing was written", - &[ - ("name", &own_db::base_name(&target)), - ("reason", &e.reason()), - ], - ), - }; - self.library.set_batch_error(&source, text.clone()); - self.toast_for(ctx, text, 8.0); - } - } - } - /// Makes the empty file and puts it on the shelf, selected and as the database the /// next game goes to. fn create_base(&mut self, ctx: &egui::Context, path: PathBuf) -> Result<(), String> { @@ -2510,10 +1528,6 @@ impl App { /// Goes on with the game put aside: its record on the screen, the opponent started /// again with its moves, the clocks where they stopped. fn resume_aside(&mut self, ctx: &egui::Context) { - if let Some(why) = engine_game_refused(self.pass_busy()) { - self.toast(ctx, why); - return; - } let Some(aside) = self.put_aside.as_ref() else { return; }; @@ -2531,7 +1545,7 @@ impl App { self.settings .active_engine() .and_then(|e| e.executable()) - .filter(|l| l.present()) + .filter(|p| p.is_file()) }); let Some(aside) = self.put_aside.take() else { return; @@ -2739,87 +1753,6 @@ impl App { self.game = Some(view); } - #[cfg(not(web))] - fn open_repertoire(&mut self, ctx: &egui::Context) { - if self.analysis.is_on() { - self.analysis.stop(); - self.live_paused = true; - } - if let Some(game) = self.game.as_mut() { - game.suspend(); - } - self.repertoire - .get_or_insert_with(crate::repertoire_ui::RepertoireUi::new) - .open_library(); - ctx.request_repaint(); - } - - #[cfg(not(web))] - fn open_repertoire_add(&mut self, ctx: &egui::Context, source: Game, at: chess_core::NodeId) { - self.open_repertoire(ctx); - if let Some(screen) = self.repertoire.as_mut() { - let title = self.game.as_ref().map(GameView::title).unwrap_or_default(); - screen.open_add_from_game(source, at, title); - } - } - - #[cfg(not(web))] - fn close_repertoire(&mut self, ctx: &egui::Context) { - self.repertoire = None; - if self.game.is_some() - && std::mem::take(&mut self.live_paused) - && let Some(config) = self.settings.active_engine().cloned() - { - self.analysis.start(&config, ctx); - } - } - - #[cfg(not(web))] - fn show_repertoire(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { - self.library.poll(); - let Some(mut screen) = self.repertoire.take() else { - return; - }; - let actions = screen.show(ui, &mut self.settings); - self.repertoire = Some(screen); - for action in actions { - match action { - crate::repertoire_ui::RepertoireAction::Close => self.close_repertoire(ctx), - crate::repertoire_ui::RepertoireAction::OpenSettings => { - self.settings_ui.open = true - } - crate::repertoire_ui::RepertoireAction::Sound(sound) => self.play(sound), - crate::repertoire_ui::RepertoireAction::Toast(message) => self.toast(ctx, message), - crate::repertoire_ui::RepertoireAction::SettingsChanged => { - self.settings_dirty = true - } - crate::repertoire_ui::RepertoireAction::Added { id, name, report } => { - let title = self.game.as_ref().map(GameView::title).unwrap_or_default(); - let text = if report.added_nodes == 0 && report.annotation_changes == 0 { - tr("Already in the repertoire — no changes").to_owned() - } else if report.added_nodes == 0 { - trf( - "The path was already in the repertoire; annotations added: {n}", - &[("n", &report.annotation_changes)], - ) - } else { - trf( - "Added to “{name}”: new moves: {added} · matched: {matched}", - &[ - ("name", &name), - ("added", &report.added_nodes), - ("matched", &report.merged_nodes.saturating_sub(1)), - ], - ) - }; - self.toast_for(ctx, text, 8.0); - self.toast_repertoire = Some((id, title)); - self.close_repertoire(ctx); - } - } - } - } - /// Learning the opening of the current game: the training opens over it. fn open_training(&mut self, start: crate::train::TrainStart) { let g = match start @@ -2839,12 +1772,6 @@ impl App { /// A new game against Maia. Her model missing (a rematch, a game from a position): /// the dialog with the same choices, to download it. fn start_play(&mut self, ctx: &egui::Context, start: crate::play::Start) { - // No game against the engine while the search for great moves runs (the owner's - // decision, task 27). - if let Some(why) = engine_game_refused(self.pass_busy()) { - self.toast(ctx, why); - return; - } let Some(maia) = crate::play::engine_for(&start) else { self.play_dialog = Some(crate::play::Dialog::for_start(&self.settings, &start)); return; @@ -2856,7 +1783,7 @@ impl App { self.settings .active_engine() .and_then(|e| e.executable()) - .filter(|l| l.present()) + .filter(|p| p.is_file()) }); match &start.from { Some(from) => self.game_from(from), @@ -2930,7 +1857,6 @@ impl App { self.own.editor = Some((editor, EditorThen::Done)); } - #[cfg(not(web))] fn pick_folder(&self, ctx: &egui::Context, start: PathBuf) { self.spawn_dialog(ctx, move || { let picked = rfd::FileDialog::new() @@ -2998,13 +1924,7 @@ impl App { self.settings.last_target = Some(dest.clone()); self.settings_dirty = true; self.library.select_db(&dest, ctx); - self.toast( - ctx, - trf( - "Copy made: {path}", - &[("path", &crate::platform::files::shown(&dest))], - ), - ); + self.toast(ctx, trf("Copy made: {path}", &[("path", &dest.display())])); } Err(e) => { self.toast(ctx, trf("Could not make the copy: {e}", &[("e", &e)])) @@ -3102,11 +2022,7 @@ impl App { } ChooserOutcome::SaveAsFile => { self.close_after_save = self.own.then_close.take(); - #[cfg(not(web))] self.pick_save(ctx); - // A file of its own in a browser: a download. - #[cfg(web)] - self.download_pgn(ctx); } ChooserOutcome::Cancel => { if let Some(intent) = self.own.then_close.take() { @@ -3120,13 +2036,9 @@ impl App { && let Some(outcome) = dialog.show(ctx) { match outcome { - // A browser has no folders: there are no new databases there. NewBaseOutcome::PickFolder => { - #[cfg(not(web))] - { - let start = dialog.dir.clone(); - self.pick_folder(ctx, start); - } + let start = dialog.dir.clone(); + self.pick_folder(ctx, start); } NewBaseOutcome::Cancel => { self.own.new_base = None; @@ -3140,13 +2052,7 @@ impl App { NewBaseOutcome::AddExisting(p) => (false, p), _ => unreachable!(), }; - let copy = matches!( - self.own.new_base.as_ref().map(|d| &d.after), - Some(own_db::AfterCreate::CopySelection { .. }) - ); - let made = if copy { - self.start_copy(ctx, path.clone()) - } else if create { + let made = if create { self.create_base(ctx, path.clone()) } else { self.settings.touch_database(&path); @@ -3178,8 +2084,6 @@ impl App { }; self.wait_for(ctx, &path, step) } - // Started by `start_copy`; its end is a toast. - own_db::AfterCreate::CopySelection { .. } => {} } } } @@ -3195,7 +2099,6 @@ impl App { } } - #[cfg(not(web))] fn spawn_dialog( &self, ctx: &egui::Context, @@ -3214,14 +2117,22 @@ impl App { } fn pick_databases(&self, ctx: &egui::Context) { - let (tx, ctx) = (self.tx.clone(), ctx.clone()); - crate::platform::files::pick_databases(move |picked| { - send_picked(&tx, picked, false); - ctx.request_repaint(); + self.spawn_dialog(ctx, || { + rfd::FileDialog::new() + .set_title(tr("Open database")) + .add_filter( + tr("Chess databases"), + &[ + "pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z", + ], + ) + .add_filter("PGN", &["pgn", "PGN"]) + .add_filter(tr("All files"), &["*"]) + .pick_files() + .map(Async::DatabasesPicked) }); } - #[cfg(not(web))] fn pick_save(&self, ctx: &egui::Context) { let Some(g) = &self.game else { return }; let name = sanitize(&g.title()) + ".pgn"; @@ -3235,7 +2146,6 @@ impl App { }); } - #[cfg(not(web))] fn pick_engine(&mut self, ctx: &egui::Context) { self.settings_ui.checking_engine = true; let tx = self.tx.clone(); @@ -3268,87 +2178,18 @@ impl App { } fn handle_async(&mut self, ctx: &egui::Context) { - self.pasted(ctx); while let Ok(msg) = self.rx.try_recv() { match msg { - #[cfg(web)] - Async::TooBig(files) => self.web_notice = Some(WebNotice::TooBig(files)), - #[cfg(web)] - Async::Incomplete(names) => { - if let Some(name) = names.into_iter().next() { - self.web_notice = Some(WebNotice::Incomplete(name)); - } - } - Async::EmptyFolder => { - self.toast( - ctx, - tr("There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z)."), - ); - } - Async::NotDatabases(names) => { - let files = names_text(&names); - self.toast( - ctx, - trf( - "Not a database: {files}. ChessPenguin opens .pgn, .cbh, .cbv, .zip and .7z files.", - &[("files", &files)], - ), - ); - } - #[cfg(web)] - Async::CopyKept(path, kept) => self.copy_kept(ctx, path, kept), - Async::Missing(names) => { - let files = names_text(&names); - self.toast(ctx, trf("Not found: {files}", &[("files", &files)])); - } - Async::DatabasesDropped(paths) => { - // As «Add database»; the game on the screen stays, so it is told. - // The first one ends up first on the shelf (as the shelf has it: a - // link to a database there is that database). - let mut first = None; - for p in paths.iter().rev() { - first = Some(self.settings.touch_database(p)); - } - if let Some(first) = first { - self.library.select_db(&first, ctx); - } - self.settings_dirty = true; - if self.game.is_some() { - let names: Vec = - paths.iter().map(|p| own_db::base_name(p)).collect(); - let files = names_text(&names); - self.toast( - ctx, - trf("Added to the shelf: {files}", &[("files", &files)]), - ); - } - } Async::DatabasesPicked(paths) => { - // The file chosen again takes the place of the one gone (a cancelled - // dialog ends «Choose again» too). - let old = self.choosing_again.take(); - if paths.is_empty() { - continue; - } - if let Some(old) = old { - self.settings.databases.retain(|d| *d != old); - self.library.forget(&old); - crate::platform::files::forget(&old); - } - // The first one ends up first on the shelf (as the shelf has it: a - // link to a database there is that database). - let mut first = None; for p in paths.iter().rev() { - first = Some(self.settings.touch_database(p)); + self.settings.touch_database(p); } - if let Some(first) = first { - self.library.select_db(&first, ctx); + if let Some(first) = paths.first() { + self.library.select_db(first, ctx); } self.settings_dirty = true; } Async::SavePicked(path) => self.save_game(ctx, path), - #[cfg(web)] - Async::ReadAllowed(path) => self.library.reload(&path, ctx), Async::SaveCancelled => { self.close_after_save = None; self.restart_to = None; @@ -3410,13 +2251,7 @@ impl App { match chess_core::pgn::store::write_atomic(&path, pgn.as_bytes()) { Ok(()) => { g.game.mark_saved(); - self.toast( - ctx, - trf( - "Saved: {path}", - &[("path", &crate::platform::files::shown(&path))], - ), - ); + self.toast(ctx, trf("Saved: {path}", &[("path", &path.display())])); if let Some(intent) = self.close_after_save.take() { self.finish_close(ctx, intent); } @@ -3516,9 +2351,6 @@ impl App { return; } self.previous_games.clear(); - if let Some(p) = self.prep.as_mut() { - p.shown = false; - } if let Some(g) = closed && let Some(src) = g.source { @@ -3569,20 +2401,6 @@ impl App { fn toggle_engine(&mut self, ctx: &egui::Context) { self.live_paused = false; - // The search for great moves has the engine (task 27 §4.5). - if !self.analysis.is_on() - && let Some(why) = self.pass_busy() - { - self.toast(ctx, why); - return; - } - if self.prep.as_ref().is_some_and(|p| p.running()) && !self.analysis.is_on() { - self.toast( - ctx, - tr("Opening errors are being searched — wait or stop it in the report"), - ); - return; - } if self.analysis.is_on() { self.analysis.stop(); return; @@ -3598,9 +2416,7 @@ impl App { } /// Makes ChessPenguin's Stockfish (just downloaded) or a found engine the active - /// one, then runs what the user was doing. The game analysis and the opening errors - /// use ChessPenguin's Stockfish whatever the active engine: downloaded for them, it - /// becomes the active one only when there was none. + /// one, then runs what the user was doing. fn engine_arrived( &mut self, ctx: &egui::Context, @@ -3614,98 +2430,17 @@ impl App { self.settings.engines.push(cfg); self.settings.engines.len() - 1 }); - let own_search = matches!( - pending, - Some( - crate::engine_offer::Pending::GameAnalysis { .. } - | crate::engine_offer::Pending::OpeningErrors { .. } - | crate::engine_offer::Pending::GreatMoves - ) - ); - if !own_search || self.settings.active_engine().is_none() { - self.settings.active_engine = Some(index); - } + self.settings.active_engine = Some(index); self.settings_dirty = true; - self.run_engine_pending(ctx, pending); - } - - /// The game analysis or the opening errors found no engine to search with: a - /// Stockfish 19 of the user's that searches as ours is taken (probed first, in the - /// background: the action waits for it, on its own game or preparation), else ours - /// is offered for download, saying why the user's engine does not do. - fn need_review_engine(&mut self, ctx: &egui::Context, pending: crate::engine_offer::Pending) { - crate::review_engine::set_candidates(&self.settings); - let waited = !self.review_wait.is_empty(); - // One wait per kind: the newer request of a kind takes its place, the other - // kind keeps its own. - let same_kind = |p: &crate::engine_offer::Pending| { - std::mem::discriminant(p) == std::mem::discriminant(&pending) - }; - self.review_wait.retain(|p| !same_kind(p)); - self.review_wait.push(pending); - // Said only when an engine is really being checked (not when the answer is - // known already: then it starts, or the offer says why not). - if self.poll_review_wait(ctx) && !waited { - self.toast( - ctx, - tr("Checking whether your engine can run the analysis…"), - ); - } - } - - /// The actions waiting for an engine of the user's to be probed: dropped when their - /// game or preparation is no longer there; when the probe is done, started, or the - /// download of ours is offered for the latest of them. - /// Returns whether they still wait. - fn poll_review_wait(&mut self, ctx: &egui::Context) -> bool { - use crate::review_engine::Lookup; - let (game, prep) = ( - self.game.as_ref().map(|g| g.serial), - self.prep.as_ref().map(|p| p.serial), - ); - self.review_wait.retain(|p| still_waiting(p, game, prep)); - if self.review_wait.is_empty() { - return false; - } - match crate::review_engine::lookup(ctx) { - Lookup::Checking => return true, - Lookup::Ready(_) => { - for p in std::mem::take(&mut self.review_wait) { - self.run_engine_pending(ctx, Some(p)); - } - } - Lookup::Unfit(unfit) => { - let waiting = std::mem::take(&mut self.review_wait); - if let Some(p) = waiting.last() { - self.engine_offer.ask_instead_of(*p, unfit); - } - } - Lookup::None => { - let waiting = std::mem::take(&mut self.review_wait); - if let Some(p) = waiting.last() { - self.engine_offer.ask(*p, &self.settings); - } - } - } - false - } - - /// Runs what the user was doing when an engine had to be found first: on the game - /// or the preparation it was asked on, if it is still there. - fn run_engine_pending( - &mut self, - ctx: &egui::Context, - pending: Option, - ) { match pending { Some(crate::engine_offer::Pending::LiveAnalysis) => { if !self.analysis.is_on() { self.toggle_engine(ctx); } } - Some(crate::engine_offer::Pending::GameAnalysis { game, full }) => { - let actions = match self.game.as_mut().filter(|g| g.serial == game) { - Some(g) => g.start_review_now(ctx, full), + Some(crate::engine_offer::Pending::GameAnalysis) => { + let actions = match self.game.as_mut() { + Some(g) => g.start_review_now(&self.settings, ctx), None => Vec::new(), }; for a in actions { @@ -3719,18 +2454,6 @@ impl App { } } } - Some(crate::engine_offer::Pending::GreatMoves) => { - if let Some(dialog) = self.brilliant_waiting.take() { - self.start_great_moves(ctx, dialog); - } - } - Some(crate::engine_offer::Pending::OpeningErrors { prep }) => { - let actions = match self.prep.as_mut().filter(|p| p.serial == prep) { - Some(p) => p.start_after_engine(ctx), - None => Vec::new(), - }; - self.prep_actions(ctx, actions); - } None => {} } } @@ -3745,295 +2468,16 @@ impl App { let cfg = crate::settings::EngineConfig::new("Stockfish".into(), path); self.engine_arrived(ctx, cfg, pending) } - #[cfg(not(web))] crate::engine_offer::OfferEvent::ChooseFile => self.pick_engine(ctx), crate::engine_offer::OfferEvent::Toast(m) => self.toast(ctx, m), } } } - /// The page's side of the frame: the game on the screen as an entry of the browser's - /// history, the browser's question on leaving with unsaved work, the draft of an - /// unsaved game. Nothing of it on a computer. - fn page_frame(&mut self, ctx: &egui::Context) { - crate::platform::page::game_shown(ctx, self.game.is_some()); - let modified = self.game.as_ref().is_some_and(|g| g.game.is_modified()); - let reviewing = self.game.as_ref().is_some_and(|g| g.review_running()); - crate::platform::page::warn_on_leave(modified || reviewing); - #[cfg(web)] - { - const EVERY: f64 = 5.0; - let now = ctx.input(|i| i.time); - match self.game.as_ref().filter(|g| g.game.is_modified()) { - Some(g) if self.draft_at.is_none_or(|t| now - t >= EVERY) => { - crate::my_games::write_draft(&crate::my_games::Draft { - title: g.title(), - moves: g.game.mainline().len().div_ceil(2), - pgn: g.game.to_pgn(), - }); - self.draft_at = Some(now); - ctx.request_repaint_after(std::time::Duration::from_secs_f64(EVERY)); - } - Some(_) => {} - // Saved, or left without saving: no draft of this visit is kept. - None if self.draft_at.take().is_some() => crate::my_games::delete_draft(), - None => {} - } - } - } - - /// «There is an unsaved game» over the library, with Open and Delete. - #[cfg(web)] - fn draft_strip(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) { - let Some(d) = self.draft_offer.clone() else { - return; - }; - let mut open = false; - let mut delete = false; - egui::Frame::new() - .inner_margin(egui::Margin::symmetric(8, 6)) - .fill(ui.visuals().faint_bg_color) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.label( - RichText::new(trf( - "There is an unsaved game: {title}, moves: {n}.", - &[("title", &d.title), ("n", &d.moves)], - )) - .color(ui.visuals().warn_fg_color), - ); - open = ui.button(tr("Open")).clicked(); - delete = ui.button(tr("Delete")).clicked(); - }); - }); - if open { - self.draft_offer = None; - self.open_pgn_text(ctx, d.pgn, false); - crate::my_games::delete_draft(); - } else if delete { - self.draft_offer = None; - crate::my_games::delete_draft(); - } - } - - /// Files dropped on the window open as databases, like chosen ones; while files are - /// dragged over it, the window says so. - fn dropped_files(&mut self, ctx: &egui::Context) { - let (tx, waker) = (self.tx.clone(), ctx.clone()); - crate::platform::files::take_dropped(ctx, move |picked| { - send_picked(&tx, picked, true); - waker.request_repaint(); - }); - if crate::platform::files::dragging(ctx) { - let rect = ctx.content_rect(); - let painter = ctx.layer_painter(egui::LayerId::new( - egui::Order::Foreground, - egui::Id::new("dropping files"), - )); - // The window tinted and framed in the accent colour; the words on a card of - // the window's own background, readable in both themes. - let visuals = ctx.global_style().visuals.clone(); - let accent = visuals.selection.bg_fill; - painter.rect_filled(rect, 0.0, accent.gamma_multiply(0.28)); - painter.rect_stroke( - rect.shrink(2.0), - 6.0, - egui::Stroke::new(4.0, accent), - egui::StrokeKind::Inside, - ); - let galley = painter.layout_no_wrap( - tr("Release to open").to_owned(), - egui::FontId::proportional(22.0), - visuals.strong_text_color(), - ); - let card = - egui::Rect::from_center_size(rect.center(), galley.size() + egui::vec2(48.0, 32.0)); - painter.rect( - card, - 10.0, - visuals.window_fill, - egui::Stroke::new(2.0, accent), - egui::StrokeKind::Inside, - ); - painter.galley( - card.center() - galley.size() / 2.0, - galley, - visuals.strong_text_color(), - ); - } - } - - /// A copy of a file of this visit kept in the browser: it takes the file's place on - /// the shelf. Only a browser has such files. - fn keep_copy(&mut self, ctx: &egui::Context, path: PathBuf) { - #[cfg(web)] - { - let (tx, wake) = (self.tx.clone(), ctx.clone()); - crate::platform::files::keep_copy(&path.clone(), move |kept| { - let _ = tx.send(Async::CopyKept(path, kept)); - wake.request_repaint(); - }); - } - #[cfg(not(web))] - let _ = (ctx, path); - } - - /// The copy of `path` is kept (or not): it takes the file's place on the shelf. - #[cfg(web)] - fn copy_kept( - &mut self, - ctx: &egui::Context, - path: PathBuf, - kept: Result, - ) { - { - use crate::platform::files::KeepCopy; - use crate::platform::size_text; - match kept { - Ok(copy) => { - for d in self.settings.databases.iter_mut().filter(|d| **d == path) { - *d = copy.clone(); - } - self.library.forget(&path); - crate::platform::files::forget(&path); - self.library.select_db(©, ctx); - self.settings_dirty = true; - let ctx2 = ctx.clone(); - crate::platform::web::storage::refresh(move || ctx2.request_repaint()); - if crate::platform::web::storage::persisted() != Some(true) { - crate::platform::web::storage::persist(|_| {}); - } - self.toast(ctx, tr("A copy is kept in the browser")); - } - Err(KeepCopy::NoRoom { need, free }) => self.toast_for( - ctx, - trf( - "Doesn't fit: the copy needs {need}, and the browser gives the site only {free} more. Free up space in “Browser data” or open the file from disk.", - &[("need", &size_text(need)), ("free", &size_text(free))], - ), - 8.0, - ), - Err(KeepCopy::Failed(e)) => self.toast(ctx, e), - } - } - } - - /// The window of [`WebNotice`]: a database too big for a browser (with the way to - /// the program for the computer), or a ChessBase database's other files to choose. - #[cfg(web)] - fn web_notice(&mut self, ctx: &egui::Context) { - let Some(notice) = &self.web_notice else { - return; - }; - let mut close = false; - let mut folder = false; - let mut files = false; - let modal = egui::Modal::new(egui::Id::new("web_notice")).show(ctx, |ui| { - ui.set_width(460.0); - match notice { - WebNotice::TooBig(dbs) => { - for (name, size) in dbs { - ui.label(RichText::new(name.as_str()).strong()); - ui.label(trf( - "This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.", - &[ - ("size", &crate::platform::size_text(*size)), - ("limit", &crate::platform::size_text(crate::platform::files::TOO_BIG)), - ], - )); - } - ui.add_space(6.0); - let lang = match crate::i18n::current() { - crate::i18n::Lang::En => "", - crate::i18n::Lang::Ru => "ru/", - crate::i18n::Lang::Fr => "fr/", - crate::i18n::Lang::De => "de/", - crate::i18n::Lang::Es => "es/", - crate::i18n::Lang::It => "it/", - crate::i18n::Lang::Pt => "pt/", - crate::i18n::Lang::Uz => "uz/", - crate::i18n::Lang::Kk => "kk/", - }; - ui.hyperlink_to( - tr("Download ChessPenguin for the computer"), - format!("/{lang}#download"), - ); - ui.add_space(8.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - close = ui.button(tr("Close")).clicked(); - }); - } - WebNotice::Incomplete(name) => { - ui.label(RichText::new(name.as_str()).strong()); - ui.label(tr( - "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", - )); - ui.add_space(4.0); - ui.label( - RichText::new(if crate::platform::files::remembers_chosen() { - tr("Allow access to the database's folder — its other files will be found by themselves.") - } else { - tr("Choose the database's folder — its other files will be found by themselves.") - }) - .weak(), - ); - ui.add_space(8.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - folder = ui.button(tr("📁 Choose the database's folder")).clicked(); - files = ui.button(tr("Choose the database's files")).clicked(); - close = ui.button(tr("Cancel")).clicked(); - }); - } - } - }); - if close || modal.should_close() { - self.web_notice = None; - } - if folder { - self.web_notice = None; - self.pick_database_folder(ctx); - } - if files { - self.web_notice = None; - self.pick_databases(ctx); - } - } - - #[cfg(web)] - fn pick_database_folder(&self, ctx: &egui::Context) { - let (tx, ctx) = (self.tx.clone(), ctx.clone()); - crate::platform::files::pick_database_folder(move |picked| { - send_picked(&tx, picked, false); - ctx.request_repaint(); - }); - } - - /// The open game's PGN, downloaded as a file named after the game. - #[cfg(web)] - fn download_pgn(&mut self, ctx: &egui::Context) { - let Some(g) = &self.game else { return }; - let name = sanitize(&g.title()) + ".pgn"; - if let Err(e) = crate::platform::files::download_pgn(&name, &g.game.to_pgn()) { - self.toast( - ctx, - trf("The PGN could not be downloaded: {e}", &[("e", &e)]), - ); - } - } - fn paste_pgn(&mut self, ctx: &egui::Context) { - self.pasting = Some(crate::platform::clipboard::read_text(ctx)); - } - - /// The clipboard read for «Paste PGN», once it is there. - fn pasted(&mut self, ctx: &egui::Context) { - let Some(text) = self.pasting.as_ref().and_then(|r| r.poll()) else { - return; - }; - self.pasting = None; + let text = arboard::Clipboard::new().and_then(|mut c| c.get_text()); match text { - Some(t) if !t.trim().is_empty() => self.open_pgn_text(ctx, t, false), + Ok(t) if !t.trim().is_empty() => self.open_pgn_text(ctx, t, false), _ => self.toast(ctx, tr("The clipboard is empty or unavailable")), } } @@ -4173,129 +2617,12 @@ impl App { _ => {} } } - - /// Online games and updates, each frame (the desktop program's). - #[cfg(not(web))] - fn desktop_frame(&mut self, ctx: &egui::Context) { - // Back to the window after a while: the downloaded databases get the games - // played since (at the start they did already). - let now = ctx.input(|i| i.time); - let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); - if focused - && !self.desktop.was_focused - && now - self.desktop.online_updated_at > ONLINE_EVERY - { - self.desktop.online_updated_at = now; - self.desktop.online.update_quietly( - self.settings - .databases - .iter() - .filter(|p| crate::online::is_online(p)) - .cloned(), - ); - } - self.desktop.was_focused = focused; - let events = self - .desktop - .online - .show(ctx, &mut self.desktop.online_probe); - for e in events { - match e { - crate::online_ui::OnlineEvent::Added(p) => { - let known = self.settings.databases.contains(&p); - self.settings.touch_database(&p); - if known { - self.library.reload(&p, ctx); - } - self.library.select_db(&p, ctx); - self.settings_dirty = true; - } - crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, ctx), - crate::online_ui::OnlineEvent::Open(p) => { - self.settings.touch_database(&p); - self.library.select_db(&p, ctx); - self.settings_dirty = true; - } - crate::online_ui::OnlineEvent::Message(t) => self.toast(ctx, t), - } - } - // Updates: the badge next to Settings, the window, the status in Settings → About. - self.desktop.update_check.poll(); - let skipped = self.settings.skipped_version.clone(); - let badge = self - .desktop - .update_check - .newer() - .filter(|r| { - self.desktop.update_ui.active() || skipped.as_deref() != Some(r.version.as_str()) - }) - .map(|r| self.desktop.update_ui.badge(r)); - self.library.update = badge.clone(); - if let Some(g) = &mut self.game { - g.update = badge; - } - for e in self.desktop.update_ui.show( - ctx, - self.desktop.update_check.newer(), - &self.desktop.update_kind, - ) { - match e { - crate::update_ui::UpdateEvent::Restart(exe) => { - self.restart_to = Some(exe); - self.request_close(ctx, CloseIntent::QuitApp); - } - crate::update_ui::UpdateEvent::CopyText(t) => { - ctx.copy_text(t); - self.toast(ctx, tr("Copied")); - } - crate::update_ui::UpdateEvent::Quit => { - self.request_close(ctx, CloseIntent::QuitApp); - } - crate::update_ui::UpdateEvent::Skip(v) => { - self.settings.skipped_version = Some(v); - self.settings_dirty = true; - } - } - } - self.settings_ui.update_available = - self.desktop.update_check.newer().map(|r| r.version.clone()); - self.settings_ui.update_status = if self.desktop.update_check.running() { - Some(tr("Checking…").to_owned()) - } else if let Some(r) = self.desktop.update_check.newer() { - Some(trf("Version {v} is out", &[("v", &r.version)])) - } else if self.desktop.update_check.release.is_some() { - Some(tr("This is the latest version").to_owned()) - } else if self.desktop.update_check.error.is_some() { - Some(tr("Could not check for updates").to_owned()) - } else { - None - }; - } } impl eframe::App for App { - #[cfg(all(debug_assertions, not(web)))] - fn raw_input_hook(&mut self, ctx: &egui::Context, input: &mut egui::RawInput) { - if self.settings_ui.open - && ctx.input(|i| i.time) >= 3.0 - && let Some(pos) = self.debug.settings_click.take() - { - input.events.push(egui::Event::PointerMoved(pos)); - for pressed in [true, false] { - input.events.push(egui::Event::PointerButton { - pos, - button: egui::PointerButton::Primary, - pressed, - modifiers: Modifiers::NONE, - }); - } - } - } - fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { crate::san::set(self.settings.move_notation); // The window has shown its first frame: this graphics mode works. - #[cfg(not(web))] if ui.ctx().cumulative_frame_nr() >= 1 { crate::graphics::started(); } @@ -4308,50 +2635,9 @@ impl eframe::App for App { }); self.applied_dark = Some(self.settings.dark_mode); } - // The opening panel's dragged width: given to the panel, saved when dragged anew. - #[cfg(not(web))] - let side_width = egui::Id::new(crate::opening_layout::SIDE_WIDTH_ID); - #[cfg(not(web))] - match ctx.data(|d| d.get_temp::(side_width)) { - None => { - if let Some(width) = self.settings.opening_side_width { - ctx.data_mut(|d| d.insert_temp(side_width, width)); - } - } - Some(width) if self.settings.opening_side_width != Some(width) => { - self.settings.opening_side_width = Some(width); - let _ = self.settings.save(); - } - Some(_) => {} - } - // Quitting while the opening errors are searched: asked first (what was found - // is kept either way). - if ctx.input(|i| i.viewport().close_requested()) - && !self.allow_quit - && !self.prep_quit_ok - && self.prep.as_ref().is_some_and(|p| p.running()) - { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - self.prep_quit_ask = true; - } - #[cfg(not(web))] - if ctx.input(|i| i.viewport().close_requested()) - && !self.allow_quit - && self - .repertoire - .as_ref() - .is_some_and(|screen| screen.has_unsaved()) - { - ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); - if let Some(screen) = self.repertoire.as_mut() { - screen.resolve_unsaved(); - } - } - let quitting = !self.prep_quit_ask; // Quitting: a comment being written goes into the game first, so the question // about unsaved changes counts it. - if quitting - && ctx.input(|i| i.viewport().close_requested()) + if ctx.input(|i| i.viewport().close_requested()) && !self.allow_quit && let Some(g) = self.game.as_mut() { @@ -4370,8 +2656,7 @@ impl eframe::App for App { } // Quitting with a modified game left for another (reference tab): show that one, // so the question "save?" is about the game that has the changes. - if quitting - && ctx.input(|i| i.viewport().close_requested()) + if ctx.input(|i| i.viewport().close_requested()) && !self.allow_quit && !self.game.as_ref().is_some_and(|g| g.game.is_modified()) && let Some(k) = self @@ -4383,8 +2668,7 @@ impl eframe::App for App { self.game = self.previous_games.pop(); } // (A game against Maia in progress has asked «The game is on» instead.) - if quitting - && ctx.input(|i| i.viewport().close_requested()) + if ctx.input(|i| i.viewport().close_requested()) && !self.allow_quit && self .game @@ -4394,12 +2678,7 @@ impl eframe::App for App { ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose); self.confirm_close = Some(CloseIntent::QuitApp); } - self.dropped_files(&ctx); self.handle_async(&ctx); - // The browser's «Back» in a game: «← Library». - if crate::platform::page::take_back() && self.game.is_some() { - self.request_close(&ctx, CloseIntent::BackToLibrary); - } // Dev hook (screenshots): the engine offer as on pressing L without an engine. if std::env::var("CP_ENGINE_OFFER").is_ok() && !self.offer_hook_done { self.offer_hook_done = true; @@ -4409,24 +2688,14 @@ impl eframe::App for App { self.engine_offer.start(&ctx); } } - if !self.review_wait.is_empty() { - let _ = self.poll_review_wait(&ctx); - } self.offer_events(&ctx); - self.page_frame(&ctx); - #[cfg(web)] - self.web_notice(&ctx); self.debug_step(&ctx); self.debug_keys(&ctx); self.debug_screenshot(&ctx); self.analysis.poll(); let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); - #[cfg(not(web))] - let repertoire_visible = self.repertoire.is_some(); - #[cfg(web)] - let repertoire_visible = false; - if !repertoire_visible && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) { + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::O))) { self.pick_databases(&ctx); } if ctx.input_mut(|i| { @@ -4435,31 +2704,16 @@ impl eframe::App for App { Key::N, )) }) && self.game.is_none() - && !repertoire_visible - && crate::platform::CAPS.own_databases { self.own.then_close = None; self.new_base_dialog(own_db::AfterCreate::Shelf); } // In the library a game from the start; on a game's screen the game plays on // from its position (the game view takes Ctrl+G there). - if self.game.is_none() - && !repertoire_visible - && crate::platform::CAPS.play - && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) - { + if self.game.is_none() && ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::G))) { self.play_new(&ctx, PlayNext::Dialog(None)); } - // A browser keeps Ctrl+N for its window: N in the library there (design §4). - let new_game_key = cfg!(web) - && self.game.is_none() - && !repertoire_visible - && !ctx.egui_wants_keyboard_input() - && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::N)); - if (new_game_key || ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N)))) - && self.game.is_none() - && !repertoire_visible - { + if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::N))) && self.game.is_none() { self.new_game(); } if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Comma))) { @@ -4469,24 +2723,28 @@ impl eframe::App for App { // A new game's target base that left the shelf or stopped taking games is // dropped before the game is drawn (its header names the target). let _ = self.current_target(); - let shelf = self.shelf_dbs(); - let pass_busy = self.pass_busy(); - if repertoire_visible { - #[cfg(not(web))] - self.show_repertoire(ui, &ctx); - } else if let Some(game) = &mut self.game { + if let Some(game) = &mut self.game { let input_enabled = self.confirm_close.is_none(); // A database opened for the reference tab arrives here (the library is // not drawn while a game is shown). self.library.poll(); - self.reference.dbs = shelf; - // The preparation's engine goes on under the game; no game analysis meanwhile. - game.engine_busy = - self.prep.as_ref().is_some_and(|p| p.running()) || self.library.pass.is_some(); - game.engine_busy_why = pass_busy.clone(); - if let Some(p) = self.prep.as_mut() { - p.poll_quietly(&ctx, &self.settings); - } + self.reference.dbs = self + .settings + .databases + .iter() + .filter(|p| self.library.files.exists(p)) + .map(|p| crate::reference::RefDb { + path: p.clone(), + name: p + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(), + db: self.library.database(p), + failed: self.library.failure(p).map(str::to_owned), + bytes: self.library.file_size(p), + }) + .collect(); + let review = self.settings.review.clone(); let actions = game.show( ui, &mut self.settings, @@ -4495,8 +2753,9 @@ impl eframe::App for App { &mut self.translation, input_enabled, ); + // The analysis options (its dialog) are kept. + self.settings_dirty |= self.settings.review != review; self.reference_tab = game.reference_tab(); - let game_back_previous = game.previous_prep && game.previous.is_some(); // Before the actions: leaving may take the game away. if let Some(res) = game.record_news.take() { let name = game.player_name(); @@ -4505,16 +2764,6 @@ impl eframe::App for App { for a in actions { match a { GameAction::Back => self.request_close(&ctx, CloseIntent::BackToLibrary), - GameAction::BackKey => { - // Ctrl+W: back where the game was opened from (the report, a - // game), else to the library. - let intent = if game_back_previous { - CloseIntent::ReturnToPrevious - } else { - CloseIntent::BackToLibrary - }; - self.request_close(&ctx, intent); - } // The game's database in the library, the game's row shown (its row is // revealed as the game closes). GameAction::OpenDatabase(path) => { @@ -4543,23 +2792,15 @@ impl eframe::App for App { } } } - #[cfg(not(web))] - GameAction::OpenUpdate => self.desktop.update_ui.open = true, - #[cfg(web)] - GameAction::DownloadPgn => self.download_pgn(&ctx), + GameAction::OpenUpdate => self.update_ui.open = true, GameAction::ReturnToPrevious => { - if !self.previous_games.is_empty() - || self.prep.as_ref().is_some_and(|p| p.shown) - { + if !self.previous_games.is_empty() { self.request_close(&ctx, CloseIntent::ReturnToPrevious); } } - GameAction::NeedEngine { full } => { - if let Some(game) = self.game.as_ref().map(|g| g.serial) { - let pending = crate::engine_offer::Pending::GameAnalysis { game, full }; - self.need_review_engine(&ctx, pending); - } - } + GameAction::NeedEngine => self + .engine_offer + .ask(crate::engine_offer::Pending::GameAnalysis, &self.settings), GameAction::Sound(s) => self.play(s), GameAction::CopyText(text, msg) => { ctx.copy_text(text); @@ -4614,10 +2855,7 @@ impl eframe::App for App { self.play_next = Some(PlayNext::Dialog(from)); self.request_close(&ctx, intent); } - #[cfg(not(web))] - GameAction::AddToRepertoire(game, at) => { - self.open_repertoire_add(&ctx, *game, at) - } + GameAction::Train(start) => self.open_training(*start), GameAction::PlayFrom(from) => self.play_new(&ctx, PlayNext::Dialog(Some(from))), GameAction::PutAside(intent) => { let intent = intent.unwrap_or( @@ -4670,16 +2908,6 @@ impl eframe::App for App { self.settings_ui.tab = Tab::Translation; } GameAction::Toast(m) => self.toast(&ctx, m), - GameAction::Reviewed { path, index, entry } => { - let marks = self.library.marks(&path); - if let Ok(mut marks) = marks.lock() { - marks.set(index as u32, entry); - if let Err(e) = marks.save() { - eprintln!("marks: {e}"); - } - } - } - GameAction::HintsChanged => self.settings_dirty = true, GameAction::PauseLive => { if self.analysis.is_on() { self.analysis.stop(); @@ -4695,50 +2923,17 @@ impl eframe::App for App { } } } - } else if self.prep.as_ref().is_some_and(|p| p.shown) { - self.library.poll(); - let actions = match self.prep.as_mut() { - Some(p) => p.show(ui, &mut self.settings), - None => Vec::new(), - }; - self.prep_actions(&ctx, actions); } else { let dbs = self.settings.databases.clone(); - if let Some(p) = self.prep.as_mut() { - p.poll_quietly(&ctx, &self.settings); - } - // Ctrl+Shift+P: «Prepare against…» with the player of the filter. - if ctx.input_mut(|i| { - i.consume_shortcut(&KeyboardShortcut::new( - Modifiers::COMMAND | Modifiers::SHIFT, - Key::P, - )) - }) && self.prep_dialog.is_none() - && let Some((path, entry)) = self.library.prep_entry() - { - self.prep_dialog = Some(PrepDialog::new(path, entry.unwrap_or_default())); - } - #[cfg(not(web))] - { - let d = &mut self.desktop; - d.online_probe.poll(); - self.library.online = d.online_probe.any(); - self.library.online_busy = d.online.busy(); - self.library.online_running = d.online.running(); - } - #[cfg(web)] - self.draft_strip(ui, &ctx); + self.online_probe.poll(); + self.library.online = self.online_probe.any(); + self.library.online_busy = self.online.busy(); + self.library.online_running = self.online.running(); for a in self.library.show(ui, &dbs, &self.settings) { match a { LibraryAction::OpenGame { path, index, at } => { self.open_game(&ctx, path, index, at) } - LibraryAction::OpenGameReport { path, index, at } => { - self.open_game(&ctx, path, index, at); - if let Some(g) = self.game.as_mut() { - g.show_report(); - } - } LibraryAction::Sound(s) => self.play(s), LibraryAction::CopyText(text, msg) => { ctx.copy_text(text); @@ -4763,47 +2958,23 @@ impl eframe::App for App { } LibraryAction::PastePgn => self.paste_pgn(&ctx), LibraryAction::AddDatabases => self.pick_databases(&ctx), - #[cfg(not(web))] - LibraryAction::OnlineGames => self.desktop.online.open(), - #[cfg(not(web))] - LibraryAction::UpdateOnline(p) => self.desktop.online.update(&p, &ctx), - #[cfg(not(web))] - LibraryAction::OpenUpdate => self.desktop.update_ui.open = true, + LibraryAction::OnlineGames => self.online.open(), + LibraryAction::UpdateOnline(p) => self.online.update(&p, &ctx), + LibraryAction::OpenUpdate => self.update_ui.open = true, LibraryAction::RemoveDatabase(p) => { self.settings.databases.retain(|d| *d != p); self.library.forget(&p); - crate::platform::files::forget(&p); self.settings_dirty = true; // The file stays where it is; said so, with the place. self.toast = Some(Toast { text: trf( "Removed from the shelf; the file stays: {path}", - &[("path", &crate::platform::files::shown(&p))], + &[("path", &p.display())], ), until: ctx.input(|i| i.time) + 6.0, undo: false, }); } - #[cfg(web)] - LibraryAction::AllowReading(p) => { - let (tx, wake) = (self.tx.clone(), ctx.clone()); - crate::platform::files::allow_reading(&p.clone(), move |back| { - if back { - let _ = tx.send(Async::ReadAllowed(p)); - } - wake.request_repaint(); - }); - } - LibraryAction::ChooseAgain(p) => { - self.choosing_again = Some(p); - self.pick_databases(&ctx); - } - #[cfg(web)] - LibraryAction::ChooseFolderAgain(p) => { - self.choosing_again = Some(p); - self.pick_database_folder(&ctx); - } - LibraryAction::KeepCopy(p) => self.keep_copy(&ctx, p), LibraryAction::OpenSettings => self.settings_ui.open = true, LibraryAction::NewDatabase => { self.own.then_close = None; @@ -4817,65 +2988,96 @@ impl eframe::App for App { self.own.then_close = None; self.open_chooser(&ctx, ChooserFor::Record { path, index }); } - LibraryAction::CopySelection { - path, - records, - sort, - ascending, - hidden, - } => { - self.own.then_close = None; - self.new_base_dialog(own_db::AfterCreate::CopySelection { - path, - records, - sort, - ascending, - hidden, - }); - // `CP_BATCH=new:`: the dialog answered at once. - if let Some(name) = std::env::var("CP_BATCH") - .ok() - .and_then(|b| b.strip_prefix("new:").map(str::to_owned)) - && let Some(d) = self.own.new_base.as_mut() - { - d.name = name; - let target = d.path(); - match self.start_copy(&ctx, target) { - Ok(()) => self.own.new_base = None, - Err(e) => { - if let Some(d) = self.own.new_base.as_mut() { - d.error = Some(e); - } - } - } - } - } - LibraryAction::Notice(text) => self.toast(&ctx, text), - LibraryAction::FindGreatMoves { - path, - records, - filter, - about, - selected, - } => self.ask_great_moves(&ctx, path, records, filter, about, selected), LibraryAction::EditGameData { path, index } => { self.open_game(&ctx, path, index, None); self.edit_game_data(); } - LibraryAction::PrepareAgainst { path, entry } => { - self.prep_dialog = Some(PrepDialog::new(path, entry)); - } - LibraryAction::Preparations => { - self.prep_list = Some(crate::prep_ui::PrepList::new()); - } - #[cfg(not(web))] - LibraryAction::OpeningTraining => self.open_repertoire(&ctx), } } } - #[cfg(not(web))] - self.desktop_frame(&ctx); + // Back to the window after a while: the downloaded databases get the games + // played since (at the start they did already). + let now = ctx.input(|i| i.time); + let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); + if focused && !self.was_focused && now - self.online_updated_at > ONLINE_EVERY { + self.online_updated_at = now; + self.online.update_quietly( + self.settings + .databases + .iter() + .filter(|p| crate::online::is_online(p)) + .cloned(), + ); + } + self.was_focused = focused; + let events = self.online.show(&ctx, &self.online_probe); + for e in events { + match e { + crate::online_ui::OnlineEvent::Added(p) => { + let known = self.settings.databases.contains(&p); + self.settings.touch_database(&p); + if known { + self.library.reload(&p, &ctx); + } + self.library.select_db(&p, &ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Updated(p) => self.library.reload(&p, &ctx), + crate::online_ui::OnlineEvent::Open(p) => { + self.settings.touch_database(&p); + self.library.select_db(&p, &ctx); + self.settings_dirty = true; + } + crate::online_ui::OnlineEvent::Message(t) => self.toast(&ctx, t), + } + } + // Updates: the badge next to Settings, the window, the status in Settings → About. + self.update_check.poll(); + let skipped = self.settings.skipped_version.clone(); + let badge = self + .update_check + .newer() + .filter(|r| self.update_ui.active() || skipped.as_deref() != Some(r.version.as_str())) + .map(|r| self.update_ui.badge(r)); + self.library.update = badge.clone(); + if let Some(g) = &mut self.game { + g.update = badge; + } + for e in self + .update_ui + .show(&ctx, self.update_check.newer(), &self.update_kind) + { + match e { + crate::update_ui::UpdateEvent::Restart(exe) => { + self.restart_to = Some(exe); + self.request_close(&ctx, CloseIntent::QuitApp); + } + crate::update_ui::UpdateEvent::CopyText(t) => { + ctx.copy_text(t); + self.toast(&ctx, tr("Copied")); + } + crate::update_ui::UpdateEvent::Quit => { + self.request_close(&ctx, CloseIntent::QuitApp); + } + crate::update_ui::UpdateEvent::Skip(v) => { + self.settings.skipped_version = Some(v); + self.settings_dirty = true; + } + } + } + self.settings_ui.update_available = self.update_check.newer().map(|r| r.version.clone()); + self.settings_ui.update_status = if self.update_check.running() { + Some(tr("Checking…").to_owned()) + } else if let Some(r) = self.update_check.newer() { + Some(trf("Version {v} is out", &[("v", &r.version)])) + } else if self.update_check.release.is_some() { + Some(tr("This is the latest version").to_owned()) + } else if self.update_check.error.is_some() { + Some(tr("Could not check for updates").to_owned()) + } else { + None + }; self.settings_ui.download = self.engine_offer.stage(); self.settings_dirty |= self.translation.poll(&ctx, &mut self.settings); @@ -4890,33 +3092,15 @@ impl eframe::App for App { self.settings_dirty |= changed; for a in actions { match a { - #[cfg(not(web))] SettingsAction::AddEngine => self.pick_engine(&ctx), - #[cfg(not(web))] SettingsAction::CheckUpdates => { - self.desktop.update_check = self.desktop.update_check.again(&ctx); + self.update_check = self.update_check.again(&ctx); } - #[cfg(not(web))] SettingsAction::PickBaseFolder => { let start = own_db::default_base_dir(self.settings.new_database_dir.as_deref()); self.pick_folder(&ctx, start); } - #[cfg(not(web))] - SettingsAction::OpenUpdate => self.desktop.update_ui.open = true, - #[cfg(web)] - SettingsAction::DownloadMyGames => { - if let Err(e) = crate::my_games::download_all() { - self.toast( - &ctx, - trf("The PGN could not be downloaded: {e}", &[("e", &e)]), - ); - } - } - #[cfg(web)] - SettingsAction::KeepData => { - let ctx = ctx.clone(); - crate::platform::web::storage::persist(move |_| ctx.request_repaint()); - } + SettingsAction::OpenUpdate => self.update_ui.open = true, SettingsAction::DownloadEngine => self.engine_offer.start(&ctx), SettingsAction::CancelDownload => self.engine_offer.cancel(), SettingsAction::RemoveDownloaded => { @@ -4948,9 +3132,6 @@ impl eframe::App for App { self.confirm_dialog(&ctx); self.own_dialogs(&ctx); - self.prep_list(&ctx); - self.prep_dialog(&ctx); - self.prep_quit_question(&ctx); // Whether the database the dialog names is there, as last found. if let Some(d) = self.play_dialog.as_mut() { d.target_there = d @@ -4985,11 +3166,6 @@ impl eframe::App for App { self.start_play(&ctx, start); } } - // A copy of chosen games ends whatever is on the screen. - self.great_moves_frame(&ctx); - if let Some(end) = self.library.poll_batch(&ctx) { - self.batch_ended(&ctx, end); - } // Ctrl+Z on the library while the deleted game can still come back. if self.game.is_none() && self.own.undo.is_some() @@ -5002,27 +3178,13 @@ impl eframe::App for App { } let mut undo_clicked = false; - let mut open_copy: Option = None; - #[cfg(not(web))] - let mut open_repertoire = None; if let Some(t) = &self.toast { let now = ctx.input(|i| i.time); if now > t.until { self.toast = None; self.own.undo = None; - #[cfg(not(web))] - { - self.toast_repertoire = None; - } } else { let (msg, undo) = (t.text.clone(), t.undo && self.own.undo.is_some()); - #[cfg(not(web))] - let repertoire_link = self.toast_repertoire.clone(); - let open_db = self.toast_open_db.clone(); - #[cfg(not(web))] - let has_action = undo || repertoire_link.is_some() || open_db.is_some(); - #[cfg(web)] - let has_action = undo || open_db.is_some(); let area = egui::Area::new(egui::Id::new(TOAST)) .anchor(egui::Align2::CENTER_BOTTOM, egui::vec2(0.0, -24.0)) .order(egui::Order::Foreground) @@ -5037,18 +3199,11 @@ impl eframe::App for App { if undo && ui.button(tr("Undo")).on_hover_text("Ctrl+Z").clicked() { undo_clicked = true; } - #[cfg(not(web))] - if repertoire_link.is_some() && ui.button(tr("Open")).clicked() { - open_repertoire = repertoire_link.clone(); - } - if open_db.is_some() && ui.button(tr("Open")).clicked() { - open_copy = open_db.clone(); - } }); }); }); // Under the mouse the toast waits (the button is being reached for). - if has_action + if undo && area.response.contains_pointer() && let Some(t) = self.toast.as_mut() { @@ -5061,46 +3216,20 @@ impl eframe::App for App { self.toast = None; self.undo_delete(&ctx); } - if let Some(path) = open_copy { - self.toast = None; - self.toast_open_db = None; - self.settings.touch_database(&path); - self.settings_dirty = true; - self.library.select_db(&path, &ctx); - } - #[cfg(not(web))] - if let Some((id, title)) = open_repertoire { - self.toast = None; - self.toast_repertoire = None; - self.open_repertoire(&ctx); - if let Some(screen) = self.repertoire.as_mut() { - screen.open_from_toast(id, title, &self.settings); - } - } if self.settings_dirty && !ctx.input(|i| i.pointer.any_down()) { self.settings_dirty = false; if let Err(e) = self.settings.save() { eprintln!("settings: save failed: {e}"); } - crate::review_engine::set_candidates(&self.settings); } } fn on_exit(&mut self) { - self.library.stop_batch(); - if let Some(job) = self.library.pass.as_mut() { - job.shutdown(std::time::Duration::from_secs(3)); - } self.analysis.stop(); - crate::review_engine::shutdown(); - if let Some(p) = self.prep.as_mut() { - p.save(); - } // Downloads of online games stop and save what they got; a new database goes on // the shelf with it (the next download continues it). - #[cfg(not(web))] - for p in self.desktop.online.stop_all() { + for p in self.online.stop_all() { if crate::online::State::load(&p).is_some_and(|s| s.games > 0) { self.settings.touch_database(&p); } @@ -5109,68 +3238,6 @@ impl eframe::App for App { } } -/// What the user chose or dropped, to the screen. -/// Sends what was chosen in a dialog (`dropped`: dropped on the window) to the screen. -/// A dialog's choice is sent even when empty (cancelled): «Choose again» ends with it. -fn send_picked(tx: &Sender, picked: crate::platform::files::Picked, dropped: bool) { - if dropped { - if !picked.paths.is_empty() { - let _ = tx.send(Async::DatabasesDropped(picked.paths)); - } - } else { - let _ = tx.send(Async::DatabasesPicked(picked.paths)); - } - if !picked.missing.is_empty() { - let _ = tx.send(Async::Missing(picked.missing)); - } - if picked.empty_folder { - let _ = tx.send(Async::EmptyFolder); - } - if !picked.unsupported.is_empty() { - let _ = tx.send(Async::NotDatabases(picked.unsupported)); - } - #[cfg(web)] - { - if !picked.too_big.is_empty() { - let _ = tx.send(Async::TooBig(picked.too_big)); - } - if !picked.incomplete.is_empty() { - let _ = tx.send(Async::Incomplete(picked.incomplete)); - } - } -} - -/// Whether an action waiting for an engine still has its screen: the game (by its -/// serial) or the preparation on which it was asked. -fn still_waiting( - pending: &crate::engine_offer::Pending, - game: Option, - prep: Option, -) -> bool { - use crate::engine_offer::Pending; - match pending { - Pending::GameAnalysis { game: g, .. } => Some(*g) == game, - Pending::OpeningErrors { prep: p } => Some(*p) == prep, - Pending::LiveAnalysis => false, - // The app keeps its question (`brilliant_waiting`) until it starts. - Pending::GreatMoves => true, - } -} - -/// Files' names for a message: at most three, each at most 40 characters. -fn names_text(names: &[String]) -> String { - let mut text = names - .iter() - .take(3) - .map(|n| crate::widgets::shorten(n, 40)) - .collect::>() - .join(", "); - if names.len() > 3 { - text.push_str(", …"); - } - text -} - fn sanitize(s: &str) -> String { s.chars() .map(|c| match c { @@ -5180,64 +3247,3 @@ fn sanitize(s: &str) -> String { }) .collect::() } - -/// Why a game against the engine (Maia, a rematch, the game put aside) may not start: -/// the search for great moves has the engine (`pass`: its message while it runs). -fn engine_game_refused(pass: Option) -> Option { - pass.map(|why| { - format!( - "{} {}", - tr("A game against the engine waits until the search for great moves ends."), - why - ) - }) -} - -#[cfg(test)] -mod waiting_tests { - use super::{names_text, still_waiting}; - use crate::engine_offer::Pending; - - /// An analysis waiting for an engine starts on its own game only: another game on - /// the screen, or none, drops it; the two kinds wait apart. - #[test] - fn a_waiting_analysis_belongs_to_its_game() { - let review = Pending::GameAnalysis { - game: 7, - full: true, - }; - let errors = Pending::OpeningErrors { prep: 3 }; - assert!(still_waiting(&review, Some(7), None)); - assert!(!still_waiting(&review, Some(8), Some(3))); - assert!(!still_waiting(&review, None, Some(3))); - assert!(still_waiting(&errors, Some(8), Some(3))); - assert!(!still_waiting(&errors, Some(7), Some(4))); - assert!(!still_waiting(&Pending::LiveAnalysis, Some(7), Some(3))); - } - - /// Every way to a game against the engine asks the same guard: refused while the - /// search for great moves runs, allowed otherwise. - #[test] - fn a_game_against_the_engine_waits_for_the_search() { - assert!(super::engine_game_refused(None).is_none()); - let why = super::engine_game_refused(Some("x".into())).unwrap(); - assert!(why.ends_with('x')); - let src = include_str!("app.rs"); - for f in ["fn resume_aside(", "fn start_play("] { - let body = &src[src.find(f).unwrap()..]; - let guard = body.find("engine_game_refused(self.pass_busy())").unwrap(); - let first_return = body.find("return").unwrap(); - assert!(guard < first_return + 40, "{f} checks the search first"); - } - } - - #[test] - fn names_in_messages_are_short() { - let names: Vec = ["a.pgn", "b.pgn", "c.pgn", "d.pgn"] - .map(String::from) - .into(); - assert_eq!(names_text(&names), "a.pgn, b.pgn, c.pgn, …"); - let long = vec!["x".repeat(100) + ".pgn"]; - assert_eq!(names_text(&long).chars().count(), 40); - } -} diff --git a/apps/desktop/src/assets.rs b/apps/desktop/src/assets.rs index 388fdaf..ebdd4fc 100644 --- a/apps/desktop/src/assets.rs +++ b/apps/desktop/src/assets.rs @@ -131,11 +131,6 @@ impl PieceSet { format!("bytes://pieces/{}/{}.svg", self.name(), Self::index(piece)) } - /// The piece's picture, to put in a widget. - pub fn image(self, piece: Piece) -> egui::Image<'static> { - egui::Image::new(self.uri(piece)) - } - pub fn paint(self, ui: &egui::Ui, piece: Piece, rect: Rect) { egui::Image::new(self.uri(piece)).paint_at(ui, rect); } diff --git a/apps/desktop/src/batch_copy.rs b/apps/desktop/src/batch_copy.rs deleted file mode 100644 index 09d02f0..0000000 --- a/apps/desktop/src/batch_copy.rs +++ /dev/null @@ -1,442 +0,0 @@ -//! Several records of a database copied into a new database (task 42, -//! docs/design/tasks-42-43-2026-11-27.md): the records chosen in the table, a set of -//! record numbers that keeps a bit per record, and the copy itself, written in the -//! background into a temporary file beside the new one and published only when whole. -//! The source database is only read. - -use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::io::Write as _; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - -use chess_core::pgn::store; -use chess_import::Database; -use chess_import::chessbase::base::SortKey; - -use crate::i18n::{tr, trf}; - -/// Records chosen in a table: one bit per record number. Membership is one lookup, and -/// choosing all the records of a list of millions is one pass over it. -#[derive(Clone, Debug, Default)] -pub struct Selection { - words: Vec, - count: usize, -} - -impl Selection { - pub fn contains(&self, index: usize) -> bool { - self.words - .get(index / 64) - .is_some_and(|w| w & (1 << (index % 64)) != 0) - } - - pub fn len(&self) -> usize { - self.count - } - - pub fn is_empty(&self) -> bool { - self.count == 0 - } - - pub fn insert(&mut self, index: usize) { - let word = index / 64; - if word >= self.words.len() { - self.words.resize(word + 1, 0); - } - let bit = 1 << (index % 64); - if self.words[word] & bit == 0 { - self.words[word] |= bit; - self.count += 1; - } - } - - pub fn remove(&mut self, index: usize) { - if let Some(w) = self.words.get_mut(index / 64) { - let bit = 1 << (index % 64); - if *w & bit != 0 { - *w &= !bit; - self.count -= 1; - } - } - } - - pub fn toggle(&mut self, index: usize) { - if self.contains(index) { - self.remove(index); - } else { - self.insert(index); - } - } - - pub fn clear(&mut self) { - self.words.clear(); - self.count = 0; - } - - /// Only `index` chosen. - pub fn only(&mut self, index: usize) { - self.clear(); - self.insert(index); - } - - /// Adds every record of `records` (a list of the table). - pub fn extend(&mut self, records: &[u32]) { - if let Some(&most) = records.iter().max() { - let words = most as usize / 64 + 1; - if words > self.words.len() { - self.words.resize(words, 0); - } - } - for &r in records { - let (word, bit) = (r as usize / 64, 1u64 << (r % 64)); - if self.words[word] & bit == 0 { - self.words[word] |= bit; - self.count += 1; - } - } - } - - /// The chosen records, in the order of their numbers. - pub fn records(&self) -> Vec { - let mut out = Vec::with_capacity(self.count); - for (n, &w) in self.words.iter().enumerate() { - let mut w = w; - while w != 0 { - let bit = w.trailing_zeros(); - out.push((n * 64) as u32 + bit); - w &= w - 1; - } - } - out - } - - /// The highest chosen record. - pub fn last(&self) -> Option { - let (n, w) = self - .words - .iter() - .enumerate() - .rev() - .find(|(_, w)| **w != 0)?; - Some(n * 64 + 63 - w.leading_zeros() as usize) - } - - /// Records from `len` on let go (a database with fewer records now). - pub fn retain_below(&mut self, len: usize) { - while let Some(last) = self.last().filter(|&l| l >= len) { - self.remove(last); - } - } - - /// How many of `records` are chosen. - pub fn count_in(&self, records: &[u32]) -> usize { - if self.is_empty() { - return 0; - } - records - .iter() - .filter(|&&r| self.contains(r as usize)) - .count() - } -} - -/// The PGN text of record `index` as «Add to database» copies it: the record's own -/// text when the file is PGN read without restoring letters, otherwise the game written -/// anew (a ChessBase database has no PGN; restored letters are in the copy). -pub fn record_text(db: &Database, index: usize) -> Option { - match db.as_pgn() { - Some(pgn) if !pgn.repair_letters_enabled() => db.raw_text(index), - _ => db.load_game(index).map(|p| p.game.to_pgn()), - } -} - -/// What to copy: the chosen records (by number), the table's order and the new file. -#[derive(Clone, Debug)] -pub struct CopyRequest { - pub records: Vec, - pub sort: SortKey, - pub ascending: bool, - pub target: PathBuf, - /// A pause per record (`CP_BATCH_SLOW`): the progress can be seen and photographed. - pub slow: bool, -} - -/// How a copy went. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct CopyReport { - pub copied: usize, - /// Record numbers (from 0) skipped as a copy of a record already copied: the same - /// PGN text, white space aside. - pub duplicates: Vec, - /// Record numbers (from 0) that could not be read. - pub unreadable: Vec, -} - -impl CopyReport { - pub fn skipped(&self) -> usize { - self.duplicates.len() + self.unreadable.len() - } -} - -/// Why nothing was written. -#[derive(Debug, thiserror::Error)] -pub enum CopyError { - /// A file of that name appeared meanwhile: it is not touched. - #[error("a file with this name is already there")] - Exists, - /// The source file changed on disk: the record numbers no longer mean the same games. - #[error("the source changed")] - SourceChanged, - #[error("{0}")] - Io(#[from] std::io::Error), -} - -impl CopyError { - /// The reason in the user's words. - pub fn reason(&self) -> String { - match self { - CopyError::Exists => tr("a file with this name is already there").to_owned(), - CopyError::SourceChanged => tr("the source changed").to_owned(), - CopyError::Io(e) => match e.kind() { - std::io::ErrorKind::StorageFull => tr("no space left on the disk").to_owned(), - std::io::ErrorKind::PermissionDenied => tr("no permission to write").to_owned(), - _ => e.to_string(), - }, - } - } -} - -/// The temporary file of a copy; removed unless published. -struct Partial { - path: PathBuf, - published: bool, -} - -impl Drop for Partial { - fn drop(&mut self) { - if !self.published { - let _ = std::fs::remove_file(&self.path); - } - } -} - -/// The temporary file of a copy into `target`: `..part--`, the -/// process that writes it in its name (`clean_orphans` knows from it whether its writer -/// is gone). -fn partial_path(target: &Path) -> PathBuf { - let name = target - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(); - let mut h = std::collections::hash_map::DefaultHasher::new(); - std::time::SystemTime::now().hash(&mut h); - std::thread::current().id().hash(&mut h); - target.hash(&mut h); - target.with_file_name(format!( - ".{name}{PART}{}-{:016x}", - std::process::id(), - h.finish() - )) -} - -const PART: &str = ".part-"; - -/// Temporary files of copies whose process is gone (a crash, a power cut), in `dirs`: -/// removed. Only names this program gives (`..pgn.part--`) and only when -/// no process `` runs; anything else is left alone. -pub fn clean_orphans(dirs: &[PathBuf]) { - for dir in dirs { - let Ok(entries) = std::fs::read_dir(dir) else { - continue; - }; - for entry in entries.flatten() { - let name = entry.file_name().to_string_lossy().into_owned(); - if let Some(pid) = orphan_pid(&name) - && pid != std::process::id() - && !Path::new(&format!("/proc/{pid}")).exists() - && entry.file_type().is_ok_and(|t| t.is_file()) - { - let _ = std::fs::remove_file(entry.path()); - } - } - } -} - -/// The writer's process of a temporary copy file named so, if the name is one. -fn orphan_pid(name: &str) -> Option { - let rest = name.strip_prefix('.')?; - let (stem, tail) = rest.rsplit_once(PART)?; - if !stem.to_lowercase().ends_with(".pgn") { - return None; - } - let (pid, hex) = tail.split_once('-')?; - (hex.len() == 16 && hex.chars().all(|c| c.is_ascii_hexdigit())) - .then(|| pid.parse().ok()) - .flatten() -} - -/// A record's PGN text with every run of white space as one space: what makes two -/// records the same for a copy (the owner's rule: tags, moves, variations, comments and -/// NAG all equal; line breaks and spaces aside). -fn normalized(text: &str) -> String { - text.split_whitespace().collect::>().join(" ") -} - -/// 128 bits of a normalized record text: millions of copied records are told apart -/// without keeping their texts; equal keys are compared again in full. -fn key_of(normalized: &str) -> u128 { - let half = |salt: u64| { - let mut h = std::collections::hash_map::DefaultHasher::new(); - salt.hash(&mut h); - normalized.hash(&mut h); - h.finish() - }; - (u128::from(half(0x9e37_79b9_7f4a_7c15)) << 64) | u128::from(half(0x6a09_e667_f3bc_c909)) -} - -/// Copies the records of `req` from `db` into the new file `req.target`, in the table's -/// order (records of equal value by number). Each record has the bytes «Add to -/// database» would append to it; a record whose text was already copied is skipped, a -/// record that cannot be read too. Written into a temporary file beside the target and published by a hard -/// link, which fails rather than replace a file of that name. `None`: cancelled, nothing -/// is left on disk. -pub fn copy_into_new( - db: &Database, - req: &CopyRequest, - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Option> { - let mut order = req.records.clone(); - order.sort_unstable(); - db.sort_records(&mut order, req.sort, req.ascending); - if cancel.load(Ordering::Relaxed) { - return None; - } - let partial = Partial { - path: partial_path(&req.target), - published: false, - }; - let run = || -> Result, CopyError> { - if let Some(dir) = req.target.parent() { - std::fs::create_dir_all(dir)?; - } - if req.target.exists() { - return Err(CopyError::Exists); - } - let file = std::fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&partial.path)?; - let mut out = std::io::BufWriter::new(file); - let mut report = CopyReport::default(); - // Copied records by the key of their text; equal keys of different texts (all - // but impossible) in `more`. - let mut seen: HashMap = HashMap::new(); - let mut more: Vec = Vec::new(); - for (n, &record) in order.iter().enumerate() { - if cancel.load(Ordering::Relaxed) { - return Ok(None); - } - if req.slow { - std::thread::sleep(std::time::Duration::from_millis(100)); - } - let index = record as usize; - let text = db - .load_game(index) - .and_then(|parsed| Some((parsed, record_text(db, index)?))); - match text { - None => report.unreadable.push(index), - Some((_, text)) => { - let flat = normalized(&text); - let key = key_of(&flat); - let same = |other: u32| { - record_text(db, other as usize).is_some_and(|t| normalized(&t) == flat) - }; - let duplicate = match seen.get(&key) { - None => { - seen.insert(key, record); - false - } - Some(&first) => { - let dup = same(first) || more.iter().any(|&o| same(o)); - if !dup { - more.push(record); - } - dup - } - }; - if duplicate { - report.duplicates.push(index); - } else { - out.write_all(&store::record_for_new_file(&text))?; - report.copied += 1; - } - } - } - progress.store(n + 1, Ordering::Relaxed); - } - let file = out.into_inner().map_err(|e| e.into_error())?; - file.sync_all()?; - if let Some(pgn) = db.as_pgn() - && pgn.source_changed().unwrap_or(true) - { - return Err(CopyError::SourceChanged); - } - if cancel.load(Ordering::Relaxed) { - return Ok(None); - } - match std::fs::hard_link(&partial.path, &req.target) { - Ok(()) => Ok(Some(report)), - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err(CopyError::Exists), - Err(e) => Err(e.into()), - } - }; - match run() { - Ok(None) => None, - Ok(Some(report)) => Some(Ok(report)), - Err(e) => Some(Err(e)), - } -} - -/// « (No. 3, 4 and 2 more)» for up to `most` record numbers, nothing for none. -fn numbers(records: &[usize], most: usize) -> String { - if records.is_empty() { - return String::new(); - } - let mut list: Vec = records - .iter() - .take(most) - .map(|i| (i + 1).to_string()) - .collect(); - if records.len() > most { - list.push(trf("and {n} more", &[("n", &(records.len() - most))])); - } - format!(" ({})", trf("No. {list}", &[("list", &list.join(", "))])) -} - -/// «Name: copied 3, skipped 1 — duplicates 1 (No. 9), unreadable 0». -pub fn summary(name: &str, report: &CopyReport) -> String { - if report.skipped() == 0 { - return trf( - "{name}: copied {n}, skipped {m}", - &[("name", &name), ("n", &report.copied), ("m", &0)], - ); - } - trf( - "{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}", - &[ - ("name", &name), - ("n", &report.copied), - ("m", &report.skipped()), - ("d", &report.duplicates.len()), - ("dl", &numbers(&report.duplicates, 10)), - ("u", &report.unreadable.len()), - ("ul", &numbers(&report.unreadable, 5)), - ], - ) -} - -#[cfg(test)] -#[path = "batch_copy_tests.rs"] -mod tests; diff --git a/apps/desktop/src/batch_copy_tests.rs b/apps/desktop/src/batch_copy_tests.rs deleted file mode 100644 index b956075..0000000 --- a/apps/desktop/src/batch_copy_tests.rs +++ /dev/null @@ -1,554 +0,0 @@ -use std::sync::atomic::{AtomicBool, AtomicUsize}; - -use chess_core::PgnDatabase; -use chess_core::pgn::store; - -use super::*; - -struct Dir(PathBuf); - -impl Dir { - fn new(name: &str) -> Dir { - let path = std::env::temp_dir().join(format!("cp-batch-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Dir(path) - } - - fn file(&self, name: &str, bytes: &[u8]) -> PathBuf { - let path = self.0.join(name); - std::fs::write(&path, bytes).unwrap(); - path - } - - /// Files of the folder besides `keep` (a temporary file left behind shows here). - fn others(&self, keep: &[&Path]) -> Vec { - std::fs::read_dir(&self.0) - .unwrap() - .map(|e| e.unwrap().path()) - .filter(|p| !keep.contains(&p.as_path())) - .collect() - } -} - -impl Drop for Dir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -fn open(path: &Path) -> Database { - chess_import::open(path, &mut |_| {}, &AtomicBool::new(false)) - .unwrap() - .db -} - -/// Games with what a copy must keep: a start position with fullmove 0, variations three -/// deep, comments at the root and after moves, NAG, arrows, a tag of its own, and the -/// first game once more (a duplicate). -const SOURCE: &str = r#"[Event "Club"] -[Site "?"] -[Date "2020.01.02"] -[Round "1"] -[White "Alpha"] -[Black "Beta"] -[Result "1-0"] -[MyTag "kept"] - -{A comment at the root} 1. e4 $1 {[%cal Ge2e4]} e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0 - -[Event "Study"] -[Site "?"] -[Date "2021.??.??"] -[Round "?"] -[White "Gamma"] -[Black "Delta"] -[Result "*"] -[SetUp "1"] -[FEN "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0"] - -1. e4 Kd7 {the king} 2. Kf2 * - -[Event "Club"] -[Site "?"] -[Date "2019.05.05"] -[Round "2"] -[White "Beta"] -[Black "Alpha"] -[Result "0-1"] - -1. d4 d5 2. c4 $2 dxc4 0-1 - -[Event "Club again"] -[Site "?"] -[Date "2020.01.02"] -[Round "1"] -[White "alpha"] -[Black "BETA"] -[Result "1-0"] - -1. e4 e5 2. Nf3 Nc6 1-0 - -[Event "Club"] -[Site "?"] -[Date "2020.01.02"] -[Round "1"] -[White "Alpha"] -[Black "Beta"] -[Result "1-0"] -[MyTag "kept"] - -{A comment at the root} 1. e4 $1 {[%cal Ge2e4]} -e5 (1... c5 2. Nf3 (2. c3 d5 (2... Nf6 3. e5)) d6) 2. Nf3 $14 Nc6 1-0 -"#; - -fn request(records: &[u32], target: &Path) -> CopyRequest { - CopyRequest { - records: records.to_vec(), - sort: SortKey::Number, - ascending: true, - target: target.to_path_buf(), - slow: false, - } -} - -fn copy(db: &Database, req: &CopyRequest) -> Option> { - copy_into_new(db, req, &AtomicUsize::new(0), &AtomicBool::new(false)) -} - -/// The new database as «Add to database» would make it: an empty file, then each record -/// appended in turn, a game already there skipped. -fn one_by_one(db: &Database, order: &[usize], target: &Path) { - std::fs::write(target, b"").unwrap(); - let mut written: Vec = Vec::new(); - for &i in order { - let into = PgnDatabase::open(target, &mut |_| {}, &AtomicBool::new(false)).unwrap(); - let text = record_text(db, i).unwrap(); - if !written.contains(&normalized(&text)) { - store::append(&into, &text).unwrap(); - written.push(normalized(&text)); - } - } -} - -#[test] -fn a_selection_keeps_a_bit_per_record() { - let mut s = Selection::default(); - assert!(s.is_empty() && !s.contains(5)); - s.insert(5); - s.insert(5); - s.insert(200); - assert_eq!((s.len(), s.records()), (2, vec![5, 200])); - s.toggle(5); - s.toggle(7); - assert_eq!(s.records(), vec![7, 200]); - s.extend(&[1, 7, 300]); - assert_eq!((s.len(), s.records()), (4, vec![1, 7, 200, 300])); - assert_eq!(s.count_in(&[0, 1, 2, 300]), 2); - s.remove(1000); - s.remove(7); - assert_eq!(s.len(), 3); - assert_eq!(s.last(), Some(300)); - s.retain_below(201); - assert_eq!(s.records(), vec![1, 200]); - s.only(42); - assert_eq!(s.records(), vec![42]); - s.clear(); - assert!(s.is_empty()); -} - -#[test] -fn a_copy_has_the_bytes_of_adding_the_games_one_by_one() { - let dir = Dir::new("same"); - let source = dir.file("source.pgn", SOURCE.as_bytes()); - let before = std::fs::read(&source).unwrap(); - let db = open(&source); - assert_eq!(db.len(), 5); - let target = dir.0.join("copy.pgn"); - let report = copy(&db, &request(&[3, 0, 4, 2, 1], &target)) - .unwrap() - .unwrap(); - // Record 5 is record 1 again with other line breaks: skipped; record 4 is the same - // game with other tags: copied. - assert_eq!( - report, - CopyReport { - copied: 4, - duplicates: vec![4], - unreadable: Vec::new() - } - ); - let expected = dir.0.join("expected.pgn"); - one_by_one(&db, &[0, 1, 2, 3, 4], &expected); - assert_eq!( - std::fs::read(&target).unwrap(), - std::fs::read(&expected).unwrap() - ); - // The source is only read; no temporary file is left. - assert_eq!(std::fs::read(&source).unwrap(), before); - assert!(dir.others(&[&source, &target, &expected]).is_empty()); - // Every game whole: tags, start position, variations, comments, NAG, arrows. - let copied = open(&target); - for (i, j) in [(0, 0), (1, 1), (2, 2)] { - assert_eq!( - copied.load_game(j).unwrap().game.to_pgn(), - db.load_game(i).unwrap().game.to_pgn() - ); - } - let text = std::fs::read_to_string(&target).unwrap(); - for kept in [ - "[MyTag \"kept\"]", - "{A comment at the root}", - "$1", - "[%cal Ge2e4]", - "(2... Nf6 3. e5)", - "4k3/8/8/8/8/8/4P3/4K3 w - - 0 0", - ] { - assert!(text.contains(kept), "{kept}"); - } -} - -/// The owner's example: in Dvoretsky's endgame manual records 719 and 728 are one game -/// with other comments; both are copied (the user's file, read only, when it is there). -#[test] -fn records_with_other_comments_are_both_copied() { - let path = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../pgnFilesforExample/Дворецкий. Учебник жндшпиля.pgn"); - if !path.exists() { - return; - } - let db = open(&path); - let dir = Dir::new("dvoretsky"); - let target = dir.0.join("copy.pgn"); - let report = copy(&db, &request(&[718, 727], &target)).unwrap().unwrap(); - assert_eq!((report.copied, report.duplicates.len()), (2, 0)); - // The same record twice in a source: the second is skipped. - let one = record_text(&db, 718).unwrap(); - let source = dir.file("twice.pgn", format!("{one}\n\n{one}\n").as_bytes()); - let twice = open(&source); - let target = dir.0.join("twice-copy.pgn"); - let report = copy(&twice, &request(&[0, 1], &target)).unwrap().unwrap(); - assert_eq!((report.copied, report.duplicates), (1, vec![1])); -} - -#[test] -fn the_summary_names_the_skipped_records() { - let report = CopyReport { - copied: 5, - duplicates: (0..12).collect(), - unreadable: vec![39], - }; - assert_eq!( - summary("Pick", &report), - "Pick: copied 5, skipped 13 — duplicates 12 (No. 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, and 2 more), unreadable 1 (No. 40)" - ); - let clean = CopyReport { - copied: 3, - ..CopyReport::default() - }; - assert_eq!(summary("Pick", &clean), "Pick: copied 3, skipped 0"); -} - -#[test] -fn only_orphans_of_this_program_are_removed() { - let dir = Dir::new("orphans"); - let mine_live = format!(".a.pgn.part-{}-0123456789abcdef", std::process::id()); - // No process has a number that high on Linux (pid_max is at most 4194304). - let dead = ".a.pgn.part-999999999-0123456789abcdef"; - let others = [ - ".a.pgn.part-999999999", - ".a.txt.part-999999999-0123456789abcdef", - "a.pgn.part-999999999-0123456789abcdef", - ".a.pgn.part-999999999-xyz", - ]; - for name in [mine_live.as_str(), dead].iter().chain(others.iter()) { - dir.file(name, b"x"); - } - clean_orphans(std::slice::from_ref(&dir.0)); - assert!(!dir.0.join(dead).exists()); - assert!(dir.0.join(&mine_live).exists()); - for name in others { - assert!(dir.0.join(name).exists(), "{name}"); - } - // Each copy has a name of its own. - let target = dir.0.join("t.pgn"); - assert_ne!(partial_path(&target), partial_path(&target)); - let name = partial_path(&target); - assert!(orphan_pid(&name.file_name().unwrap().to_string_lossy()).is_some()); -} - -#[test] -fn a_copy_follows_the_tables_order() { - let dir = Dir::new("order"); - let source = dir.file("source.pgn", SOURCE.as_bytes()); - let db = open(&source); - let target = dir.0.join("copy.pgn"); - let req = CopyRequest { - sort: SortKey::White, - ascending: false, - ..request(&[0, 1, 2], &target) - }; - copy(&db, &req).unwrap().unwrap(); - let mut table = vec![0, 1, 2]; - db.sort_records(&mut table, SortKey::White, false); - let whites: Vec = (0..3) - .map(|i| { - open(&target) - .load_game(i) - .unwrap() - .game - .tag("White") - .unwrap() - .to_owned() - }) - .collect(); - let wanted: Vec = table - .iter() - .map(|&i| { - db.load_game(i as usize) - .unwrap() - .game - .tag("White") - .unwrap() - .to_owned() - }) - .collect(); - assert_eq!(whites, wanted); - assert_eq!(whites, ["Gamma", "Beta", "Alpha"]); -} - -#[test] -fn a_cancelled_copy_leaves_nothing() { - let dir = Dir::new("cancel"); - let source = dir.file("source.pgn", SOURCE.as_bytes()); - let db = open(&source); - let target = dir.0.join("copy.pgn"); - let cancel = AtomicBool::new(true); - let got = copy_into_new( - &db, - &request(&[0, 1], &target), - &AtomicUsize::new(0), - &cancel, - ); - assert!(got.is_none()); - assert!(!target.exists()); - assert!(dir.others(&[&source]).is_empty()); - - // Cancelled while writing (another thread, a slow copy). - let cancel = std::sync::Arc::new(AtomicBool::new(false)); - let progress = std::sync::Arc::new(AtomicUsize::new(0)); - let (c, p) = (cancel.clone(), progress.clone()); - let req = CopyRequest { - slow: true, - ..request(&[0, 1, 2, 3], &target) - }; - let worker = std::thread::spawn(move || copy_into_new(&db, &req, &p, &c)); - while progress.load(std::sync::atomic::Ordering::Relaxed) == 0 { - std::thread::yield_now(); - } - cancel.store(true, std::sync::atomic::Ordering::Relaxed); - assert!(worker.join().unwrap().is_none()); - assert!(!target.exists()); - assert!(dir.others(&[&source]).is_empty()); -} - -#[test] -fn a_copy_never_replaces_a_file() { - let dir = Dir::new("exists"); - let source = dir.file("source.pgn", SOURCE.as_bytes()); - let db = open(&source); - let target = dir.file("copy.pgn", b"mine"); - let got = copy(&db, &request(&[0], &target)).unwrap(); - assert!(matches!(got, Err(CopyError::Exists))); - assert_eq!(std::fs::read(&target).unwrap(), b"mine"); - assert!(dir.others(&[&source, &target]).is_empty()); -} - -#[test] -fn a_source_changed_while_copying_writes_nothing() { - let dir = Dir::new("changed"); - let source = dir.file("source.pgn", SOURCE.as_bytes()); - let db = open(&source); - std::fs::write(&source, format!("{SOURCE}\n[White \"x\"]\n\n1. e4 *\n")).unwrap(); - let target = dir.0.join("copy.pgn"); - let got = copy(&db, &request(&[0], &target)).unwrap(); - assert!(matches!(got, Err(CopyError::SourceChanged))); - assert!(!target.exists()); - assert!(dir.others(&[&source]).is_empty()); -} - -#[test] -fn a_legacy_source_is_copied_as_its_text_reads() { - let dir = Dir::new("legacy"); - // windows-1252: «é», «ü» and «—» are one byte each. - let mut bytes = b"[Event \"Caf\xe9\"]\n[White \"M\xfcller\"]\n[Black \"Ren\xe9\"]\n[Result \"1-0\"]\n\n{Le d\xe9but \x97 bien} 1. e4 e5 1-0\n".to_vec(); - bytes.extend_from_slice(b"\n[White \"B\"]\n[Black \"C\"]\n[Result \"*\"]\n\n1. d4 *\n"); - let source = dir.file("legacy.pgn", &bytes); - let db = open(&source); - let target = dir.0.join("copy.pgn"); - copy(&db, &request(&[0, 1], &target)).unwrap().unwrap(); - let expected = dir.0.join("expected.pgn"); - one_by_one(&db, &[0, 1], &expected); - assert_eq!( - std::fs::read(&target).unwrap(), - std::fs::read(&expected).unwrap() - ); - let copied = open(&target); - let (a, b) = ( - db.load_game(0).unwrap().game, - copied.load_game(0).unwrap().game, - ); - assert_eq!(a.tag("White"), b.tag("White")); - assert_eq!(a.to_pgn(), b.to_pgn()); - assert!(String::from_utf8(std::fs::read(&target).unwrap()).is_ok()); - assert_eq!(std::fs::read(&source).unwrap(), bytes); -} - -/// windows-1251 bytes of `text` (ASCII and the Russian letters without «ё»). -fn cp1251(text: &str) -> Vec { - text.chars() - .map(|c| match c { - 'А'..='я' => (c as u32 - 'А' as u32 + 0xC0) as u8, - c => c as u8, - }) - .collect() -} - -#[test] -fn a_source_with_restored_letters_is_copied_as_adding_one_game() { - let dir = Dir::new("repair"); - // `~~`, `o^` and `><` stand for ч, ю and Ч in old Russian files; restored on reading - // (a copy has the restored text, as a game added alone; tasks.md, task 42, Д1). - let comment = "{Клo^~~евые поля, ><ерные играo^т, ~~ерные} ".repeat(12); - let text = format!( - "[White \"Петров\"]\n[Black \"Иванов\"]\n[Result \"*\"]\n\n{comment}1. e4 *\n\n[White \"Б\"]\n[Black \"В\"]\n[Result \"*\"]\n\n{{~~ерные}} 1. d4 *\n" - ); - let bytes = cp1251(&text); - let source = dir.file("repair.pgn", &bytes); - let db = open(&source); - assert!(db.as_pgn().is_some_and(|p| p.repair_letters_enabled())); - let target = dir.0.join("copy.pgn"); - copy(&db, &request(&[0, 1], &target)).unwrap().unwrap(); - let expected = dir.0.join("expected.pgn"); - one_by_one(&db, &[0, 1], &expected); - assert_eq!( - std::fs::read(&target).unwrap(), - std::fs::read(&expected).unwrap() - ); - assert!(std::fs::read_to_string(&target).unwrap().contains("ерные")); - assert_eq!(std::fs::read(&source).unwrap(), bytes); -} - -/// Copying 1000 games and choosing 4 million rows: timed (`cargo test -- --ignored -/// --nocapture`, release for figures). -#[test] -#[ignore] -fn timing() { - let dir = Dir::new("timing"); - let mut text = String::new(); - for i in 0..1000 { - text.push_str(&format!( - "[Event \"E\"]\n[White \"W{i}\"]\n[Black \"B{i}\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 (2. f4 exf4 {{gambit}}) Nc6 3. Bb5 $1 a6 4. Ba4 Nf6 5. O-O Be7 *\n\n" - )); - } - let source = dir.file("source.pgn", text.as_bytes()); - let db = open(&source); - let target = dir.0.join("copy.pgn"); - let records: Vec = (0..1000).collect(); - let t = std::time::Instant::now(); - let report = copy(&db, &request(&records, &target)).unwrap().unwrap(); - println!( - "copy 1000 games: {:?} ({} copied)", - t.elapsed(), - report.copied - ); - let view: Vec = (0..4_000_000).collect(); - let t = std::time::Instant::now(); - let mut s = Selection::default(); - s.extend(&view); - println!("select all of 4 000 000: {:?}", t.elapsed()); - let t = std::time::Instant::now(); - let n = s.count_in(&view); - println!("count chosen in 4 000 000: {:?} ({n})", t.elapsed()); -} - -fn rss_anon_kb() -> u64 { - std::fs::read_to_string("/proc/self/status") - .ok() - .and_then(|s| { - s.lines() - .find(|l| l.starts_with("RssAnon:")) - .and_then(|l| l.split_whitespace().nth(1)?.parse().ok()) - }) - .unwrap_or(0) -} - -/// The memory a copy takes beyond the open database: the peak of `RssAnon` while it runs -/// less the value before. `CP_PROBE_DB=` and `CP_PROBE_N=` (release: -/// `cargo test --release -- --ignored --nocapture copy_memory`); without them, synthetic -/// PGN of 1 000 000 games in a temporary folder. -#[test] -#[ignore] -fn copy_memory() { - let dir = Dir::new("memory"); - let (db, n) = match std::env::var("CP_PROBE_DB") { - Ok(path) => { - let n = std::env::var("CP_PROBE_N") - .ok() - .and_then(|n| n.parse().ok()) - .unwrap_or(200_000); - (open(Path::new(&path)), n) - } - Err(_) => { - let n: usize = std::env::var("CP_PROBE_N") - .ok() - .and_then(|n| n.parse().ok()) - .unwrap_or(1_000_000); - let path = dir.0.join("big.pgn"); - let mut out = std::io::BufWriter::new(std::fs::File::create(&path).unwrap()); - for i in 0..n { - write!( - out, - "[White \"W{i}\"]\n[Black \"B{}\"]\n[Result \"*\"]\n\n1. 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 *\n\n", - i % 977 - ) - .unwrap(); - } - drop(out); - (open(&path), n) - } - }; - let records: Vec = (0..n.min(db.len()) as u32).collect(); - // The database's own index for sorting is built once, by the table: not the copy's. - db.sort_records(&mut records.clone(), SortKey::Number, true); - let before = rss_anon_kb(); - let done = std::sync::Arc::new(AtomicBool::new(false)); - let peak = { - let done = done.clone(); - std::thread::spawn(move || { - let mut peak = 0; - while !done.load(std::sync::atomic::Ordering::Relaxed) { - peak = peak.max(rss_anon_kb()); - std::thread::sleep(std::time::Duration::from_millis(20)); - } - peak - }) - }; - let target = dir.0.join("copy.pgn"); - let t = std::time::Instant::now(); - let report = copy(&db, &request(&records, &target)).unwrap().unwrap(); - let took = t.elapsed(); - done.store(true, std::sync::atomic::Ordering::Relaxed); - let peak = peak.join().unwrap(); - println!( - "records {}: copied {}, duplicates {}, {:?}; RssAnon before {} KB, peak {} KB, +{} KB ({:.0} B per record)", - records.len(), - report.copied, - report.duplicates.len(), - took, - before, - peak, - peak.saturating_sub(before), - peak.saturating_sub(before) as f64 * 1024.0 / records.len().max(1) as f64 - ); -} diff --git a/apps/desktop/src/board.rs b/apps/desktop/src/board.rs index 3081f3a..b1c79bf 100644 --- a/apps/desktop/src/board.rs +++ b/apps/desktop/src/board.rs @@ -32,9 +32,6 @@ pub enum Drawn { Circle(chess_core::ShapeColor, Square), } -#[cfg(test)] -pub(crate) type TestAnimation<'a> = (f64, &'a [(Piece, Square, Square)], f32); - #[derive(Default)] pub struct BoardState { selected: Option, @@ -44,9 +41,6 @@ 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, @@ -95,42 +89,10 @@ 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() } - - #[cfg(test)] - pub(crate) fn animation_at(&self, now: f64) -> Option> { - let anim = self.anim.as_ref()?; - Some((anim.duration, &anim.slides, anim.rest(now)?)) - } } /// Pieces moving from one position to the next, as on Lichess (chessground): each piece @@ -205,8 +167,6 @@ 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, @@ -247,11 +207,6 @@ 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() { @@ -310,11 +265,10 @@ 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() { - let drawn = match to { + state.shape = Some(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() { @@ -322,27 +276,14 @@ 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)); - self.record_shape(state, Drawn::Circle(color, sq)); + state.shape = Some(Drawn::Circle(color, sq)); } } } - // A released legal drag is already at its destination. Draw that result - // in this frame too, before the caller installs the move in its model. - // Click moves keep the ordinary animation on the following frame. - let dropped_position = result - .as_ref() - .filter(|_| state.dropped.is_some()) - .map(|mv| { - let mut position = self.pos.clone(); - position.play_unchecked(*mv); - position - }); - let painted_position = dropped_position.as_ref().unwrap_or(self.pos); - // --- animation --------------------------------------------------------------------- let now = ui.input(|i| i.time); - let board = painted_position.board(); + let board = self.pos.board(); if state.shown.as_ref() != Some(board) { state.anim = None; if let Some(prev) = &state.shown @@ -399,8 +340,8 @@ impl BoardView<'_> { hl(&painter, from, red); hl(&painter, to, red); } - if painted_position.is_check() - && let Some(k) = painted_position.board().king_of(painted_position.turn()) + if self.pos.is_check() + && let Some(k) = self.pos.board().king_of(self.pos.turn()) { let r = geo.square_rect(k); painter.circle_filled( @@ -423,7 +364,7 @@ impl BoardView<'_> { .paint_tinted(ui, piece, r, Color32::WHITE.gamma_multiply(rest)); } } - for (sq, piece) in painted_position.board().clone() { + for (sq, piece) in self.pos.board().clone() { if state.drag == Some(sq) && response.dragged() { continue; } @@ -476,31 +417,6 @@ 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) { @@ -613,14 +529,6 @@ 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 { @@ -1014,252 +922,4 @@ 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()); - } - - /// A right-button drag in the analysis of a game: one arrow, handed over once, in - /// the colour of the modifiers held as the button is let go. - #[test] - fn analysis_arrow_is_drawn_by_a_right_drag() { - let ctx = egui::Context::default(); - let pos = Chess::default(); - let mut state = BoardState::default(); - let from = egui::pos2(225.0, 325.0); - let to = egui::pos2(225.0, 225.0); - let shift_alt = egui::Modifiers::SHIFT | egui::Modifiers::ALT; - board_frame(&ctx, &mut state, &pos, 0.0, Vec::new(), false); - 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, - }, - ], - false, - ); - board_frame( - &ctx, - &mut state, - &pos, - 0.2, - vec![egui::Event::PointerMoved(to)], - false, - ); - assert!( - state.take_shape().is_none(), - "nothing before the button is let go" - ); - board_frame( - &ctx, - &mut state, - &pos, - 0.3, - vec![ - egui::Event::ModifiersChanged(shift_alt), - egui::Event::PointerButton { - pos: to, - button: egui::PointerButton::Secondary, - pressed: false, - modifiers: shift_alt, - }, - ], - false, - ); - assert!(state.temporary_shapes.is_empty()); - assert_eq!( - state.take_shape(), - Some(Drawn::Arrow( - chess_core::ShapeColor::Yellow, - "e2".parse().unwrap(), - "e4".parse().unwrap() - )) - ); - assert!(state.take_shape().is_none()); - } - - #[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 73d050e..76445fc 100644 --- a/apps/desktop/src/board_search.rs +++ b/apps/desktop/src/board_search.rs @@ -519,7 +519,6 @@ impl SearchBoard { circles: &[], badge: None, interactive: true, - temporary_shapes: false, show_coords: settings.show_coords, theme: settings.board_theme.theme(), pieces: settings.piece_set, @@ -884,7 +883,7 @@ pub fn ply_label(ply: u32) -> String { } } -/// A position search (or other work with progress and cancelling) in the background. +/// A position search running in a background thread. pub struct Background { cancel: Arc, progress: Arc, @@ -903,12 +902,14 @@ impl Background { let progress = Arc::new(AtomicUsize::new(0)); let (tx, rx) = channel(); let (c, p, ctx) = (cancel.clone(), progress.clone(), ctx.clone()); - crate::platform::spawn("position-search", move || { - let r = work(&p, &c); - let _ = tx.send(r); - ctx.request_repaint(); - }) - .ok()?; + std::thread::Builder::new() + .name("position-search".into()) + .spawn(move || { + let r = work(&p, &c); + let _ = tx.send(r); + ctx.request_repaint(); + }) + .ok()?; Some(Background { cancel, progress, @@ -930,11 +931,6 @@ impl Background { pub fn cancel(&self) { self.cancel.store(true, Ordering::Relaxed); } - - /// Waits up to `timeout` for the result (the work cleans up after itself). - pub fn wait(&self, timeout: std::time::Duration) -> Option> { - self.rx.recv_timeout(timeout).ok() - } } impl Drop for Background { diff --git a/apps/desktop/src/brilliant.rs b/apps/desktop/src/brilliant.rs deleted file mode 100644 index f41e4ec..0000000 --- a/apps/desktop/src/brilliant.rs +++ /dev/null @@ -1,862 +0,0 @@ -//! The search for brilliant and great moves (!!, !) in the games of a filtered list -//! or a manual selection (tasks 27 and 42): a background pass of -//! the game analysis's engine over at most [`LIMIT`] games, the index of what each -//! analysed record holds (kept beside the analysis cache, one file per database), and -//! the totals of a pass by category. Games already analysed come from the analysis -//! cache, the engine is not asked again; the source database is only read. - -use std::collections::BTreeMap; -use std::hash::{Hash, Hasher}; -use std::path::{Path, PathBuf}; -use std::sync::Mutex; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - -use chess_core::Game; -use chess_import::Database; -use game_review::{CacheStore, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement}; -use serde::{Deserialize, Serialize}; - -/// A pass takes at most this many games (the owner's limit, inclusive). -pub const LIMIT: usize = 100; - -/// Why a pass over `n` listed games cannot start (the button is disabled with this). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Blocked { - NoGames, - TooMany, -} - -/// Whether a pass over a list of `n` games may start: 1 to [`LIMIT`] inclusive. -pub fn can_start(n: usize) -> Result<(), Blocked> { - match n { - 0 => Err(Blocked::NoGames), - n if n > LIMIT => Err(Blocked::TooMany), - _ => Ok(()), - } -} - -/// The manual source of a pass: its size before cached or unsupported games are taken -/// out, and how many of those records the current filter hid when the request was made. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct SelectedGames { - pub games: usize, - pub hidden: usize, -} - -/// Engine judgements of one side of a game. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Counts { - pub brilliant: u32, - pub great: u32, - pub inaccuracies: u32, - pub mistakes: u32, - pub blunders: u32, -} - -/// One side of an analysed game: its judgements, average centipawn loss and accuracy. -#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct SideMarks { - #[serde(flatten)] - pub counts: Counts, - #[serde(default)] - pub acpl: Option, - #[serde(default)] - pub accuracy: Option, -} - -impl SideMarks { - fn of(s: &game_review::SideStats) -> SideMarks { - SideMarks { - counts: Counts { - brilliant: s.brilliant, - great: s.great, - inaccuracies: s.inaccuracies, - mistakes: s.mistakes, - blunders: s.blunders, - }, - acpl: s.acpl, - accuracy: s.accuracy, - } - } -} - -impl Counts { - pub fn add(&mut self, o: &Counts) { - self.brilliant += o.brilliant; - self.great += o.great; - self.inaccuracies += o.inaccuracies; - self.mistakes += o.mistakes; - self.blunders += o.blunders; - } -} - -/// A move of note: its ply in the main line (0: the first move), who made it, its -/// number and SAN (Latin letters, as in PGN), and whether it is brilliant (else great). -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Found { - pub ply: u16, - pub white: bool, - pub number: u32, - pub san: String, - pub brilliant: bool, -} - -impl Found { - /// «21.Rxf7!!», «34…Nf3+!!» in the notation of the settings. - pub fn label(&self) -> String { - let dots = if self.white { "." } else { "…" }; - let mark = if self.brilliant { "!!" } else { "!" }; - format!("{}{dots}{}{mark}", self.number, crate::san::show(&self.san)) - } -} - -/// Why a game is not analysed. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum Skip { - NoMoves, - Chess960, - /// A training null move (`--`) in the main line. - NullMove, - Unreadable, -} - -impl Skip { - pub fn reason(self) -> &'static str { - crate::i18n::tr(match self { - Skip::NoMoves => "no moves", - Skip::Chess960 => "Chess960", - Skip::NullMove => "a null move in the main line", - Skip::Unreadable => "the game cannot be read", - }) - } -} - -/// What the index knows of a record. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Entry { - /// The main line's name in the analysis cache: the entry holds only while the record - /// still has this main line. - pub line: String, - #[serde(default)] - pub white: SideMarks, - #[serde(default)] - pub black: SideMarks, - /// Every !! and the first three !. - #[serde(default)] - pub found: Vec, - /// Analysed with the engine settings of before (counted as analysed). - #[serde(default)] - pub stale: bool, - #[serde(default)] - pub skip: Option, -} - -impl Entry { - /// The entry with only the marks of the sides that count (the filter's player): the - /// row's sign and hint show only them. - pub fn for_sides(&self, white: bool, black: bool) -> Entry { - let keep = |on: bool, s: &SideMarks| if on { *s } else { SideMarks::default() }; - Entry { - white: keep(white, &self.white), - black: keep(black, &self.black), - found: self - .found - .iter() - .filter(|f| if f.white { white } else { black }) - .cloned() - .collect(), - ..self.clone() - } - } - - /// The !! and ! of the sides that count. - pub fn of_sides(&self, white: bool, black: bool) -> Counts { - let mut c = Counts::default(); - if white { - c.add(&self.white.counts); - } - if black { - c.add(&self.black.counts); - } - c - } -} - -/// The entry of `record` if it still belongs to the game the database has there now (its -/// main line is the one analysed): a deleted or changed game never lends its marks to -/// the record that took its number. -pub fn current_entry(index: &Index, db: &Database, record: u32) -> Option { - let entry = index.get(record)?; - let game = db.load_game(record as usize)?.game; - (GameAnalysis::new(&game, None).cache_key() == entry.line).then(|| entry.clone()) -} - -/// The record of an analysis of `game`: its marks per side and its moves of note. -pub fn entry_of(analysis: &GameAnalysis, game: &Game) -> Entry { - let report = &analysis.report; - let line = analysis.line(); - let mut found = Vec::new(); - let mut great = 0; - for (ply, j) in report.judgements.iter().enumerate() { - let brilliant = match j { - Some(Judgement::Brilliant) => true, - Some(Judgement::Great) if great < 3 => { - great += 1; - false - } - _ => continue, - }; - let Some(&node) = line.get(ply + 1) else { - continue; - }; - let (Some(m), Some((number, color))) = (game.game_move(node), game.move_number(node)) - else { - continue; - }; - found.push(Found { - ply: ply as u16, - white: color == chess_core::shakmaty::Color::White, - number, - san: m.san.clone(), - brilliant, - }); - } - Entry { - line: analysis.cache_key(), - white: SideMarks::of(&report.white), - black: SideMarks::of(&report.black), - found, - stale: analysis.stale(), - skip: None, - } -} - -/// The entry of a game that is not analysed, and why («—» in the column). -pub fn skipped_entry(line: String, skip: Skip) -> Entry { - Entry { - line, - white: SideMarks::default(), - black: SideMarks::default(), - found: Vec::new(), - stale: false, - skip: Some(skip), - } -} - -/// Why `game` is not analysed, if it is not. -pub fn skip_of(game: &Game, chess960: bool) -> Option { - if chess960 { - return Some(Skip::Chess960); - } - let line = game.mainline(); - if line.is_empty() { - return Some(Skip::NoMoves); - } - if line - .iter() - .any(|id| game.game_move(*id).is_none_or(|m| m.is_null())) - { - return Some(Skip::NullMove); - } - None -} - -#[derive(Serialize, Deserialize)] -struct IndexFile { - version: u32, - records: Vec<(u32, Entry)>, -} - -const INDEX_VERSION: u32 = 1; - -/// The marks of a database's records, by record number, in a file of their own. No -/// file (or one of another version) is an empty index: nothing found yet. -#[derive(Debug, Default)] -pub struct Index { - file: Option, - records: BTreeMap, - /// Changes since it was read (the table re-checks what it shows). - pub generation: u64, -} - -/// The folder of the indexes: beside the analysis cache. -fn index_dir() -> Option { - crate::settings::Settings::cache_dir().map(|d| d.join("marks")) -} - -/// The index file of the database at `db`: named by a hash of its real path. -pub fn index_file(dir: &Path, db: &Path) -> PathBuf { - let real = std::fs::canonicalize(db).unwrap_or_else(|_| db.to_path_buf()); - let mut h = std::collections::hash_map::DefaultHasher::new(); - real.hash(&mut h); - dir.join(format!("{:016x}.json", h.finish())) -} - -impl Index { - /// The index of the database at `db`, from the program's cache. - pub fn of(db: &Path) -> Index { - match index_dir() { - Some(dir) => Index::load(index_file(&dir, db)), - None => Index::default(), - } - } - - /// The index kept in `file`. - pub fn load(file: PathBuf) -> Index { - let records = match crate::platform::fs::read(&file) { - Ok(bytes) => match serde_json::from_slice::(&bytes) { - Ok(f) if f.version == INDEX_VERSION => f.records.into_iter().collect(), - Ok(f) => { - eprintln!("marks: {}: version {}", file.display(), f.version); - BTreeMap::new() - } - Err(e) => { - eprintln!("marks: {}: {e}", file.display()); - BTreeMap::new() - } - }, - Err(_) => BTreeMap::new(), - }; - Index { - file: Some(file), - records, - generation: 0, - } - } - - /// The records with an entry. - pub fn records(&self) -> impl Iterator + '_ { - self.records.keys().copied() - } - - pub fn get(&self, record: u32) -> Option<&Entry> { - self.records.get(&record) - } - - pub fn set(&mut self, record: u32, entry: Entry) { - self.records.insert(record, entry); - self.generation += 1; - } - - /// Where a record goes when the table is sorted by its marks: !! first, then !, - /// analysed without them, not analysable, not analysed. - pub fn rank(&self, record: u32, sides: &Sides, current: &dyn Fn(u32) -> bool) -> u8 { - match self.records.get(&record).filter(|_| current(record)) { - None => 4, - Some(e) if e.skip.is_some() => 3, - Some(e) => { - let (w, b) = sides.of(record); - let c = e.of_sides(w, b); - if c.brilliant > 0 { - 0 - } else if c.great > 0 { - 1 - } else { - 2 - } - } - } - } - - #[cfg(test)] - pub fn len(&self) -> usize { - self.records.len() - } - - /// Written whole into a temporary file and renamed over the old one. - pub fn save(&self) -> std::io::Result<()> { - let Some(file) = &self.file else { - return Ok(()); - }; - let out = IndexFile { - version: INDEX_VERSION, - records: self.records.iter().map(|(r, e)| (*r, e.clone())).collect(), - }; - let bytes = serde_json::to_vec(&out).map_err(std::io::Error::other)?; - if let Some(dir) = file.parent() { - std::fs::create_dir_all(dir)?; - } - crate::platform::fs::write_atomic(file, &bytes) - } -} - -/// How far a pass is: games done, and the record being analysed (its number + 1; 0: -/// none). -#[derive(Debug, Default)] -pub struct Progress { - pub done: AtomicUsize, - pub current: AtomicUsize, -} - -/// How a pass ended. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Outcome { - Finished, - Stopped, - EngineFailed(String), - SourceChanged, -} - -/// What a pass did. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PassEnd { - pub outcome: Outcome, - /// Records analysed (by the engine now, or from the cache), in the pass's order. - pub reviewed: Vec, - /// Of them, taken from the cache without the engine. - pub from_cache: usize, - pub skipped: Vec<(u32, Skip)>, -} - -/// The engine of a pass: started for each game that needs it. -pub struct Engine { - #[cfg(not(web))] - pub config: uci::EngineConfig, - pub settings: JobSettings, - /// Whether the engine, by the name it gives, is still the one checked. - pub fits: Box bool + Send + Sync>, - /// A pause before each game (`CP_BRILLIANT_SLOW`: the progress can be photographed). - pub pause: std::time::Duration, -} - -/// The engine job over `targets` (on a computer; a browser has no pass, `CAPS`). -#[cfg(not(web))] -fn engine_run( - engine: &Engine, - targets: Vec, - cancel: &AtomicBool, - on_event: &mut dyn FnMut(JobEvent), -) -> Result<(), JobFailure> { - game_review::run( - engine.config.clone(), - &engine.settings, - targets, - cancel, - on_event, - ) -} - -#[cfg(web)] -fn engine_run( - _engine: &Engine, - _targets: Vec, - _cancel: &AtomicBool, - _on_event: &mut dyn FnMut(JobEvent), -) -> Result<(), JobFailure> { - Err(JobFailure::Start( - crate::i18n::tr("the engine did not start").to_owned(), - )) -} - -/// Analyses `records` of `db` in this order: each from the analysis cache in `cache` -/// when it is there (also one made with the engine settings of before), else with -/// `engine`; after each game the cache and `index` are saved, so a stop or a crash -/// keeps what was done. `cancel` stops it within the current search. -pub fn run_pass( - db: &Database, - records: &[u32], - index: &Mutex, - cache: &dyn CacheStore, - engine: &Engine, - progress: &Progress, - cancel: &AtomicBool, -) -> PassEnd { - let mut end = PassEnd { - outcome: Outcome::Finished, - reviewed: Vec::new(), - from_cache: 0, - skipped: Vec::new(), - }; - for &record in records { - if cancel.load(Ordering::Relaxed) { - end.outcome = Outcome::Stopped; - break; - } - if let Some(pgn) = db.as_pgn() - && pgn.source_changed().unwrap_or(true) - { - end.outcome = Outcome::SourceChanged; - break; - } - progress - .current - .store(record as usize + 1, Ordering::Relaxed); - if !engine.pause.is_zero() { - std::thread::sleep(engine.pause); - if cancel.load(Ordering::Relaxed) { - end.outcome = Outcome::Stopped; - break; - } - } - let index_skip = |skip: Skip, line: String| { - if let Ok(mut i) = index.lock() { - i.set( - record, - Entry { - line, - white: SideMarks::default(), - black: SideMarks::default(), - found: Vec::new(), - stale: false, - skip: Some(skip), - }, - ); - let _ = i.save(); - } - }; - let Some(parsed) = db.load_game(record as usize) else { - end.skipped.push((record, Skip::Unreadable)); - index_skip(Skip::Unreadable, String::new()); - progress.done.fetch_add(1, Ordering::Relaxed); - continue; - }; - let game = parsed.game; - let chess960 = db.row(record as usize).chess960; - let mut analysis = GameAnalysis::with_store(&game, Some(cache)); - if let Some(skip) = skip_of(&game, chess960) { - end.skipped.push((record, skip)); - index_skip(skip, analysis.cache_key()); - progress.done.fetch_add(1, Ordering::Relaxed); - continue; - } - let by_engine = analysis.has_data() && analysis.meta.as_ref().is_some_and(|m| m.nodes > 0); - // An analysis with every position evaluated is one, also of the engine settings - // of before (the owner's decision; `begin` would drop that one): it is taken as - // it is, the engine is not asked. - let targets = if by_engine && (analysis.stale() || analysis.missing() == 0) { - Vec::new() - } else { - analysis.begin(&game, !by_engine) - }; - if targets.is_empty() && by_engine { - end.from_cache += 1; - } else { - let mut changed = false; - let result = engine_run(engine, targets, cancel, &mut |e| { - if changed { - return; - } - if let JobEvent::Engine(name) = &e - && !(engine.fits)(name) - { - changed = true; - return; - } - analysis.apply(e); - }); - if changed { - end.outcome = Outcome::EngineFailed( - crate::i18n::tr("the engine is no longer the Stockfish 19 that was checked") - .to_owned(), - ); - break; - } - if let Err(e) = result { - end.outcome = Outcome::EngineFailed(match e { - JobFailure::Start(e) => { - eprintln!("great moves: {e}"); - crate::i18n::tr("the engine did not start").to_owned() - } - JobFailure::Engine(e) => { - eprintln!("great moves: {e}"); - crate::i18n::tr("the engine stopped answering").to_owned() - } - JobFailure::Terminated(r) => crate::analysis::termination_message(&r), - }); - break; - } - if cancel.load(Ordering::Relaxed) { - // The evaluations made are kept for later; the game is not counted. - let _ = analysis.save_to(cache); - end.outcome = Outcome::Stopped; - break; - } - if let Err(e) = analysis.save_to(cache) { - eprintln!("review cache: {e}"); - } - } - analysis.refresh(&game); - if let Ok(mut i) = index.lock() { - i.set(record, entry_of(&analysis, &game)); - if let Err(e) = i.save() { - eprintln!("marks: {e}"); - } - } - end.reviewed.push(record); - progress.done.fetch_add(1, Ordering::Relaxed); - } - progress.current.store(0, Ordering::Relaxed); - end -} - -/// Whose moves count in the totals of each record: the player of the filter's sides -/// (`white`, `black`), or both when the filter names no player. -#[derive(Clone, Debug, Default)] -pub struct Sides { - /// Records where the filter's player has White, and Black; `None`: no player. - pub player: Option<(Vec, Vec)>, -} - -impl Sides { - /// Whether White's and Black's moves of `record` count. - pub fn of(&self, record: u32) -> (bool, bool) { - match &self.player { - None => (true, true), - Some((w, b)) => ( - w.binary_search(&record).is_ok(), - b.binary_search(&record).is_ok(), - ), - } - } -} - -/// The totals of a pass: games analysed, those with !! and with !, every category -/// summed over the sides that count, the averages over those sides, and the !! moves. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Totals { - pub games: usize, - pub with_brilliant: usize, - pub with_great: usize, - pub counts: Counts, - /// Sides counted (a game counts twice when both of its sides do). - pub sides: usize, - /// Average over the sides of their average centipawn loss, and of their accuracy, - /// with the least and the greatest accuracy. - pub acpl: Option, - pub accuracy: Option, - pub accuracy_range: Option<(f64, f64)>, - /// Of them, analysed with the engine settings of before. - pub stale: usize, - /// Records where the filter's player was found on neither side. - pub player_missing: Vec, - /// Every !! of the sides that count: record and move, in the records' order. - pub brilliant: Vec<(u32, Found)>, -} - -/// Sums the index's entries of `records` over the sides that count (`sides`). -pub fn totals(index: &Index, db: &Database, records: &[u32], sides: &Sides) -> Totals { - let mut t = Totals::default(); - let (mut acpl, mut acc) = (Vec::new(), Vec::new()); - for &r in records { - let Some(e) = current_entry(index, db, r).filter(|e| e.skip.is_none()) else { - continue; - }; - let e = &e; - let (white, black) = sides.of(r); - if !white && !black { - t.player_missing.push(r); - } - let c = e.of_sides(white, black); - t.games += 1; - t.stale += usize::from(e.stale); - t.with_brilliant += usize::from(c.brilliant > 0); - t.with_great += usize::from(c.great > 0); - t.counts.add(&c); - for (counted, side) in [(white, &e.white), (black, &e.black)] { - if counted { - t.sides += 1; - acpl.extend(side.acpl.map(f64::from)); - acc.extend(side.accuracy); - } - } - t.brilliant.extend( - e.found - .iter() - .filter(|f| f.brilliant && if f.white { white } else { black }) - .map(|f| (r, f.clone())), - ); - } - let mean = |v: &[f64]| (!v.is_empty()).then(|| v.iter().sum::() / v.len() as f64); - t.acpl = mean(&acpl); - t.accuracy = mean(&acc); - t.accuracy_range = acc.iter().copied().fold(None, |r: Option<(f64, f64)>, a| { - Some(r.map_or((a, a), |(lo, hi)| (lo.min(a), hi.max(a)))) - }); - t -} - -/// The records where the filter's player has White and Black: the player condition -/// with the side fixed, without the other conditions. A selected game hidden by those -/// other conditions still keeps its player's side; a game of another player has neither. -pub fn player_sides( - db: &Database, - filter: &chess_import::chessbase::base::Filter, - cancel: &AtomicBool, -) -> Sides { - use chess_import::chessbase::base::{Side, SortKey}; - if !filter.player.is_set() { - return Sides::default(); - } - let player = chess_import::chessbase::base::Filter { - player: filter.player.clone(), - side: filter.side, - ..Default::default() - }; - let side = |s: Side| { - let f = chess_import::chessbase::base::Filter { - side: s, - ..player.clone() - }; - let mut v = db - .query(&f, SortKey::Number, true, &AtomicUsize::new(0), cancel) - .unwrap_or_default(); - v.sort_unstable(); - v - }; - let (w, b) = match filter.side { - Side::White => (side(Side::White), Vec::new()), - Side::Black => (Vec::new(), side(Side::Black)), - _ => (side(Side::White), side(Side::Black)), - }; - Sides { - player: Some((w, b)), - } -} - -/// What the app keeps of a pass for its summary: the filter, the words for its -/// conditions (or the manual source), and the games that could not be analysed. -pub type PassMeta = ( - chess_import::chessbase::base::Filter, - String, - Option, - Vec<(u32, Skip)>, -); - -/// A pass under way, on a thread of its own: its source, its list, how far it is, and -/// how it ended once it did. -pub struct PassJob { - pub source: PathBuf, - pub records: Vec, - pub selected: Option, - progress: std::sync::Arc, - cancel: std::sync::Arc, - rx: std::sync::mpsc::Receiver<(PassEnd, Sides)>, - pub stopping: bool, - pub started: std::time::Instant, -} - -impl PassJob { - /// Starts the pass over `records` of `db` (the database at `source`); the sides of - /// the filter's player are found first, in the same thread. - #[allow(clippy::too_many_arguments)] - pub fn start( - ctx: &egui::Context, - source: PathBuf, - db: std::sync::Arc, - records: Vec, - filter: chess_import::chessbase::base::Filter, - selected: Option, - index: std::sync::Arc>, - cache: PathBuf, - engine: Engine, - ) -> std::io::Result { - let progress = std::sync::Arc::new(Progress::default()); - let cancel = std::sync::Arc::new(AtomicBool::new(false)); - let (tx, rx) = std::sync::mpsc::channel(); - let (p, c, list, ctx) = ( - progress.clone(), - cancel.clone(), - records.clone(), - ctx.clone(), - ); - std::thread::Builder::new() - .name("brilliant-search".into()) - .spawn(move || { - let sides = player_sides(&db, &filter, &c); - let store = crate::review::Cache(cache); - let end = run_pass(&db, &list, &index, &store, &engine, &p, &c); - let _ = tx.send((end, sides)); - ctx.request_repaint(); - })?; - Ok(PassJob { - source, - records, - selected, - progress, - cancel, - rx, - stopping: false, - started: std::time::Instant::now(), - }) - } - - pub fn done(&self) -> usize { - self.progress.done.load(Ordering::Relaxed) - } - - /// The record being analysed. - pub fn current(&self) -> Option { - match self.progress.current.load(Ordering::Relaxed) { - 0 => None, - n => Some(n as u32 - 1), - } - } - - /// «Stop»: the engines stop within their search; what was analysed stays. - pub fn stop(&mut self) { - self.cancel.store(true, Ordering::Relaxed); - self.stopping = true; - } - - /// How it ended, once it did. - pub fn poll(&self) -> Option<(PassEnd, Sides)> { - self.rx.try_recv().ok() - } - - /// Stops and waits up to `timeout` (closing the program). - pub fn shutdown(&mut self, timeout: std::time::Duration) { - self.stop(); - let _ = self.rx.recv_timeout(timeout); - } - - /// The time left, from the pace so far after three games, else from the moves. - pub fn left_secs(&self, estimate: impl Fn(&[u32]) -> f64) -> f64 { - let done = self.done(); - let rest = &self.records[done.min(self.records.len())..]; - if done >= 3 { - self.started.elapsed().as_secs_f64() / done as f64 * rest.len() as f64 - } else { - estimate(rest) - } - } -} - -impl Drop for PassJob { - fn drop(&mut self) { - self.cancel.store(true, Ordering::Relaxed); - } -} - -/// Seconds per position of one engine process, with the second search of !! and !: -/// measured, 3 games of 170 plies in 44 s in 8 processes (i7-13700KF, -/// docs/qa/task-27-functional-2026-11-27.md). -const SECS_PER_POSITION: f64 = 2.0; - -/// Seconds an engine takes for games of these many plies over `processes`: the same in -/// the question and in the progress until three games are done. -pub fn estimate_secs(plies: impl Iterator, processes: usize) -> f64 { - plies - .map(|p| (p + 1) as f64 * SECS_PER_POSITION) - .sum::() - / processes.max(1) as f64 -} - -/// «less than a minute», «about 14 min», «about 1 h 20 min». -pub fn format_estimate(secs: f64) -> String { - if secs < 60.0 { - return crate::i18n::tr("less than a minute").to_owned(); - } - let min = (secs / 60.0).round() as u64; - if min < 60 { - crate::i18n::trf("about {n} min", &[("n", &min)]) - } else { - crate::i18n::trf( - "about {h} h {m} min", - &[("h", &(min / 60)), ("m", &(min % 60))], - ) - } -} - -#[cfg(test)] -#[path = "brilliant_tests.rs"] -mod tests; diff --git a/apps/desktop/src/brilliant_tests.rs b/apps/desktop/src/brilliant_tests.rs deleted file mode 100644 index 3cca246..0000000 --- a/apps/desktop/src/brilliant_tests.rs +++ /dev/null @@ -1,617 +0,0 @@ -use std::sync::Arc; - -use game_review::CacheDir; - -use super::*; - -struct Dir(PathBuf); - -impl Dir { - fn new(name: &str) -> Dir { - let path = std::env::temp_dir().join(format!("cp-brilliant-{}-{name}", std::process::id())); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(path.join("cache")).unwrap(); - Dir(path) - } - - fn cache(&self) -> PathBuf { - self.0.join("cache") - } -} - -impl Drop for Dir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -/// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). -fn fake() -> PathBuf { - let fake = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/debug/fake_uci"); - assert!( - fake.exists(), - "build the fake engine first: cargo build -p uci --bin fake_uci" - ); - fake -} - -fn engine_at(path: &Path) -> Engine { - Engine { - config: uci::EngineConfig { - // The second search of !! and ! (`searchmoves`), as Stockfish makes it. - args: vec!["--searchmoves".into()], - ..uci::EngineConfig::new(path) - }, - settings: JobSettings::new(2, None), - fits: Box::new(|_| true), - pause: std::time::Duration::ZERO, - } -} - -/// An engine that cannot start: a pass that asks for it fails. -fn no_engine(dir: &Dir) -> Engine { - engine_at(&dir.0.join("no-such-engine")) -} - -const GAMES: &str = "[White \"Carlsen\"]\n[Black \"Kasparov\"]\n[Result \"*\"]\n\n1. e4 e5 2. Nf3 Nc6 *\n\n\ -[White \"Kasparov\"]\n[Black \"Carlsen\"]\n[Result \"*\"]\n\n1. d4 d5 2. c4 *\n\n\ -[White \"Anand\"]\n[Black \"Topalov\"]\n[Result \"*\"]\n\n1. e4 -- 2. d4 *\n\n\ -[White \"Anand\"]\n[Black \"Kramnik\"]\n[Result \"*\"]\n\n*\n"; - -fn source(dir: &Dir) -> (PathBuf, Database) { - let path = dir.0.join("games.pgn"); - std::fs::write(&path, GAMES).unwrap(); - let db = chess_import::open(&path, &mut |_| {}, &AtomicBool::new(false)) - .unwrap() - .db; - (path, db) -} - -fn pass( - db: &Database, - records: &[u32], - index: &Mutex, - dir: &Dir, - engine: &Engine, -) -> PassEnd { - let cache = dir.cache(); - run_pass( - db, - records, - index, - &CacheDir(&cache), - engine, - &Progress::default(), - &AtomicBool::new(false), - ) -} - -#[test] -fn the_limit_is_one_hundred_games_inclusive() { - assert_eq!(can_start(0), Err(Blocked::NoGames)); - assert_eq!(can_start(1), Ok(())); - assert_eq!(can_start(LIMIT), Ok(())); - assert_eq!(LIMIT, 100); - assert_eq!(can_start(101), Err(Blocked::TooMany)); -} - -#[test] -fn a_pass_analyses_keeps_the_index_and_takes_the_cache_next_time() { - let dir = Dir::new("pass"); - let (path, db) = source(&dir); - let before = std::fs::read(&path).unwrap(); - let file = dir.0.join("marks.json"); - let index = Mutex::new(Index::load(file.clone())); - let end = pass(&db, &[0, 1, 2, 3], &index, &dir, &engine_at(&fake())); - assert_eq!(end.outcome, Outcome::Finished); - assert_eq!(end.reviewed, vec![0, 1]); - assert_eq!(end.from_cache, 0); - assert_eq!(end.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]); - // The index lives on: read anew (as after a restart) it has every record. - let again = Index::load(file.clone()); - assert_eq!(again.len(), 4); - let entry = again.get(0).unwrap(); - let game = db.load_game(0).unwrap().game; - assert_eq!(entry.line, GameAnalysis::new(&game, None).cache_key()); - assert_eq!(again.get(2).unwrap().skip, Some(Skip::NullMove)); - // Again: from the cache, the engine is not asked (there is none now). - let index = Mutex::new(again); - let end = pass(&db, &[1, 0], &index, &dir, &no_engine(&dir)); - assert_eq!(end.outcome, Outcome::Finished); - assert_eq!((end.reviewed, end.from_cache), (vec![1, 0], 2)); - // The source is only read. - assert_eq!(std::fs::read(&path).unwrap(), before); -} - -#[test] -fn an_analysis_of_the_settings_of_before_counts_as_made() { - let dir = Dir::new("stale"); - let (_, db) = source(&dir); - let index = Mutex::new(Index::load(dir.0.join("marks.json"))); - pass(&db, &[0], &index, &dir, &engine_at(&fake())); - // The cached analysis made «before the fixed search». - for f in std::fs::read_dir(dir.cache()).unwrap() { - let f = f.unwrap().path(); - let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap(); - v["meta"]["search"] = serde_json::json!(0); - std::fs::write(&f, serde_json::to_vec(&v).unwrap()).unwrap(); - } - let end = pass(&db, &[0], &index, &dir, &no_engine(&dir)); - assert_eq!((end.outcome, end.from_cache), (Outcome::Finished, 1)); - assert!(index.lock().unwrap().get(0).unwrap().stale); -} - -#[test] -fn a_stopped_pass_keeps_what_it_analysed() { - let dir = Dir::new("stop"); - let (_, db) = source(&dir); - let file = dir.0.join("marks.json"); - let index = Mutex::new(Index::load(file.clone())); - // Stopped when the second game's engine starts: the first one is kept. - let cancel = Arc::new(AtomicBool::new(false)); - let starts = Arc::new(AtomicUsize::new(0)); - let (c, s) = (cancel.clone(), starts.clone()); - let engine = Engine { - fits: Box::new(move |_| { - if s.fetch_add(1, Ordering::Relaxed) >= 1 { - c.store(true, Ordering::Relaxed); - } - true - }), - ..engine_at(&fake()) - }; - let cache = dir.cache(); - let end = run_pass( - &db, - &[0, 1], - &index, - &CacheDir(&cache), - &engine, - &Progress::default(), - &cancel, - ); - assert_eq!(end.outcome, Outcome::Stopped); - assert_eq!(end.reviewed, vec![0]); - let kept = Index::load(file); - assert!(kept.get(0).is_some() && kept.get(1).is_none()); -} - -#[test] -fn starting_and_stopping_at_once_never_breaks_the_index() { - let dir = Dir::new("race"); - let (_, db) = source(&dir); - let db = Arc::new(db); - let file = dir.0.join("marks.json"); - for round in 0..10 { - let index = Arc::new(Mutex::new(Index::load(file.clone()))); - let cancel = Arc::new(AtomicBool::new(false)); - let (d, i, c, cache) = (db.clone(), index.clone(), cancel.clone(), dir.cache()); - let worker = std::thread::spawn(move || { - run_pass( - &d, - &[0, 1, 2, 3], - &i, - &CacheDir(&cache), - &engine_at(&fake()), - &Progress::default(), - &c, - ) - }); - if round % 2 == 0 { - std::thread::yield_now(); - } - cancel.store(true, Ordering::Relaxed); - let end = worker.join().unwrap(); - assert!(matches!(end.outcome, Outcome::Stopped | Outcome::Finished)); - // The file is whole: it reads. - if file.exists() { - let bytes = std::fs::read(&file).unwrap(); - assert!(serde_json::from_slice::(&bytes).is_ok()); - } - } -} - -#[test] -fn a_broken_index_is_an_empty_one() { - let dir = Dir::new("broken"); - let file = dir.0.join("marks.json"); - std::fs::write(&file, b"{not json").unwrap(); - assert_eq!(Index::load(file.clone()).len(), 0); - std::fs::write(&file, br#"{"version":99,"records":[]}"#).unwrap(); - assert_eq!(Index::load(file).len(), 0); - assert_eq!(Index::load(dir.0.join("none.json")).len(), 0); -} - -/// The entries of `index` made the database's own: their main lines are those of its -/// games (as a pass writes them). -fn fit(index: &mut Index, db: &Database) { - let records: Vec = index.records().collect(); - for r in records { - let mut e = index.get(r).unwrap().clone(); - e.line = GameAnalysis::new(&db.load_game(r as usize).unwrap().game, None).cache_key(); - index.set(r, e); - } -} - -fn side(brilliant: u32, great: u32, blunders: u32, acpl: u32, accuracy: f64) -> SideMarks { - SideMarks { - counts: Counts { - brilliant, - great, - blunders, - ..Counts::default() - }, - acpl: Some(acpl), - accuracy: Some(accuracy), - } -} - -fn found(ply: u16, white: bool, number: u32, san: &str, brilliant: bool) -> Found { - Found { - ply, - white, - number, - san: san.into(), - brilliant, - } -} - -#[test] -fn totals_count_only_the_filters_players_moves() { - let mut index = Index::default(); - let entry = |white, black, found| Entry { - line: String::new(), - white, - black, - found, - stale: false, - skip: None, - }; - index.set( - 0, - entry( - side(1, 0, 0, 20, 90.0), - side(0, 2, 1, 40, 70.0), - vec![ - found(40, true, 21, "Rxf7", true), - found(13, false, 7, "Nd5", false), - ], - ), - ); - index.set( - 1, - entry( - side(0, 0, 3, 60, 60.0), - side(1, 1, 0, 10, 96.0), - vec![found(67, false, 34, "Nf3+", true)], - ), - ); - index.set( - 2, - Entry { - skip: Some(Skip::Chess960), - ..entry(SideMarks::default(), SideMarks::default(), Vec::new()) - }, - ); - let dir = Dir::new("totals"); - let (_, db) = source(&dir); - fit(&mut index, &db); - let all = totals(&index, &db, &[0, 1, 2], &Sides::default()); - assert_eq!( - (all.games, all.sides, all.with_brilliant, all.with_great), - (2, 4, 2, 2) - ); - assert_eq!( - all.counts, - Counts { - brilliant: 2, - great: 3, - blunders: 4, - ..Counts::default() - } - ); - assert_eq!(all.acpl, Some(32.5)); - assert_eq!(all.accuracy_range, Some((60.0, 96.0))); - assert_eq!(all.brilliant.len(), 2); - // The player had White in game 0 and Black in game 1: only those sides count. - let player = Sides { - player: Some((vec![0], vec![1])), - }; - let t = totals(&index, &db, &[0, 1, 2], &player); - assert_eq!( - (t.games, t.sides, t.with_brilliant, t.with_great), - (2, 2, 2, 1) - ); - assert_eq!(t.counts.blunders, 0); - assert_eq!(t.acpl, Some(15.0)); - assert_eq!(t.accuracy, Some(93.0)); - assert_eq!( - t.brilliant - .iter() - .map(|(r, f)| (*r, f.label())) - .collect::>(), - [(0, "21.Rxf7!!".to_owned()), (1, "34…Nf3+!!".to_owned())] - ); - // A player found on neither side is said. - let nobody = Sides { - player: Some((Vec::new(), Vec::new())), - }; - assert_eq!( - totals(&index, &db, &[0, 1], &nobody).player_missing, - vec![0, 1] - ); -} - -#[test] -fn the_players_sides_come_from_the_filter() { - let dir = Dir::new("sides"); - let (_, db) = source(&dir); - let filter = chess_import::chessbase::base::Filter { - player: chess_import::chessbase::base::NameFilter { - text: "carlsen".into(), - exact: None, - }, - ..Default::default() - }; - let sides = player_sides(&db, &filter, &AtomicBool::new(false)); - assert_eq!(sides.player, Some((vec![0], vec![1]))); - assert!( - player_sides(&db, &Default::default(), &AtomicBool::new(false)) - .player - .is_none() - ); - let quick_search = chess_import::chessbase::base::Filter { - text: "carlsen".into(), - ..Default::default() - }; - assert!( - player_sides(&db, &quick_search, &AtomicBool::new(false)) - .player - .is_none() - ); -} - -#[test] -fn a_selected_game_hidden_by_another_condition_keeps_its_players_side() { - let dir = Dir::new("hidden-sides"); - let (_, db) = source(&dir); - let filter = chess_import::chessbase::base::Filter { - player: chess_import::chessbase::base::NameFilter { - text: "carlsen".into(), - exact: None, - }, - // None of the sample games has a year, so the filtered table is empty. The - // manually selected Carlsen games nevertheless retain White and Black. - year_from: Some(2020), - ..Default::default() - }; - let sides = player_sides(&db, &filter, &AtomicBool::new(false)); - assert_eq!(sides.player, Some((vec![0], vec![1]))); - assert_eq!(sides.of(0), (true, false)); - assert_eq!(sides.of(1), (false, true)); - assert_eq!(sides.of(2), (false, false)); - - let mut white = filter.clone(); - white.side = chess_import::chessbase::base::Side::White; - assert_eq!( - player_sides(&db, &white, &AtomicBool::new(false)).player, - Some((vec![0], Vec::new())) - ); - let mut black = filter; - black.side = chess_import::chessbase::base::Side::Black; - assert_eq!( - player_sides(&db, &black, &AtomicBool::new(false)).player, - Some((Vec::new(), vec![1])) - ); -} - -/// White found a !! and Black a !: the row of a filter on the Black player shows !. -fn two_sided() -> Index { - let mut index = Index::default(); - index.set( - 0, - Entry { - line: String::new(), - white: side(1, 0, 0, 10, 95.0), - black: side(0, 1, 2, 40, 70.0), - found: vec![ - found(20, true, 11, "Rxf7", true), - found(23, false, 12, "Nd5", false), - ], - stale: false, - skip: None, - }, - ); - index.set( - 1, - Entry { - found: Vec::new(), - ..index.get(0).unwrap().clone() - }, - ); - index -} - -#[test] -fn the_column_counts_only_the_filters_players_moves() { - let index = two_sided(); - let any = |_| true; - let both = Sides::default(); - let black = Sides { - player: Some((Vec::new(), vec![0])), - }; - assert_eq!(index.rank(0, &both, &any), 0); - assert_eq!(index.rank(0, &black, &any), 1); - // A game where the player is on neither side has nothing of his. - assert_eq!(index.rank(1, &black, &any), 2); - let e = index.get(0).unwrap().for_sides(false, true); - assert_eq!(e.of_sides(true, true).brilliant, 0); - assert_eq!(e.of_sides(true, true).great, 1); - assert_eq!( - e.found.iter().map(Found::label).collect::>(), - ["12…Nd5!"] - ); -} - -#[test] -fn the_summary_keeps_the_original_snapshot_and_player_for_continue() { - let dir = Dir::new("summary"); - let (path, db) = source(&dir); - let filter = chess_import::chessbase::base::Filter { - player: chess_import::chessbase::base::NameFilter { - text: "carlsen".into(), - exact: None, - }, - ..Default::default() - }; - let sides = player_sides(&db, &filter, &AtomicBool::new(false)); - let mut index = two_sided(); - fit(&mut index, &db); - let mut original = vec![0, 1, 2]; - let selected = Some(SelectedGames { - games: 3, - hidden: 1, - }); - // Record 0: Carlsen has White (its !!); record 1: Carlsen has Black (a !). - let summary = crate::brilliant_ui::Summary::new( - &path, - &db, - &index, - &original, - &sides, - &filter, - String::new(), - selected, - Some((2, 3)), - Vec::new(), - ); - // A later live selection has new records: neither the new record nor the changed - // order can enter the continuation held by this summary. - original.clear(); - original.push(3); - assert_eq!(summary.filter, filter); - assert_eq!(summary.rest, vec![2]); - assert_eq!(summary.selected_games, selected); - assert_eq!( - (summary.totals.counts.brilliant, summary.totals.counts.great), - (1, 1) - ); - assert_eq!(summary.totals.counts.blunders, 2); - assert_eq!(summary.player, Some(("carlsen".to_owned(), 1, 1))); - assert_eq!(summary.rows.len(), 1); -} - -const FIVE: &str = "[White \"A\"]\n[Black \"B\"]\n[Result \"*\"]\n\n1. e4 e5 *\n\n\ -[White \"C\"]\n[Black \"D\"]\n[Result \"*\"]\n\n1. d4 d5 *\n\n\ -[White \"E\"]\n[Black \"F\"]\n[Result \"*\"]\n\n1. c4 e5 *\n\n\ -[White \"G\"]\n[Black \"H\"]\n[Result \"*\"]\n\n1. Nf3 d5 *\n\n\ -[White \"I\"]\n[Black \"J\"]\n[Result \"*\"]\n\n1. g3 g6 *\n"; - -/// A game deleted (the 2nd of 5): the records after it take other numbers, and none of -/// them lends another game's marks — not in the summary, not in the sort; asked again, -/// the entries are made anew from the cache. -#[test] -fn a_deleted_game_never_lends_its_marks() { - let dir = Dir::new("deleted"); - let path = dir.0.join("five.pgn"); - std::fs::write(&path, FIVE).unwrap(); - let open = |p: &Path| { - chess_import::open(p, &mut |_| {}, &AtomicBool::new(false)) - .unwrap() - .db - }; - let db = open(&path); - let file = dir.0.join("marks.json"); - let index = Mutex::new(Index::load(file.clone())); - pass(&db, &[0, 1, 2, 3, 4], &index, &dir, &engine_at(&fake())); - // Each game marked: a !! of its own, told apart by its number. - { - let mut i = index.lock().unwrap(); - for r in 0..5u32 { - let mut e = i.get(r).unwrap().clone(); - e.white.counts.brilliant = 1; - e.found = vec![found(0, true, r + 1, "x", true)]; - i.set(r, e); - } - i.save().unwrap(); - } - let without_second: String = FIVE - .split("\n\n[") - .enumerate() - .filter(|(i, _)| *i != 1) - .map(|(i, g)| { - if i == 0 { - g.to_owned() - } else { - format!("[{g}") - } - }) - .collect::>() - .join("\n\n"); - std::fs::write(&path, without_second).unwrap(); - let db = open(&path); - assert_eq!(db.len(), 4); - let i = index.lock().unwrap(); - let t = totals(&i, &db, &[0, 1, 2, 3], &Sides::default()); - assert_eq!(t.games, 1); - assert_eq!( - t.brilliant - .iter() - .map(|(_, f)| f.number) - .collect::>(), - [1] - ); - assert!(current_entry(&i, &db, 1).is_none()); - assert_eq!( - i.rank(1, &Sides::default(), &|r| current_entry(&i, &db, r) - .is_some()), - 4 - ); - drop(i); - // «Find» again: counted from the cache, the entries are the games' own again. - let cache = dir.cache(); - let c = crate::brilliant_ui::count( - &db, - &[0, 1, 2, 3], - &Default::default(), - &cache, - &index, - &AtomicBool::new(false), - ); - assert_eq!(c.reviewed, vec![0, 1, 2, 3]); - let i = index.lock().unwrap(); - assert_eq!(totals(&i, &db, &[0, 1, 2, 3], &Sides::default()).games, 4); -} - -/// Games that cannot be analysed get «—» with the reason in the index. -#[test] -fn games_not_analysable_get_their_reason() { - let dir = Dir::new("skips"); - let (_, db) = source(&dir); - let index = Mutex::new(Index::load(dir.0.join("marks.json"))); - let c = crate::brilliant_ui::count( - &db, - &[2, 3], - &Default::default(), - &dir.cache(), - &index, - &AtomicBool::new(false), - ); - assert_eq!(c.skipped, vec![(2, Skip::NullMove), (3, Skip::NoMoves)]); - let i = index.lock().unwrap(); - assert_eq!( - current_entry(&i, &db, 2).unwrap().skip, - Some(Skip::NullMove) - ); - assert_eq!(i.get(3).unwrap().skip, Some(Skip::NoMoves)); -} - -#[test] -fn estimates_are_said_plainly() { - assert_eq!(format_estimate(30.0), "less than a minute"); - assert_eq!(format_estimate(14.0 * 60.0), "about 14 min"); - assert_eq!(format_estimate(80.0 * 60.0), "about 1 h 20 min"); - // The tester's measure: 3 games of 170 plies in 8 processes, 44 s. - let secs = estimate_secs([56, 57, 57].into_iter(), 8); - assert!((40.0..48.0).contains(&secs), "{secs}"); -} diff --git a/apps/desktop/src/brilliant_ui.rs b/apps/desktop/src/brilliant_ui.rs deleted file mode 100644 index b37c07e..0000000 --- a/apps/desktop/src/brilliant_ui.rs +++ /dev/null @@ -1,776 +0,0 @@ -//! The windows of the search for great moves (task 27, -//! docs/design/task-27-brilliant-search-2026-11-27.md): the question before a pass -//! (§4.4) and the summary after it (§4.9). - -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{Receiver, channel}; - -use chess_import::Database; -use chess_import::chessbase::base::Filter; -use egui::{Key, RichText}; -use game_review::{GameAnalysis, Judgement}; - -use crate::brilliant::{Found, Index, SelectedGames, Sides, Skip, Totals}; -use crate::i18n::{tr, trf}; - -/// What a list holds before a pass: the records already analysed, those to analyse with -/// their plies, those that cannot be, and the sides of the filter's player. -pub struct Counted { - pub reviewed: Vec, - pub left: Vec, - pub plies_left: Vec, - pub skipped: Vec<(u32, Skip)>, - pub sides: Sides, -} - -/// Counts what of `records` is analysed (the analysis cache in `cache`), on this thread. -/// The index follows: a game analysed whose entry is missing or belongs to another game -/// (one deleted or changed) gets its entry anew from the cache, a game that cannot be -/// analysed gets «—» with the reason. -pub fn count( - db: &Database, - records: &[u32], - filter: &Filter, - cache: &Path, - index: &std::sync::Mutex, - cancel: &AtomicBool, -) -> Counted { - let store = crate::review::Cache(cache.to_path_buf()); - let mut c = Counted { - reviewed: Vec::new(), - left: Vec::new(), - plies_left: Vec::new(), - skipped: Vec::new(), - sides: crate::brilliant::player_sides(db, filter, cancel), - }; - for &r in records { - if cancel.load(Ordering::Relaxed) { - break; - } - let set = |entry: crate::brilliant::Entry| { - if let Ok(mut i) = index.lock() - && i.get(r) != Some(&entry) - { - i.set(r, entry); - let _ = i.save(); - } - }; - let Some(parsed) = db.load_game(r as usize) else { - c.skipped.push((r, Skip::Unreadable)); - set(crate::brilliant::skipped_entry( - String::new(), - Skip::Unreadable, - )); - continue; - }; - let mut a = GameAnalysis::with_store(&parsed.game, Some(&store)); - if let Some(skip) = crate::brilliant::skip_of(&parsed.game, db.row(r as usize).chess960) { - c.skipped.push((r, skip)); - set(crate::brilliant::skipped_entry(a.cache_key(), skip)); - continue; - } - let by_engine = a.has_data() && a.meta.as_ref().is_some_and(|m| m.nodes > 0); - if by_engine && (a.stale() || a.missing() == 0) { - c.reviewed.push(r); - a.refresh(&parsed.game); - set(crate::brilliant::entry_of(&a, &parsed.game)); - } else { - c.left.push(r); - c.plies_left.push(parsed.game.mainline().len()); - } - } - c -} - -/// The question before a pass. -pub struct StartDialog { - pub source: PathBuf, - pub records: Vec, - pub filter: Filter, - pub about: String, - pub selected: Option, - rx: Receiver, - cancel: Arc, - pub counted: Option, -} - -pub enum StartOutcome { - Start, - /// Every game is analysed already, or «Summary of the reviewed». - Summary, - Cancel, -} - -/// One of the three fixed-height source rows: empty rows keep their place. -fn source_line(ui: &mut egui::Ui, text: &str, weak: bool, hover: Option<&str>) { - if text.is_empty() { - return; - } - let text = RichText::new(text).size(12.0); - let text = if weak { text.weak() } else { text }; - let response = ui.add(egui::Label::new(text).truncate()); - if let Some(hover) = hover { - response.on_hover_text(hover); - } -} - -impl StartDialog { - #[allow(clippy::too_many_arguments)] - pub fn new( - ctx: &egui::Context, - source: PathBuf, - db: Arc, - records: Vec, - filter: Filter, - about: String, - selected: Option, - cache: PathBuf, - index: Arc>, - ) -> StartDialog { - let (tx, rx) = channel(); - let cancel = Arc::new(AtomicBool::new(false)); - let (list, f, c, ctx) = (records.clone(), filter.clone(), cancel.clone(), ctx.clone()); - let _ = std::thread::Builder::new() - .name("brilliant-count".into()) - .spawn(move || { - let _ = tx.send(count(&db, &list, &f, &cache, &index, &c)); - ctx.request_repaint(); - }); - StartDialog { - source, - records, - filter, - about, - selected, - rx, - cancel, - counted: None, - } - } - - pub fn show(&mut self, ctx: &egui::Context) -> Option { - if self.counted.is_none() - && let Ok(c) = self.rx.try_recv() - { - // All analysed: no question, the summary at once. - if c.left.is_empty() { - self.counted = Some(c); - return Some(StartOutcome::Summary); - } - self.counted = Some(c); - } - let mut out = None; - let name = crate::own_db::base_name(&self.source); - egui::Window::new(tr("Find great moves")) - .id(egui::Id::new("brilliant_start")) - .collapsible(false) - .resizable(false) - .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO) - .default_width(520.0) - .show(ctx, |ui| { - ui.set_width(520.0); - let (source, hidden) = match self.selected { - Some(selected) => ( - trf( - "Selected: {games}", - &[("games", &crate::i18n::games(selected.games))], - ), - (selected.hidden > 0).then(|| { - trf( - "{k} hidden by the current filter", - &[("k", &crate::large_db::grouped(selected.hidden))], - ) - }), - ), - None => ( - format!( - "{} · {}", - crate::i18n::games(self.records.len()), - self.about - ), - None, - ), - }; - let player = (self.selected.is_some() && self.filter.player.is_set()).then(|| { - let name = self.filter.player.text.trim(); - match self.filter.side { - chess_import::chessbase::base::Side::White => trf( - "Only the moves of «{name}» as White count.", - &[("name", &name)], - ), - chess_import::chessbase::base::Side::Black => trf( - "Only the moves of «{name}» as Black count.", - &[("name", &name)], - ), - _ => trf("Only the moves of «{name}» count.", &[("name", &name)]), - } - }); - for (text, weak, hover) in [ - (format!("{name} · {source}"), true, None), - (hidden.unwrap_or_default(), true, None), - ( - player.unwrap_or_default(), - false, - self.filter.player.is_set().then(|| { - tr( - "The player condition limits the moves counted, but does not exclude selected games from review.", - ) - }), - ), - ] { - ui.allocate_ui(egui::vec2(520.0, 18.0), |ui| { - source_line(ui, &text, weak, hover); - }); - } - ui.add_space(8.0); - // Two lines kept for the counts: the window does not jump when they come. - ui.allocate_ui(egui::vec2(520.0, 60.0), |ui| match &self.counted { - None => { - ui.horizontal(|ui| { - ui.spinner(); - ui.label(tr("Counting the games already reviewed…")); - }); - } - Some(c) => { - let secs = crate::brilliant::estimate_secs( - c.plies_left.iter().copied(), - crate::review::processes(), - ); - ui.label(trf( - "The engine will review {games} — {time}.", - &[ - ("games", &crate::i18n::games_object(c.left.len())), - ("time", &crate::brilliant::format_estimate(secs)), - ], - )); - if !c.reviewed.is_empty() { - let key = if crate::i18n::is_one(c.reviewed.len()) { - "{games} is already reviewed: its marks come from the saved review." - } else { - "{games} are already reviewed: their marks come from the saved review." - }; - ui.label(trf(key, &[("games", &crate::i18n::games(c.reviewed.len()))])); - } - // Why the list here is shorter than the table's. - if !c.skipped.is_empty() { - let mut reasons: Vec<&str> = - c.skipped.iter().map(|(_, s)| s.reason()).collect(); - reasons.sort_unstable(); - reasons.dedup(); - ui.label( - RichText::new(trf( - "{k} cannot be reviewed ({reason})", - &[("k", &c.skipped.len()), ("reason", &reasons.join(", "))], - )) - .weak(), - ); - } - } - }); - ui.add_space(6.0); - ui.label(trf( - "The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.", - &[("p", &crate::review::processes())], - )); - ui.add_space(8.0); - // Its own height, not the window's: the buttons sit under the text. - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let ready = self.counted.is_some(); - let start = ui.add_enabled(ready, egui::Button::new(tr("Start"))); - if start.clicked() || (ready && ui.input(|i| i.key_pressed(Key::Enter))) { - out = Some(StartOutcome::Start); - } - if ui.button(tr("Cancel")).clicked() { - out = Some(StartOutcome::Cancel); - } - if let Some(c) = &self.counted - && !c.reviewed.is_empty() - && ui - .button(trf( - "Summary of the reviewed ({k})", - &[("k", &c.reviewed.len())], - )) - .clicked() - { - out = Some(StartOutcome::Summary); - } - }); - }); - }); - if out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape)) { - out = Some(StartOutcome::Cancel); - } - out - } -} - -impl Drop for StartDialog { - fn drop(&mut self) { - self.cancel.store(true, Ordering::Relaxed); - } -} - -/// A row of the summary's list: a !! move of a game. -pub struct BrilliantRow { - pub record: u32, - pub found: Found, - /// «White — Black · result · event · date». - pub game: String, -} - -/// The summary of a pass (§4.9), counted anew from the index for the pass's list. -pub struct Summary { - pub source: PathBuf, - pub about: String, - pub selected_games: Option, - pub totals: Totals, - /// The filter's player and the games counted for each colour. - pub player: Option<(String, usize, usize)>, - /// Stopped: analysed of all. - pub stopped: Option<(usize, usize)>, - /// Not analysed (for «Continue»). - pub rest: Vec, - pub skipped: Vec<(u32, Skip)>, - pub rows: Vec, - pub selected: Option, - /// The pass's filter: «Continue» goes on with it (its player's moves only). - pub filter: Filter, -} - -pub enum SummaryAction { - /// The game of a row chosen in the table behind. - Select(u32), - /// Open the game at the position after the move. - Open { - record: u32, - ply: u16, - }, - Continue { - records: Vec, - filter: Box, - }, - /// Sort the table by the «!!» column. - Sort, - Close, -} - -impl Summary { - /// The summary of `records` (a pass's list, in its order) from `index`. - #[allow(clippy::too_many_arguments)] - pub fn new( - source: &Path, - db: &Database, - index: &Index, - records: &[u32], - sides: &Sides, - filter: &Filter, - about: String, - selected: Option, - stopped: Option<(usize, usize)>, - skipped: Vec<(u32, Skip)>, - ) -> Summary { - let totals = crate::brilliant::totals(index, db, records, sides); - let rest = records - .iter() - .copied() - .filter(|r| crate::brilliant::current_entry(index, db, *r).is_none()) - .collect(); - let player = sides.player.as_ref().map(|(w, b)| { - let count = |v: &Vec| { - records - .iter() - .filter(|r| v.binary_search(r).is_ok()) - .count() - }; - (filter.player.text.trim().to_owned(), count(w), count(b)) - }); - let rows = totals - .brilliant - .iter() - .map(|(r, f)| { - let row = db.row(*r as usize); - let mut parts = vec![format!("{} — {}", row.white, row.black)]; - parts.push(row.result.to_string()); - if !row.event.trim().is_empty() && row.event != "?" { - parts.push(row.event.to_string()); - } - let date = crate::library::display_date(&row.date); - if !date.is_empty() { - parts.push(date); - } - BrilliantRow { - record: *r, - found: f.clone(), - game: parts.join(" · "), - } - }) - .collect(); - Summary { - source: source.to_path_buf(), - about, - selected_games: selected, - totals, - player, - stopped, - rest, - skipped, - rows, - selected: None, - filter: filter.clone(), - } - } - - pub fn show(&mut self, ctx: &egui::Context) -> Option { - let mut out = None; - // `CP_SUMMARY_CONTINUE=1`, `CP_SUMMARY_OPEN=`: «Continue», or the i-th move of - // «Games with !!» opened, once (checks without a mouse). - static HOOK: std::sync::Once = std::sync::Once::new(); - let mut hook = None; - HOOK.call_once(|| { - if std::env::var_os("CP_SUMMARY_CONTINUE").is_some() && !self.rest.is_empty() { - hook = Some(SummaryAction::Continue { - records: self.rest.clone(), - filter: Box::new(self.filter.clone()), - }); - } else if let Some(row) = std::env::var("CP_SUMMARY_OPEN") - .ok() - .and_then(|i| i.parse::().ok()) - .and_then(|i| self.rows.get(i)) - { - hook = Some(SummaryAction::Open { - record: row.record, - ply: row.found.ply, - }); - } - }); - if hook.is_some() { - return hook; - } - let mut open = true; - let t = &self.totals; - let title = match self.stopped { - Some((i, n)) if crate::i18n::is_one(i) => trf( - "Search stopped · reviewed: {i} of {n} game", - &[("i", &i), ("n", &n)], - ), - Some((i, n)) => trf( - "Search stopped · reviewed: {i} of {n}", - &[("i", &i), ("n", &n)], - ), - None => trf( - "Summary · reviewed: {games}", - &[("games", &crate::i18n::games(t.games))], - ), - }; - let width = (ctx.content_rect().width() - 40.0).min(600.0); - egui::Window::new(title) - .id(egui::Id::new("brilliant_summary")) - // In the middle: the «!!» column it sums up stays in sight. - .pivot(egui::Align2::CENTER_CENTER) - .default_pos(ctx.content_rect().center()) - .open(&mut open) - .collapsible(false) - .resizable(false) - .default_width(width) - .max_height(ctx.content_rect().height() - 80.0) - .show(ctx, |ui| { - ui.set_width(width); - let weak = |ui: &mut egui::Ui, text: String| { - ui.add(egui::Label::new(RichText::new(text).weak().size(12.0)).truncate()) - }; - let about = match self.selected_games { - Some(selected) => trf( - "Selected: {games}", - &[("games", &crate::i18n::games(selected.games))], - ), - None => self.about.clone(), - }; - let subtitle = weak( - ui, - format!("{} · {about}", crate::own_db::base_name(&self.source)), - ); - if let Some(selected) = self.selected_games - && selected.hidden > 0 - { - subtitle.on_hover_text(trf( - "Hidden by the filter at start: {k}", - &[("k", &crate::large_db::grouped(selected.hidden))], - )); - } - if let Some((name, w, b)) = &self.player { - weak( - ui, - trf( - "Only the moves of «{name}» count: as White {w}, as Black {b}", - &[("name", name), ("w", w), ("b", b)], - ), - ); - } - if !self.skipped.is_empty() { - let reasons: Vec<&str> = { - let mut r: Vec<&str> = self.skipped.iter().map(|(_, s)| s.reason()).collect(); - r.sort_unstable(); - r.dedup(); - r - }; - weak( - ui, - trf( - "Not reviewed: {k} ({reason})", - &[("k", &self.skipped.len()), ("reason", &reasons.join(", "))], - ), - ); - } - if t.stale > 0 { - weak( - ui, - trf( - "{k} of them were reviewed with the previous engine settings", - &[("k", &t.stale)], - ), - ); - } - if !t.player_missing.is_empty() { - let numbers: Vec = - t.player_missing.iter().map(|r| (r + 1).to_string()).collect(); - ui.add( - egui::Label::new( - RichText::new(trf( - "In {k} games the player was not found by name: their moves did not count", - &[("k", &t.player_missing.len())], - )) - .weak() - .size(12.0), - ) - .truncate(), - ) - .on_hover_text(numbers.join(", ")); - } - if self.stopped.is_some() && !self.rest.is_empty() { - weak( - ui, - trf( - "{k} games are not reviewed: «Continue» reviews only them", - &[("k", &self.rest.len())], - ), - ); - } - ui.add_space(8.0); - let dark = ui.visuals().dark_mode; - egui::Grid::new("brilliant_totals") - .num_columns(2) - .spacing([12.0, 4.0]) - .show(ui, |ui| { - let c = &t.counts; - for (j, n) in [ - (Judgement::Brilliant, c.brilliant), - (Judgement::Great, c.great), - (Judgement::Inaccuracy, c.inaccuracies), - (Judgement::Mistake, c.mistakes), - (Judgement::Blunder, c.blunders), - ] { - let color = if n == 0 { - ui.visuals().weak_text_color() - } else { - crate::review::judgement_text_color(j, dark) - }; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(RichText::new(n.to_string()).strong().size(15.0).color(color)); - }); - ui.label( - RichText::new(crate::review::judgement_plural(j)) - .size(15.0) - .color(color), - ); - ui.end_row(); - } - let shown = |v: Option| v.unwrap_or_else(|| "—".to_owned()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label( - RichText::new(shown(t.acpl.map(|a| format!("{}", a.round() as i64)))) - .strong() - .size(15.0), - ); - }); - ui.label(RichText::new(tr("Average centipawn loss")).size(15.0)); - ui.end_row(); - let color = t - .accuracy - .map(|a| crate::review::accuracy_color(a, dark)) - .unwrap_or(ui.visuals().weak_text_color()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label( - RichText::new(shown(t.accuracy.map(|a| format!("{}%", a.round() as i64)))) - .strong() - .size(15.0) - .color(color), - ); - }); - let label = ui.label(RichText::new(tr("Average accuracy")).size(15.0)); - if let Some((lo, hi)) = t.accuracy_range { - label.on_hover_text(trf( - "Average over {k}: from {min}% to {max}%", - &[ - ("k", &crate::i18n::games(t.sides)), - ("min", &(lo.round() as i64)), - ("max", &(hi.round() as i64)), - ], - )); - } - ui.end_row(); - }); - ui.separator(); - if self.rows.is_empty() { - if t.counts.great > 0 { - ui.horizontal(|ui| { - ui.label( - RichText::new(tr( - "No brilliant moves. Games with ! — sort by the «!!» column", - )) - .weak(), - ); - if ui.link(tr("Sort")).clicked() { - out = Some(SummaryAction::Sort); - } - }); - } else { - ui.label(RichText::new(tr("No brilliant or great moves")).weak()); - } - } else { - ui.label( - RichText::new(trf("Games with !! ({n})", &[("n", &self.rows.len())])) - .strong() - .size(13.0), - ); - let teal = crate::review::judgement_text_color(Judgement::Brilliant, dark); - let labels: Vec = self.rows.iter().map(|r| r.found.label()).collect(); - let move_w = labels - .iter() - .map(|l| { - ui.fonts_mut(|f| { - f.layout_no_wrap( - l.clone(), - egui::TextStyle::Body.resolve(ui.style()), - egui::Color32::WHITE, - ) - .size() - .x - }) - }) - .fold(0.0, f32::max) - + 12.0; - let rows = if ctx.content_rect().height() < 700.0 { 3 } else { 6 }; - egui::ScrollArea::vertical() - .max_height(24.0 * rows as f32) - .auto_shrink([false, true]) - .show_rows(ui, 24.0, self.rows.len(), |ui, range| { - for i in range { - let row = &self.rows[i]; - let selected = self.selected == Some(i); - let (rect, resp) = ui.allocate_exact_size( - egui::vec2(ui.available_width(), 24.0), - egui::Sense::click(), - ); - if selected { - ui.painter().rect_filled(rect, 0.0, ui.visuals().selection.bg_fill); - } else if resp.hovered() { - ui.painter() - .rect_filled(rect, 0.0, ui.visuals().widgets.hovered.weak_bg_fill); - } - let mut child = ui.new_child( - egui::UiBuilder::new() - .max_rect(rect.shrink2(egui::vec2(4.0, 0.0))) - .layout(egui::Layout::left_to_right(egui::Align::Center)), - ); - let color = if selected { ui.visuals().selection.stroke.color } else { teal }; - child.add_sized( - egui::vec2(move_w, 24.0), - egui::Label::new(RichText::new(&labels[i]).strong().color(color)) - .selectable(false), - ); - child.add(egui::Label::new(&row.game).truncate().selectable(false)); - if resp.clicked() { - self.selected = Some(i); - out = Some(SummaryAction::Select(row.record)); - } - if resp.double_clicked() { - out = Some(SummaryAction::Open { - record: row.record, - ply: row.found.ply, - }); - } - } - }); - ui.label( - RichText::new(tr( - "Click: choose the row in the table; double click: open at this move", - )) - .weak() - .size(12.0), - ); - // ↑ ↓ through the list, Enter opens. - let (up, down, enter) = ui.input(|i| { - ( - i.key_pressed(Key::ArrowUp), - i.key_pressed(Key::ArrowDown), - i.key_pressed(Key::Enter), - ) - }); - if up || down { - let last = self.rows.len() - 1; - let next = match (self.selected, down) { - (None, _) => 0, - (Some(s), true) => (s + 1).min(last), - (Some(s), false) => s.saturating_sub(1), - }; - self.selected = Some(next); - out = Some(SummaryAction::Select(self.rows[next].record)); - } - if enter && let Some(s) = self.selected { - out = Some(SummaryAction::Open { - record: self.rows[s].record, - ply: self.rows[s].found.ply, - }); - } - } - ui.add_space(6.0); - // Its own height, not the window's: the buttons sit under the text. - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Close")).clicked() { - out = Some(SummaryAction::Close); - } - if !self.rows.is_empty() { - let pick = self.selected.map(|s| &self.rows[s]); - if ui - .add_enabled(pick.is_some(), egui::Button::new(tr("Open game"))) - .clicked() - && let Some(r) = pick - { - out = Some(SummaryAction::Open { - record: r.record, - ply: r.found.ply, - }); - } - } - if self.stopped.is_some() - && !self.rest.is_empty() - && ui.button(tr("Continue")).clicked() - { - out = Some(SummaryAction::Continue { - records: self.rest.clone(), - filter: Box::new(self.filter.clone()), - }); - } - }); - }); - }); - if !open || (out.is_none() && ctx.input(|i| i.key_pressed(Key::Escape))) { - out = Some(SummaryAction::Close); - } - out - } -} diff --git a/apps/desktop/src/chatgpt.rs b/apps/desktop/src/chatgpt.rs index 57d79e3..0f69b51 100644 --- a/apps/desktop/src/chatgpt.rs +++ b/apps/desktop/src/chatgpt.rs @@ -12,8 +12,7 @@ use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, channel}; -use std::time::Duration; -use web_time::{Instant, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; @@ -21,9 +20,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use crate::translate::{Failure, update_credentials}; -#[cfg(not(web))] -use crate::translate::{agent, with_waits}; +use crate::translate::{Failure, agent, update_credentials, with_waits}; const AUTHORIZE: &str = "https://auth.openai.com/api/accounts/authorize"; const TOKEN: &str = "https://auth.openai.com/api/accounts/oauth/token"; @@ -151,13 +148,6 @@ pub struct SignIn { } impl SignIn { - /// The web version does not sign in to ChatGPT (it would listen on a port). - #[cfg(web)] - pub fn start(_ctx: &egui::Context, _host_id: &str, _client_id: &str) -> Result { - Err("the web version does not sign in to ChatGPT".into()) - } - - #[cfg(not(web))] /// Starts listening for the callback and returns the address to open in the browser. pub fn start(ctx: &egui::Context, host_id: &str, client_id: &str) -> Result { let listener = PORTS @@ -227,7 +217,6 @@ impl Drop for SignIn { } } -#[cfg(not(web))] /// The page the browser tab shows after the sign-in. fn page(ok: bool) -> String { let (title, text) = if ok { @@ -251,7 +240,6 @@ fn page(ok: bool) -> String { ) } -#[cfg(not(web))] fn reply(stream: &mut TcpStream, status: &str, body: &str) { let _ = write!( stream, @@ -260,7 +248,6 @@ fn reply(stream: &mut TcpStream, status: &str, body: &str) { ); } -#[cfg(not(web))] /// Waits for the browser to come back to the callback: (code, issued client id). fn wait_for_callback( listener: &TcpListener, @@ -323,7 +310,6 @@ fn wait_for_callback( } } -#[cfg(not(web))] fn token_request(body: &str) -> Result { let mut resp = agent(Duration::from_secs(30)) .post(TOKEN) @@ -354,7 +340,6 @@ fn tokens_from(v: &Value, client_id: &str, old_refresh: &str) -> Tokens { } } -#[cfg(not(web))] fn exchange( code: &str, verifier: &str, @@ -395,11 +380,9 @@ fn exchange( }) } -#[cfg(not(web))] /// Refreshes are one at a time: the refresh token rotates. static REFRESH: Mutex<()> = Mutex::new(()); -#[cfg(not(web))] /// A valid access token, refreshed when it is about to expire. fn access_token() -> Result { let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner()); @@ -415,7 +398,6 @@ fn access_token() -> Result { refresh(&t) } -#[cfg(not(web))] fn refresh(t: &Tokens) -> Result { let body = form(&[ ("grant_type", "refresh_token"), @@ -477,15 +459,11 @@ pub fn sign_out() { return; }; update_credentials(|c| c.chatgpt = None); - #[cfg(not(web))] let _ = std::thread::Builder::new() .name("chatgpt-sign-out".into()) .spawn(move || revoke(&t)); - #[cfg(web)] - let _ = t; } -#[cfg(not(web))] fn revoke(t: &Tokens) -> bool { let body = form(&[ ("token", &t.refresh), @@ -511,22 +489,6 @@ fn revoke(t: &Tokens) -> bool { // --- Requests ------------------------------------------------------------------------------ -#[cfg(web)] -pub fn models() -> Result, Failure> { - Err(crate::translate::no_requests()) -} - -#[cfg(web)] -pub fn respond( - _model: &str, - _system: &str, - _user: &str, - _cancel: &AtomicBool, -) -> Result { - Err(crate::translate::no_requests()) -} - -#[cfg(not(web))] /// The models this account may use (`visibility: list`). pub fn models() -> Result, Failure> { let token = access_token()?; @@ -632,7 +594,6 @@ fn failure(status: u16, body: &str) -> Failure { } } -#[cfg(not(web))] /// One answer of the model, read from the event stream. pub fn respond( model: &str, @@ -694,7 +655,6 @@ pub fn respond( }) } -#[cfg(not(web))] /// The text of a Responses event stream: the deltas until `response.completed`. fn read_stream(reader: impl BufRead, cancel: &AtomicBool) -> Result { let mut text = String::new(); diff --git a/apps/desktop/src/db_counts.rs b/apps/desktop/src/db_counts.rs index fe9ee57..3209a42 100644 --- a/apps/desktop/src/db_counts.rs +++ b/apps/desktop/src/db_counts.rs @@ -1,14 +1,15 @@ //! How many games each database on the shelf holds before it is opened: «not loaded» -//! on a card told the user nothing. The databases are counted one after another away -//! from the screen (reading a large one takes seconds; the screen never waits): on a -//! thread of its own, in a browser by the page's reader (`platform::web::import`). The -//! counts are remembered with the file's size and time, so the next start shows them -//! at once. A card whose database is not counted yet says nothing. +//! on a card told the user nothing. A thread of its own counts the databases one after +//! another (reading a large one takes seconds; the screen never waits) and remembers the +//! counts with the file's size and time, so the next start shows them at once. A card +//! whose database is not counted yet says nothing. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::atomic::AtomicBool; +use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Mutex}; +use std::time::UNIX_EPOCH; use chess_import::Database; use serde::{Deserialize, Serialize}; @@ -51,145 +52,13 @@ enum Job { Known(PathBuf, Count), } -/// A file to read and count: its path and its size and time now. -struct ToCount(PathBuf, (u64, u64)); - -/// The counts known and where they are kept. -#[derive(Clone)] -struct Counter { - known: Arc>>, - /// `None`: for this run only. - file: Option, - ctx: egui::Context, -} - -impl Counter { - /// What the job leaves to do: a file to read, or nothing (its count is known now). - fn take(&self, job: Job) -> Option { - let (path, known) = match job { - Job::Count(p) => (p, None), - Job::Known(p, c) => (p, Some(c)), - }; - let stamp = stamp(&path)?; - let fresh = self.known.lock().ok().and_then(|k| { - k.get(&path) - .filter(|e| (e.size, e.modified) == stamp) - .map(|e| e.count) - }); - match known { - Some(c) if fresh == Some(c) => None, - Some(c) => { - self.record(path, stamp, c); - None - } - None if fresh.is_some() => None, - None => Some(ToCount(path, stamp)), - } - } - - fn record(&self, path: PathBuf, (size, modified): (u64, u64), count: Count) { - let json = match self.known.lock() { - Ok(mut k) => { - k.insert( - path, - Entry { - size, - modified, - count, - }, - ); - serde_json::to_vec(&*k).ok() - } - Err(_) => return, - }; - if let (Some(f), Some(json)) = (&self.file, json) { - let _ = crate::platform::fs::write_atomic(f, &json); - } - self.ctx.request_repaint(); - } - - /// Counts the files of the jobs, one after another, on a thread of its own. - #[cfg(not(web))] - fn start(self, jobs: Receiver) -> bool { - let spawned = std::thread::Builder::new() - .name("db-counts".into()) - .spawn(move || { - let never = std::sync::atomic::AtomicBool::new(false); - for job in jobs { - let Some(ToCount(path, stamp)) = self.take(job) else { - continue; - }; - // The card says why it cannot be read when the database is opened. - if let Ok(o) = chess_import::open(&path, &mut |_| {}, &never) { - self.record(path, stamp, Count::of(&o.db)); - } - } - }); - spawned.is_ok() - } - - /// Counts the files of the jobs, one after another, in the page's reader: the next - /// once the last is answered ([`Counts`] calls [`Counter::next`] after each job). - #[cfg(web)] - fn start(self, jobs: Receiver) -> bool { - WEB.with_borrow_mut(|w| { - *w = Some(Web { - counter: self, - jobs, - busy: false, - }) - }); - true - } - - #[cfg(web)] - fn next() { - let read = WEB.with_borrow_mut(|w| { - let w = w.as_mut()?; - if w.busy { - return None; - } - while let Ok(job) = w.jobs.try_recv() { - if let Some(to_count) = w.counter.take(job) { - w.busy = true; - return Some((w.counter.clone(), to_count)); - } - } - None - }); - let Some((counter, ToCount(path, stamp))) = read else { - return; - }; - crate::platform::web::import::count(&path.clone(), move |games| { - if let Some(games) = games { - let locked = false; - counter.record(path, stamp, Count { games, locked }); - } - WEB.with_borrow_mut(|w| { - if let Some(w) = w.as_mut() { - w.busy = false; - } - }); - Counter::next(); - }); - } -} - -/// The counting of the page: the jobs not taken yet, and whether a file is being read. -#[cfg(web)] -struct Web { - counter: Counter, - jobs: Receiver, - busy: bool, -} - -#[cfg(web)] -thread_local! { - static WEB: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +#[derive(Default)] +struct Shared { + known: HashMap, } pub struct Counts { - known: Arc>>, + shared: Arc>, asked: HashSet, jobs: Option>, } @@ -204,58 +73,106 @@ impl Counts { fn kept_in(file: Option, ctx: &egui::Context) -> Self { let known: HashMap = file .as_ref() - .and_then(|f| crate::platform::fs::read(f).ok()) + .and_then(|f| std::fs::read(f).ok()) .and_then(|b| serde_json::from_slice(&b).ok()) .unwrap_or_default(); - let known = Arc::new(Mutex::new(known)); + let shared = Arc::new(Mutex::new(Shared { known })); let (tx, rx) = channel::(); - let counter = Counter { - known: known.clone(), - file, - ctx: ctx.clone(), - }; + let (worker, ctx) = (shared.clone(), ctx.clone()); + let spawned = std::thread::Builder::new() + .name("db-counts".into()) + .spawn(move || { + let never = AtomicBool::new(false); + for job in rx { + let (path, known) = match job { + Job::Count(p) => (p, None), + Job::Known(p, c) => (p, Some(c)), + }; + let Some((size, modified)) = stamp(&path) else { + continue; + }; + let fresh = worker.lock().ok().and_then(|s| { + s.known + .get(&path) + .filter(|e| e.size == size && e.modified == modified) + .map(|e| e.count) + }); + let count = match known { + Some(c) if fresh == Some(c) => continue, + Some(c) => c, + None if fresh.is_some() => continue, + None => match chess_import::open(&path, &mut |_| {}, &never) { + Ok(o) => Count::of(&o.db), + // The card says why when the database is opened. + Err(_) => continue, + }, + }; + let json = match worker.lock() { + Ok(mut s) => { + s.known.insert( + path, + Entry { + size, + modified, + count, + }, + ); + serde_json::to_vec(&s.known).ok() + } + Err(_) => return, + }; + if let (Some(f), Some(json)) = (&file, json) { + if let Some(dir) = f.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = crate::settings::write_atomic(f, &json); + } + ctx.request_repaint(); + } + }); Self { - known, + shared, asked: HashSet::new(), - jobs: counter.start(rx).then_some(tx), - } - } - - fn send(&self, job: Job) { - if let Some(jobs) = &self.jobs { - let _ = jobs.send(job); - #[cfg(web)] - Counter::next(); + jobs: spawned.ok().map(|_| tx), } } /// The games of a database not opened yet (`None`: not counted yet); it is counted /// from now on. pub fn get(&mut self, path: &Path) -> Option { - if self.asked.insert(path.to_owned()) { - self.send(Job::Count(path.to_owned())); + if self.asked.insert(path.to_owned()) + && let Some(jobs) = &self.jobs + { + let _ = jobs.send(Job::Count(path.to_owned())); } - self.known.lock().ok()?.get(path).map(|e| e.count) + self.shared.lock().ok()?.known.get(path).map(|e| e.count) } /// A database was opened: its count is remembered for the next start. pub fn opened(&mut self, path: &Path, db: &Database) { self.asked.insert(path.to_owned()); - self.send(Job::Known(path.to_owned(), Count::of(db))); + if let Some(jobs) = &self.jobs { + let _ = jobs.send(Job::Known(path.to_owned(), Count::of(db))); + } } } /// The file's size and time (seconds since the epoch); a changed file is counted again. fn stamp(path: &Path) -> Option<(u64, u64)> { - let m = crate::platform::fs::meta(path).ok()?; - Some((m.len, m.modified_ms / 1000)) + let m = std::fs::metadata(path).ok()?; + let modified = m + .modified() + .ok()? + .duration_since(UNIX_EPOCH) + .ok()? + .as_secs(); + Some((m.len(), modified)) } #[cfg(test)] mod tests { use super::*; - use std::time::Duration; - use web_time::Instant; + use std::time::{Duration, Instant}; fn wait(counts: &mut Counts, path: &Path, want: usize) -> bool { let deadline = Instant::now() + Duration::from_secs(5); @@ -284,8 +201,9 @@ mod tests { assert!(wait(&mut counts, &pgn, 2)); // An opened database tells its count; a changed file is counted anew. std::fs::write(&pgn, "[White \"A\"]\n\n1. e4 *\n").unwrap(); - let never = std::sync::atomic::AtomicBool::new(false); - let db = chess_import::open(&pgn, &mut |_| {}, &never).unwrap().db; + let db = chess_import::open(&pgn, &mut |_| {}, &AtomicBool::new(false)) + .unwrap() + .db; counts.opened(&pgn, &db); assert!(wait(&mut counts, &pgn, 1)); assert!(!counts.get(&pgn).unwrap().locked); diff --git a/apps/desktop/src/engine_download.rs b/apps/desktop/src/engine_download.rs index 45dc123..f0130a2 100644 --- a/apps/desktop/src/engine_download.rs +++ b/apps/desktop/src/engine_download.rs @@ -66,14 +66,11 @@ fn asset() -> Option { /// Whether a download is offered on this platform at all. pub fn available() -> bool { - cfg!(web) || asset().is_some() + asset().is_some() } /// Size of the download in megabytes (rounded), for the offer. pub fn size_mb() -> u64 { - #[cfg(web)] - return crate::platform::web::engine::DOWNLOAD_MB; - #[cfg(not(web))] asset().map_or(0, |a| a.size.div_ceil(1_000_000)) } @@ -102,40 +99,13 @@ pub fn clean_leftovers() { } /// The downloaded engine, if it is there. -pub fn installed() -> Option { - #[cfg(web)] - return crate::platform::web::engine::worker_script() - .map(crate::engines::EngineLocation::Worker); - #[cfg(not(web))] - { - let p = dir()?.join(EXE); - p.is_file() - .then_some(crate::engines::EngineLocation::Program(p)) - } -} - -/// The size of the downloaded engine, in MB (0 when it is not there). -pub fn installed_mb() -> u64 { - #[cfg(web)] - return if crate::platform::web::engine::ready() { - crate::platform::web::engine::WASM_BYTES / 1_000_000 - } else { - 0 - }; - #[cfg(not(web))] - dir() - .and_then(|d| std::fs::metadata(d.join(EXE)).ok()) - .map_or(0, |m| m.len() / 1_000_000) +pub fn installed() -> Option { + let p = dir()?.join(EXE); + p.is_file().then_some(p) } /// Removes the downloaded engine (frees its space). pub fn remove() -> std::io::Result<()> { - #[cfg(web)] - { - crate::platform::web::engine::remove(); - Ok(()) - } - #[cfg(not(web))] match dir() { Some(d) if d.exists() => std::fs::remove_dir_all(d), _ => Ok(()), @@ -178,54 +148,11 @@ pub struct Download { } impl Download { - #[cfg(not(web))] pub fn start(ctx: &egui::Context) -> Download { let total = asset().map_or(0, |a| a.size); Download::spawn(ctx, total, run) } - /// The browser's engine: Stockfish 19 in WebAssembly from our site, into the - /// browser's cache (`platform::web::engine`). - #[cfg(web)] - pub fn start(ctx: &egui::Context) -> Download { - use crate::platform::web::engine::{self, Fetch}; - let total = engine::WASM_BYTES; - let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0, total })); - let cancel = Arc::new(AtomicBool::new(false)); - let (s, c, ctx) = (stage.clone(), cancel.clone(), ctx.clone()); - wasm_bindgen_futures::spawn_local(async move { - let report = |st: Stage| { - if let Ok(mut g) = s.lock() { - *g = st; - } - ctx.request_repaint(); - }; - let end = - match engine::download(|done, total| report(Stage::Downloading { done, total }), c) - .await - { - // The engine's file: its worker's script. - Ok(()) => Stage::Done(PathBuf::from(engine::SCRIPT)), - Err(Fetch::Cancelled) => Stage::Cancelled, - Err(Fetch::Network(e)) => Stage::Failed(Failure::Network(e)), - Err(Fetch::Server(code)) => Stage::Failed(Failure::Server(code)), - Err(Fetch::Checksum) => Stage::Failed(Failure::Checksum), - Err(Fetch::Storage(e)) => Stage::Failed(Failure::Disk(e)), - }; - report(end); - }); - Download { stage, cancel } - } - - /// The download of a platform that has none (Rodent and the like in a browser). - #[cfg(web)] - pub fn unsupported() -> Download { - Download { - stage: Arc::new(Mutex::new(Stage::Failed(Failure::Unsupported))), - cancel: Arc::new(AtomicBool::new(false)), - } - } - /// Runs `job` (a download and what follows it) in a thread of its own; `total`: the /// bytes expected, shown until the server says. pub fn spawn(ctx: &egui::Context, total: u64, job: Job) -> Download { @@ -278,7 +205,6 @@ impl Drop for Download { } } -#[cfg(not(web))] fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let asset = asset().ok_or(Failure::Unsupported)?; let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; @@ -302,7 +228,6 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result result } -#[cfg(not(web))] /// Downloads `url` into `to`, checking the size and the SHA-256 on the way. The file is /// written beside and put in place once checked: a new file, never the old one rewritten /// (macOS on Apple silicon kills an executable rewritten in place after it once ran: it @@ -325,7 +250,6 @@ pub fn fetch( result } -#[cfg(not(web))] fn fetch_into( url: &str, to: &Path, @@ -404,7 +328,6 @@ pub fn already(file: &Path, asset: &Asset) -> bool { } /// Takes the engine executable and its license files out of the archive. -#[cfg(not(web))] fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result { let exe = dir.join(EXE); let wanted = |name: &str| -> Option { @@ -459,7 +382,6 @@ fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result { Ok(exe) } -#[cfg(not(web))] /// Starts the engine once and waits for its name: the binary runs on this computer. fn check_runs(exe: &Path) -> Result<(), Failure> { let mut cmd = std::process::Command::new(exe); @@ -533,10 +455,7 @@ mod tests { .output() .expect("runs"); assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish")); - assert_eq!( - installed(), - Some(crate::engines::EngineLocation::Program(exe)) - ); + assert_eq!(installed(), Some(exe)); } #[test] diff --git a/apps/desktop/src/engine_offer.rs b/apps/desktop/src/engine_offer.rs index c218ced..7f732f6 100644 --- a/apps/desktop/src/engine_offer.rs +++ b/apps/desktop/src/engine_offer.rs @@ -18,25 +18,7 @@ pub const DOWNLOAD_INDICATOR: &str = "download_indicator"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Pending { LiveAnalysis, - /// The search for great moves in a database's list (task 27), waiting in the app. - GreatMoves, - /// The analysis of the game on the screen whose `serial` is `game` (no other game's); - /// `full`: anew, over evaluations read from the PGN. - GameAnalysis { - game: u64, - full: bool, - }, - /// The search for opening errors of the preparation whose `serial` is `prep`. - OpeningErrors { - prep: u64, - }, -} - -/// A number of its own for a screen an action waits on (a game, a preparation), so -/// that an engine arriving later starts it there and nowhere else. -pub fn next_serial() -> u64 { - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); - NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + GameAnalysis, } /// What the owner should do. @@ -46,7 +28,6 @@ pub enum OfferEvent { /// Use the Stockfish found on this computer, then run `Pending`. UseSystem(PathBuf, Option), /// Open the file dialog to choose an engine. - #[cfg(not(web))] ChooseFile, Toast(String), } @@ -58,11 +39,6 @@ enum Mode { System(PathBuf), /// The downloaded engine was deleted from the disk. Missing, - /// The game analysis or the opening errors, which need ChessPenguin's Stockfish 19 - /// itself (their search is the same on every computer): only its download helps. - Own, - /// The same, when the user's engine does not do (`review_engine`): it is named. - OwnInstead(crate::review_engine::Unfit), } pub struct EngineOffer { @@ -91,16 +67,17 @@ impl EngineOffer { /// Whether the active engine can be started. pub fn engine_ready(settings: &Settings) -> bool { - settings.active_engine().is_some_and(|e| e.present()) + settings + .active_engine() + .and_then(|e| e.executable()) + .is_some_and(|p| p.is_file()) } /// Opens the offer for an action that needs an engine. pub fn ask(&mut self, pending: Pending, settings: &Settings) { self.pending = Some(pending); self.failure = None; - self.mode = if pending != Pending::LiveAnalysis { - Mode::Own - } else if settings.active_engine().is_some_and(|e| e.builtin) { + self.mode = if settings.active_engine().is_some_and(|e| e.builtin) { Mode::Missing } else if settings.engines.is_empty() && let Some(p) = crate::engines::system_stockfish() @@ -112,15 +89,6 @@ impl EngineOffer { self.open = true; } - /// Opens the offer of ChessPenguin's Stockfish 19 for the game analysis or the - /// opening errors, saying why the user's engine does not do. - pub fn ask_instead_of(&mut self, pending: Pending, unfit: crate::review_engine::Unfit) { - self.pending = Some(pending); - self.failure = None; - self.mode = Mode::OwnInstead(unfit); - self.open = true; - } - /// Starts the download (from the offer or from the settings). pub fn start(&mut self, ctx: &egui::Context) { if self.download.as_ref().is_some_and(Download::running) { @@ -155,18 +123,12 @@ impl EngineOffer { events.push(OfferEvent::Installed(pending)); events.push(OfferEvent::Toast( match pending { - Some(Pending::GameAnalysis { .. }) => { + Some(Pending::GameAnalysis) => { tr("Stockfish installed — game analysis started") } Some(Pending::LiveAnalysis) => { tr("Stockfish installed — analysis is on") } - Some(Pending::OpeningErrors { .. }) => { - tr("Stockfish installed — the search for opening errors started") - } - Some(Pending::GreatMoves) => { - tr("Stockfish installed — the search for great moves started") - } None => tr("Stockfish installed"), } .to_string(), @@ -240,32 +202,20 @@ impl EngineOffer { fn offer_body(&mut self, ui: &mut Ui, events: &mut Vec) { let size = engine_download::size_mb(); - let (title, text): (&str, String) = match &self.mode { + let (title, text) = match &self.mode { Mode::Offer => ( tr("Analysis needs a chess engine"), tr( "Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.", - ) - .into(), + ), ), Mode::System(_) => ( tr("Analysis needs a chess engine"), - tr("Stockfish is already installed on this computer.").into(), + tr("Stockfish is already installed on this computer."), ), Mode::Missing => ( tr("Stockfish not found"), - tr("The Stockfish file is missing from the disk. Download it again?").into(), - ), - Mode::Own => ( - tr("Analysis needs Stockfish 19"), - tr( - "Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.", - ) - .into(), - ), - Mode::OwnInstead(unfit) => ( - tr("Analysis needs Stockfish 19"), - instead_text(unfit, self.pending), + tr("The Stockfish file is missing from the disk. Download it again?"), ), }; ui.heading(title); @@ -280,19 +230,6 @@ impl EngineOffer { )) .weak(), ); - } else if cfg!(web) { - // The browser's engine: from our site, into this browser (design §1.4). - ui.label(tr( - "It evaluates the position, shows the best moves and reviews the game. It is downloaded once and kept in this browser.", - )); - let free = crate::platform::storage_free().map(|f| { - trf( - "free for the site: {free}", - &[("free", &crate::platform::size_text(f))], - ) - }); - let size = trf("Size: {size}", &[("size", &format!("{size} MB"))]); - ui.label(RichText::new(free.map_or(size.clone(), |f| format!("{size} · {f}"))).weak()); } else { ui.label( RichText::new(trf( @@ -341,18 +278,13 @@ impl EngineOffer { } } } - // Another engine does not do for the game analysis (and a browser has - // no engine programs). - #[cfg(not(web))] - if !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) { - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - if ui.button(tr("Choose engine file…")).clicked() { - events.push(OfferEvent::ChooseFile); - self.open = false; - self.pending = None; - } - }); - } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.button(tr("Choose engine file…")).clicked() { + events.push(OfferEvent::ChooseFile); + self.open = false; + self.pending = None; + } + }); }); }); } @@ -393,15 +325,9 @@ impl EngineOffer { } ui.add_space(4.0); let after = match self.pending { - Some(Pending::GameAnalysis { .. }) => { + Some(Pending::GameAnalysis) => { tr("Game analysis will start by itself when the download finishes.") } - Some(Pending::OpeningErrors { .. }) => { - tr("The search for opening errors will start by itself when the download finishes.") - } - Some(Pending::GreatMoves) => { - tr("The search for great moves will start by itself when the download finishes.") - } _ => tr("Analysis will start by itself when the download finishes."), }; ui.label(RichText::new(after).weak()); @@ -420,8 +346,6 @@ impl EngineOffer { }); } - // In a browser nothing is pushed: there are no engine files to choose. - #[cfg_attr(web, allow(clippy::ptr_arg))] fn failure_body(&mut self, ui: &mut Ui, f: &Failure, events: &mut Vec) { ui.heading(tr("⚠ Stockfish wasn't downloaded")); ui.add_space(6.0); @@ -434,10 +358,7 @@ impl EngineOffer { ui.label(RichText::new(d).small().weak()); }); } - if matches!(f, Failure::Network(_)) - && cfg!(target_os = "linux") - && !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) - { + if matches!(f, Failure::Network(_)) && cfg!(target_os = "linux") { ui.label( RichText::new(tr( "A stockfish package of your distribution is found by ChessPenguin too.", @@ -459,17 +380,14 @@ impl EngineOffer { self.failure = None; self.pending = None; } - #[cfg(not(web))] - if !matches!(self.mode, Mode::Own | Mode::OwnInstead(_)) { - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - if ui.button(tr("Choose engine file…")).clicked() { - events.push(OfferEvent::ChooseFile); - self.open = false; - self.failure = None; - self.pending = None; - } - }); - } + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if ui.button(tr("Choose engine file…")).clicked() { + events.push(OfferEvent::ChooseFile); + self.open = false; + self.failure = None; + self.pending = None; + } + }); }); }); } @@ -517,67 +435,6 @@ impl EngineOffer { } } -/// Why the user's engine does not do for the game analysis (or the opening errors), -/// what is offered instead, and that the analysis follows the download by itself. -fn instead_text(unfit: &crate::review_engine::Unfit, pending: Option) -> String { - use crate::review_engine::Why; - let errors = matches!(pending, Some(Pending::OpeningErrors { .. })); - let engine = crate::widgets::shorten(&unfit.name, 48); - let mut parts = vec![match unfit.why { - Why::Differs => tr( - "Your Stockfish 19 calculates differently from ChessPenguin's build (another build or network).", - ) - .to_owned(), - Why::NotStarted => trf("{engine} could not be started.", &[("engine", &engine)]), - Why::TimedOut => trf( - "{engine} did not finish the check in time; it will be checked again next time.", - &[("engine", &engine)], - ), - Why::Other if unfit.from_settings => { - trf("The settings name {engine}.", &[("engine", &engine)]) - } - Why::Other => trf("The system has {engine}.", &[("engine", &engine)]), - }]; - let official = matches!(unfit.why, Why::Differs | Why::TimedOut); - parts.push( - match (official, errors) { - (true, false) => tr( - "So that the marks are the same on every computer, game analysis runs on the official build.", - ), - (true, true) => tr( - "So that the marks are the same on every computer, the search for opening errors runs on the official build.", - ), - (false, false) => tr( - "Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer.", - ), - (false, true) => tr( - "The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer.", - ), - } - .to_owned(), - ); - parts.push( - if official { - tr("Download it?") - } else { - tr("Download Stockfish 19?") - } - .to_owned(), - ); - if unfit.why != Why::NotStarted { - parts.push(tr("Your engine stays for position analysis.").to_owned()); - } - parts.push( - if errors { - tr("The search for opening errors will start by itself when the download finishes.") - } else { - tr("Game analysis will start by itself when the download finishes.") - } - .to_owned(), - ); - parts.join(" ") -} - /// What to tell the user about a failure, and the technical details (collapsed). fn failure_text(f: &Failure) -> (String, Option) { match f { @@ -611,51 +468,3 @@ fn failure_text(f: &Failure) -> (String, Option) { ), } } - -#[cfg(test)] -mod tests { - use super::{Pending, instead_text}; - use crate::review_engine::{Unfit, Why}; - - fn text(why: Why, from_settings: bool, pending: Pending) -> String { - let unfit = Unfit { - name: "Rodent V 1.2".into(), - from_settings, - why, - }; - instead_text(&unfit, Some(pending)) - } - - /// The offer says why the user's engine does not do and where it is from; the - /// user's engine stays for the live analysis, the analysis follows the download. - #[test] - fn the_offer_says_why_the_users_engine_does_not_do() { - let game = Pending::GameAnalysis { - game: 1, - full: false, - }; - let errors = Pending::OpeningErrors { prep: 1 }; - let t = text(Why::Other, true, game); - assert!(t.starts_with("The settings name Rodent V 1.2."), "{t}"); - assert!(t.contains("Your engine stays for position analysis.")); - assert!(t.ends_with("Game analysis will start by itself when the download finishes.")); - let t = text(Why::Other, false, errors); - assert!(t.starts_with("The system has Rodent V 1.2."), "{t}"); - assert!(t.contains("The search for opening errors needs Stockfish 19 itself")); - let t = text(Why::Differs, true, game); - assert!( - t.starts_with("Your Stockfish 19 calculates differently"), - "{t}" - ); - assert!(t.contains("Download it?")); - let t = text(Why::TimedOut, true, game); - assert!( - t.starts_with("Rodent V 1.2 did not finish the check in time"), - "{t}" - ); - assert!(t.contains("runs on the official build") && t.contains("Download it?")); - let t = text(Why::NotStarted, true, game); - assert!(t.starts_with("Rodent V 1.2 could not be started."), "{t}"); - assert!(!t.contains("stays for position analysis")); - } -} diff --git a/apps/desktop/src/engines.rs b/apps/desktop/src/engines.rs index 3e86544..7f91a19 100644 --- a/apps/desktop/src/engines.rs +++ b/apps/desktop/src/engines.rs @@ -27,53 +27,14 @@ pub fn bundled_stockfish() -> Option { candidates.into_iter().flatten().find(|p| is_executable(p)) } -/// Where an engine starts from: its program on a computer; in a browser, which runs no -/// programs, the address of its Web Worker's script. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum EngineLocation { - #[cfg(not(web))] - Program(PathBuf), - #[cfg(web)] - Worker(String), -} - -impl EngineLocation { - /// Whether the engine is there to start (its program's file; a worker always). - pub fn present(&self) -> bool { - match self { - #[cfg(not(web))] - EngineLocation::Program(p) => p.is_file(), - #[cfg(web)] - EngineLocation::Worker(_) => true, - } - } -} - -impl std::fmt::Display for EngineLocation { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - #[cfg(not(web))] - EngineLocation::Program(p) => write!(f, "{}", p.display()), - #[cfg(web)] - EngineLocation::Worker(script) => write!(f, "{script}"), - } - } -} - /// ChessPenguin's Stockfish: the bundled one, or else the downloaded one. -pub fn own_stockfish() -> Option { - #[cfg(not(web))] - return bundled_stockfish() - .map(EngineLocation::Program) - .or_else(crate::engine_download::installed); - #[cfg(web)] - crate::engine_download::installed() +pub fn own_stockfish() -> Option { + bundled_stockfish().or_else(crate::engine_download::installed) } /// `stockfish` from `PATH` (for example, the distribution package). On macOS an app /// started from the Finder does not get the shell's `PATH`: Homebrew's directories are /// looked at too. -#[cfg(not(web))] pub fn system_stockfish() -> Option { let path = std::env::var_os("PATH").unwrap_or_default(); let extra: &[&str] = if cfg!(target_os = "macos") { @@ -87,12 +48,6 @@ pub fn system_stockfish() -> Option { .find(|p| is_executable(p)) } -/// A browser has no programs of the system to find. -#[cfg(web)] -pub fn system_stockfish() -> Option { - None -} - fn is_executable(p: &Path) -> bool { let Ok(meta) = std::fs::metadata(p) else { return false; diff --git a/apps/desktop/src/examples.rs b/apps/desktop/src/examples.rs index 4843acd..2aaacd3 100644 --- a/apps/desktop/src/examples.rs +++ b/apps/desktop/src/examples.rs @@ -1,36 +1,29 @@ -//! Sample databases of the program, so the library is not empty: classic games with -//! short introductions, and Alekhine's games (moves only). At the first start they are -//! written, named in the interface language, to `/examples/` and put on -//! the library shelf; a sample removed from the shelf does not come back. -//! -//! The samples are read only, so their files are the program's: at every start a file -//! that is not the text built into this version (an older version of the sample, a file -//! damaged or edited outside) is replaced by it, whether on the shelf or not. Nothing -//! keeps a sample by its place in the file: the counts of the cards are of the file's -//! size and time, the marks of viewed games of the games' text. +//! Sample databases for the first start, so the library is not empty: classic games +//! with short introductions, and Alekhine's games (moves only). They are written once, +//! named in the interface language, to `/examples/` and put on the +//! library shelf; a sample removed from the shelf does not come back. -use std::path::{Path, PathBuf}; +use std::path::PathBuf; -use crate::i18n::{all_languages, tr}; +use crate::i18n::tr; use crate::settings::Settings; -/// The samples: the English name (a key of the translations) and the text. -const SAMPLES: [(&str, &str); 2] = [ - ( - "Classic games", - include_str!("../../../examples/classics.pgn"), - ), - ("Alekhine", include_str!("../../../examples/alekhine.pgn")), -]; - -#[cfg(test)] -const OPENING_SAMPLES: [(&str, &str); 2] = [ - ("najdorf", include_str!("../../../examples/najdorf.pgn")), - ("spanish", include_str!("../../../examples/spanish.pgn")), -]; +fn files() -> [(&'static str, &'static str); 2] { + [ + ( + tr("Classic games"), + include_str!("../../../examples/classics.pgn"), + ), + ( + tr("Alekhine"), + include_str!("../../../examples/alekhine.pgn"), + ), + ] +} fn dir() -> Option { - crate::platform::examples_dir() + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("examples")) } /// A sample database of the program: only read (games added there would end up in a @@ -39,67 +32,44 @@ pub fn is_example(path: &std::path::Path) -> bool { dir().is_some_and(|d| path.starts_with(d)) } -/// Adds the samples at the first start and brings their files up to this version; -/// `true` when the settings changed. A new library starts with them (the classics -/// open); an existing one gets them after its own databases. -pub fn setup(settings: &mut Settings) -> bool { - match dir() { - Some(dir) => setup_in(&dir, settings), - None => !std::mem::replace(&mut settings.examples_added, true), +/// Adds the samples once; `true` when the settings changed. A new library starts with +/// them (the classics open); an existing one gets them after its own databases. +pub fn first_run_setup(settings: &mut Settings) -> bool { + if settings.examples_added { + return false; } -} - -fn setup_in(dir: &Path, settings: &mut Settings) -> bool { - let first = !std::mem::replace(&mut settings.examples_added, true); - for (key, text) in SAMPLES { - let named = dir.join(format!("{}.pgn", tr(key))); - // The file is named in the language of the first start: the sample's file under - // any language's name is it. - for name in all_languages(key) { - let path = dir.join(format!("{name}.pgn")); - let kept = crate::platform::fs::exists(&path) || settings.databases.contains(&path); - if (kept || (first && path == named)) - && let Err(e) = bring_up_to_date(&path, text) - { - eprintln!("examples: cannot write {}: {e}", path.display()); - } + settings.examples_added = true; + let Some(dir) = dir() else { + return true; + }; + if let Err(e) = std::fs::create_dir_all(&dir) { + eprintln!("examples: cannot create {}: {e}", dir.display()); + return true; + } + for (name, text) in files() { + let path = dir.join(format!("{name}.pgn")); + if !path.exists() + && let Err(e) = std::fs::write(&path, text) + { + eprintln!("examples: cannot write {}: {e}", path.display()); + continue; } - if first && crate::platform::fs::exists(&named) && !settings.databases.contains(&named) { - settings.databases.push(named); + if !settings.databases.contains(&path) { + settings.databases.push(path); } } - first -} - -/// Writes `text` to `path` unless the file holds it already. The new file takes the old -/// one's place at once (a program started meanwhile reads one or the other whole). -fn bring_up_to_date(path: &Path, text: &str) -> std::io::Result<()> { - if crate::platform::fs::read(path).is_ok_and(|on_disk| on_disk == text.as_bytes()) { - return Ok(()); - } - crate::platform::fs::write_atomic(path, text.as_bytes()) + true } #[cfg(test)] mod tests { use super::*; - /// A folder of its own for each test, empty. - fn folder(name: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("cp-examples-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - dir - } - - fn classics(dir: &Path) -> PathBuf { - dir.join(format!("{}.pgn", tr("Classic games"))) - } - #[test] fn samples_are_valid_pgn() { - let dir = folder("valid"); - std::fs::create_dir_all(&dir).unwrap(); - for (name, text) in SAMPLES { + for (name, text) in files() { + let dir = std::env::temp_dir().join(format!("cp-examples-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); let path = dir.join(format!("{name}.pgn")); std::fs::write(&path, text).unwrap(); let db = chess_core::PgnDatabase::open( @@ -118,138 +88,7 @@ mod tests { parsed.diagnostics ); } + let _ = std::fs::remove_dir_all(&dir); } - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn opening_samples_have_three_legal_records_and_the_requested_branches() { - for (name, text) in OPENING_SAMPLES { - let db = chess_core::PgnDatabase::from_bytes( - text.as_bytes().to_vec(), - None, - &mut |_| {}, - &std::sync::atomic::AtomicBool::new(false), - ) - .unwrap(); - assert_eq!(db.len(), 3, "{name}"); - let mut branches = Vec::new(); - for index in 0..db.len() { - let parsed = db.load_game(index).unwrap(); - assert!(parsed.diagnostics.is_empty(), "{name} #{}", index + 1); - let game = parsed.game; - for tag in ["Event", "Site", "Date", "Round", "White", "Black", "Result"] { - assert!(game.tag(tag).is_some(), "{name} #{index}: {tag}"); - } - assert_eq!(game.result().as_str(), "*"); - let san: Vec = game - .mainline() - .iter() - .filter_map(|id| game.game_move(*id).map(|mv| mv.san.clone())) - .collect(); - let common: &[&str] = if name == "najdorf" { - &[ - "e4", "c5", "Nf3", "d6", "d4", "cxd4", "Nxd4", "Nf6", "Nc3", "a6", - ] - } else { - &["e4", "e5", "Nf3", "Nc6", "Bb5"] - }; - assert!(san.len() >= common.len(), "{name} #{index}: {san:?}"); - assert!( - common - .iter() - .zip(&san) - .all(|(expected, actual)| *expected == actual), - "{name} #{index}: {san:?}" - ); - branches.push(san); - } - if name == "najdorf" { - assert_eq!(branches[0][10], "Be3"); - assert_eq!(branches[1][10], "Bg5"); - assert_eq!(branches[2][10], "Be2"); - } else { - assert_eq!(branches[0][5], "Nf6"); - assert_eq!(branches[1][5], "a6"); - assert_eq!(branches[2][5], "a6"); - assert_eq!(branches[2][9], "Nxe4"); - } - } - } - - #[test] - fn the_first_start_writes_the_samples_and_shelves_them() { - let dir = folder("first"); - let mut settings = Settings::default(); - assert!(setup_in(&dir, &mut settings)); - assert!(settings.examples_added); - assert_eq!(settings.databases.len(), SAMPLES.len()); - assert_eq!(settings.databases[0], classics(&dir)); - for (path, (_, text)) in settings.databases.iter().zip(SAMPLES) { - assert_eq!(std::fs::read_to_string(path).unwrap(), text); - } - // The next start changes nothing. - let before = settings.databases.clone(); - assert!(!setup_in(&dir, &mut settings)); - assert_eq!(settings.databases, before); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn an_older_or_damaged_sample_is_replaced() { - let dir = folder("older"); - let mut settings = Settings::default(); - setup_in(&dir, &mut settings); - let path = classics(&dir); - let old: String = SAMPLES[0].1.chars().take(SAMPLES[0].1.len() / 3).collect(); - std::fs::write(&path, old).unwrap(); - assert!(!setup_in(&dir, &mut settings)); - assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1); - // Edited outside: the same. - let mut edited = SAMPLES[0].1.to_owned(); - edited.push_str("\n[Event \"mine\"]\n\n1. e4 *\n"); - std::fs::write(&path, edited).unwrap(); - setup_in(&dir, &mut settings); - assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1); - let _ = std::fs::remove_dir_all(&dir); - } - - /// A program that started in another language named the file in it. - #[test] - fn a_sample_named_in_another_language_is_replaced() { - let dir = folder("language"); - std::fs::create_dir_all(&dir).unwrap(); - let russian = dir.join("Классические партии.pgn"); - std::fs::write(&russian, "[Event \"old\"]\n\n1. e4 *\n").unwrap(); - let mut settings = Settings { - examples_added: true, - databases: vec![russian.clone()], - ..Settings::default() - }; - assert!(!setup_in(&dir, &mut settings)); - assert_eq!(std::fs::read_to_string(&russian).unwrap(), SAMPLES[0].1); - // The samples of the other names are not made. - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); - assert_eq!(settings.databases, vec![russian]); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn a_sample_taken_off_the_shelf_stays_off() { - let dir = folder("off"); - let mut settings = Settings::default(); - setup_in(&dir, &mut settings); - let path = classics(&dir); - settings.databases.retain(|p| *p != path); - std::fs::write(&path, "[Event \"old\"]\n\n1. e4 *\n").unwrap(); - assert!(!setup_in(&dir, &mut settings)); - assert!(!settings.databases.contains(&path)); - // Its file is the new one, should the user open it again. - assert_eq!(std::fs::read_to_string(&path).unwrap(), SAMPLES[0].1); - // Deleted as well: not made again. - std::fs::remove_file(&path).unwrap(); - setup_in(&dir, &mut settings); - assert!(!path.exists()); - let _ = std::fs::remove_dir_all(&dir); } } diff --git a/apps/desktop/src/file_state.rs b/apps/desktop/src/file_state.rs index f214d98..38dc669 100644 --- a/apps/desktop/src/file_state.rs +++ b/apps/desktop/src/file_state.rs @@ -2,8 +2,7 @@ //! read only) without touching the disk in the frame: a network drive that has lost its //! network (an NFS mount waits for it) would hold the whole window. A thread of its own //! looks at the files the screen asks about, again every few seconds; the screen reads -//! what it last found. A file not looked at yet counts as there. In a browser the -//! files are the page's, in memory: they are looked at when asked. +//! what it last found. A file not looked at yet counts as there. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -32,7 +31,6 @@ pub struct FileStates { const EVERY: Duration = Duration::from_secs(3); impl FileStates { - #[cfg(not(web))] pub fn new() -> Self { let shared = Arc::new(Mutex::new(Shared::default())); let looked = shared.clone(); @@ -57,21 +55,7 @@ impl FileStates { Self { shared } } - #[cfg(web)] - pub fn new() -> Self { - Self { - shared: Arc::default(), - } - } - - /// The file as it is (the page's files are in memory: no waiting). - #[cfg(web)] - pub fn get(&self, path: &Path) -> Option { - Some(look(path)) - } - /// The file as last found (`None`: not looked at yet); it is looked at from now on. - #[cfg(not(web))] pub fn get(&self, path: &Path) -> Option { let mut s = self.shared.lock().ok()?; if !s.asked.contains(path) { @@ -87,11 +71,11 @@ impl FileStates { } fn look(path: &Path) -> State { - match crate::platform::fs::meta(path) { + match std::fs::metadata(path) { Ok(m) => State { exists: true, - size: m.len, - readonly: m.readonly, + size: m.len(), + readonly: m.permissions().readonly(), }, Err(_) => State { exists: false, @@ -116,8 +100,8 @@ mod tests { // Not looked at yet: counted as there, nothing waited for. assert!(states.get(&there).is_none()); assert!(states.exists(&gone)); - let deadline = web_time::Instant::now() + Duration::from_secs(5); - while states.get(&gone).is_none() && web_time::Instant::now() < deadline { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while states.get(&gone).is_none() && std::time::Instant::now() < deadline { std::thread::sleep(Duration::from_millis(20)); } assert!(!states.exists(&gone)); diff --git a/apps/desktop/src/game_link.rs b/apps/desktop/src/game_link.rs deleted file mode 100644 index a29f587..0000000 --- a/apps/desktop/src/game_link.rs +++ /dev/null @@ -1,133 +0,0 @@ -//! The game's page on the site it was played on: Lichess writes it in the Site tag -//! («https://lichess.org/AbCdEfGh»), Chess.com in the Link tag (its Site is -//! «Chess.com»). A Lichess game opens at the move shown and from the side at the -//! bottom of the board; Chess.com's page has no such address, it opens at the start. - -use crate::i18n::tr; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Site { - Lichess, - ChessCom, - /// Another web address. - Other, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct GameLink { - pub url: String, - pub site: Site, - /// The Lichess game id (8 characters), when the address is a game's. - lichess_id: Option, -} - -/// The game's web address from its tags (Link first, then Site), if it has one. -pub fn of(tag: impl Fn(&str) -> Option) -> Option { - let url = ["Link", "Site"] - .into_iter() - .filter_map(&tag) - .map(|v| v.trim().to_owned()) - .find(|v| v.starts_with("https://") || v.starts_with("http://"))?; - let host_and_path = url.split_once("://").map_or("", |(_, rest)| rest); - let (host, path) = host_and_path.split_once('/').unwrap_or((host_and_path, "")); - let host = host.to_ascii_lowercase(); - let host = host.strip_prefix("www.").unwrap_or(&host); - let site = match host { - "lichess.org" => Site::Lichess, - "chess.com" => Site::ChessCom, - _ => Site::Other, - }; - // «AbCdEfGh», or the 12-character id of one player's view of it. - let first = path.split(['/', '#', '?']).next().unwrap_or(""); - let lichess_id = (site == Site::Lichess - && (first.len() == 8 || first.len() == 12) - && first.chars().all(|c| c.is_ascii_alphanumeric())) - .then(|| first[..8].to_owned()); - Some(GameLink { - url, - site, - lichess_id, - }) -} - -impl GameLink { - /// The address to open: a Lichess game at half-move `ply` (0: the start) from - /// Black's side when `black`; any other as written. - pub fn at(&self, ply: u32, black: bool) -> String { - match &self.lichess_id { - Some(id) => { - let mut url = format!("https://lichess.org/{id}"); - if black { - url.push_str("/black"); - } - if ply > 0 { - url.push_str(&format!("#{ply}")); - } - url - } - None => self.url.clone(), - } - } - - /// The globe's tooltip: «Open on Lichess (in the browser, at this move)». - pub fn hint(&self) -> &'static str { - match (self.site, self.lichess_id.is_some()) { - (Site::Lichess, true) => tr("Open on Lichess (in the browser, at this move)"), - (Site::Lichess, false) => tr("Open on Lichess (in the browser)"), - (Site::ChessCom, _) => tr("Open on Chess.com (in the browser)"), - (Site::Other, _) => tr("Open the game's link (in the browser)"), - } - } - - /// «🌐 Open on Lichess». - pub fn label(&self) -> &'static str { - match self.site { - Site::Lichess => tr("🌐 Open on Lichess"), - Site::ChessCom => tr("🌐 Open on Chess.com"), - Site::Other => tr("🌐 Open the game's link"), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn link(tags: &[(&str, &str)]) -> Option { - of(|name| { - tags.iter() - .find(|(n, _)| *n == name) - .map(|(_, v)| (*v).to_owned()) - }) - } - - #[test] - fn lichess_chess_com_and_others() { - let l = link(&[("Site", "https://lichess.org/AbCdEfGh")]).expect("lichess"); - assert_eq!(l.site, Site::Lichess); - assert_eq!(l.at(0, false), "https://lichess.org/AbCdEfGh"); - assert_eq!(l.at(23, true), "https://lichess.org/AbCdEfGh/black#23"); - // One player's view (12 characters): the game. - let l = link(&[("Site", "https://lichess.org/AbCdEfGh1234")]).unwrap(); - assert_eq!(l.at(4, false), "https://lichess.org/AbCdEfGh#4"); - // A study is opened as it is. - let s = link(&[("Site", "https://lichess.org/study/abcdefgh/ijklmnop")]).unwrap(); - assert_eq!( - s.at(10, true), - "https://lichess.org/study/abcdefgh/ijklmnop" - ); - let c = link(&[ - ("Site", "Chess.com"), - ("Link", "https://www.chess.com/game/live/123456789"), - ]) - .expect("chess.com"); - assert_eq!(c.site, Site::ChessCom); - assert_eq!(c.at(12, true), "https://www.chess.com/game/live/123456789"); - assert_eq!( - link(&[("Site", "http://example.org/g/1")]).unwrap().site, - Site::Other - ); - assert!(link(&[("Site", "Moscow RUS")]).is_none()); - assert!(link(&[("Site", "Chess.com")]).is_none()); - } -} diff --git a/apps/desktop/src/game_view.rs b/apps/desktop/src/game_view.rs index 5d6950c..627d6a1 100644 --- a/apps/desktop/src/game_view.rs +++ b/apps/desktop/src/game_view.rs @@ -15,12 +15,10 @@ use crate::analysis::{self, Analysis, PvLine, Status}; use crate::assets::Sound; use crate::board::{self, Arrow, BoardState, BoardView}; use crate::notation::{ - CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, ShapeCount, Slot, - toggle_nag, + CommentEditor, EditorOutcome, MOVE_NAGS, Notation, NotationCommand, Slot, toggle_nag, }; -use crate::review::{ReportAction, Review}; +use crate::review::{DialogAction, ReportAction, Review}; use crate::settings::Settings; -use std::collections::HashMap; /// Where an opened game came from (to return to the same library row, to save into). #[derive(Clone, Debug)] @@ -51,8 +49,6 @@ impl Preview { } pub struct GameView { - /// This view's own number (`engine_offer::next_serial`). - pub serial: u64, pub game: Game, pub source: Option, /// A new game meant for this database (the table's «+ Game»): Ctrl+S adds it there. @@ -84,15 +80,13 @@ pub struct GameView { play_start: Option, /// «The game is on» asked (leaving during a game); the clocks wait meanwhile. /// Where leaving goes, and since when the question is open. - play_leave: Option<(crate::app::CloseIntent, web_time::Instant)>, + play_leave: Option<(crate::app::CloseIntent, std::time::Instant)>, /// Learning an opening (this screen is the training). pub train: Option, /// A line from the clipboard that would go elsewhere than the user stands: asked. paste_pending: Option, /// Text to paste on the next frame (dev hook `CP_PASTE_LINE`). paste_request: Option, - /// The menu's «Paste a line»: the clipboard being read. - clipboard: Option, show_diagnostics: bool, engine_settings_open: bool, review: Review, @@ -101,14 +95,6 @@ pub struct GameView { side_tab: SideTab, /// The game this one was opened from (reference tab): the title for "← back to". pub previous: Option, - /// The game was opened from the opponent preparation: «⬅ Back to preparation». - pub previous_prep: bool, - /// The engine is busy with the opponent preparation: no game analysis meanwhile - /// (one engine job for the whole program, opponent-prep.md §4.3). - pub engine_busy: bool, - /// Why, when another job than the search for opening errors has it (the search for - /// great moves, task 27). - pub engine_busy_why: Option, /// The game's data were asked once (on its first add); not again. pub data_asked: bool, /// A newer version to offer (its number), next to Settings. @@ -117,27 +103,6 @@ pub struct GameView { translation: crate::translate_ui::GameTranslation, /// "Translate comments" was chosen (menu, Ctrl+Shift+T): done once the settings are at hand. translate_now: bool, - /// The moves whose comments draw on the board, for the notation's sign; by the - /// revision of the game they were counted at. - shape_counts: Option<(u64, HashMap)>, - /// The hint about drawing arrows above the notation: decided as the notation is - /// first drawn (`None`: not yet). - shapes_hint: Option, - /// An arrow or a circle went into the game on this frame (the hint has done its job). - shape_drawn: bool, - /// Dev hook `CP_BEST_DELAY`: the better line to open after the notation is drawn. - debug_best: Option, -} - -/// The better line opened on a timer (screenshots of the notation before, during and -/// after the line); times in seconds. -struct DebugBest { - shown: usize, - delay: f64, - exit: Option, - /// When the notation was first drawn. - start: Option, - opened: bool, } #[derive(Clone, Copy, PartialEq, Eq)] @@ -150,14 +115,12 @@ enum SideTab { pub enum GameAction { Back, - /// Ctrl+W: back to what the game was opened from, else to the library. - BackKey, /// Back to the library with this database chosen (the game's own). OpenDatabase(PathBuf), /// «Play on from here»: the play dialog for this position. PlayFrom(Box), - #[cfg(not(web))] - AddToRepertoire(Box, NodeId), + /// «Learn the opening up to this move»: the training over this game. + Train(Box), Sound(Sound), CopyText(String, &'static str), /// Ctrl+S: into the game's own database, else "Add to database…". @@ -185,24 +148,14 @@ pub enum GameAction { OpenEngineSettings, OpenSettings, Toast(String), - /// The analysis of a game of a database ended: its marks go into that database's - /// index (task 27), so its row shows them. - Reviewed { - path: PathBuf, - index: usize, - entry: crate::brilliant::Entry, - }, /// A whole-game analysis started: pause the live engine (they would share the CPU). PauseLive, /// The whole-game analysis ended: resume the live engine if it was paused. ResumeLive, /// Find the current position in a database (`None`: the last chosen one). FindPosition(Option), - /// Game analysis (`full`: anew) needs an engine that is not there yet (offer to - /// download one). - NeedEngine { - full: bool, - }, + /// Game analysis needs an engine that is not there yet (offer to download one). + NeedEngine, /// The reference tab: use / load a database, open one of its games. ReferenceChoose(std::path::PathBuf), ReferenceLoad(std::path::PathBuf), @@ -210,15 +163,9 @@ pub enum GameAction { /// Back to the game this one was opened from. ReturnToPrevious, /// The window offering a newer version. - #[cfg(not(web))] OpenUpdate, - /// The game's PGN as a downloaded file (the web version saves so). - #[cfg(web)] - DownloadPgn, /// Settings → Translation. OpenTranslationSettings, - /// A hint was shown or put away: the settings are to be written. - HintsChanged, } impl GameView { @@ -226,7 +173,6 @@ impl GameView { let flipped = false; let review = Review::new(&game); Self { - serial: crate::engine_offer::next_serial(), game, source, diagnostics, @@ -247,7 +193,6 @@ impl GameView { paste_pending: None, train: None, paste_request: None, - clipboard: None, show_diagnostics: false, engine_settings_open: false, review, @@ -259,18 +204,11 @@ impl GameView { SideTab::Notation }, previous: None, - previous_prep: false, - engine_busy: false, - engine_busy_why: None, data_asked: false, target: None, update: None, translation: Default::default(), translate_now: false, - shape_counts: None, - shapes_hint: None, - shape_drawn: false, - debug_best: None, } } @@ -279,11 +217,6 @@ impl GameView { self.translation.suspend(); } - /// The whole-game analysis is running. - pub fn review_running(&self) -> bool { - self.review.running() - } - /// Copying the PGN always copies the original comments; say so when the translation is shown. fn copy_pgn(&self) -> GameAction { let note = if self.translation.shown().is_some() { @@ -368,17 +301,6 @@ impl GameView { } } - /// The game's web page, if its tags have one. - fn link(&self) -> Option { - crate::game_link::of(|t| self.game.tag(t).map(str::to_owned)) - } - - /// Opens the game's page at the move shown, from the side at the bottom. - fn open_link(&self, ctx: &egui::Context, link: &crate::game_link::GameLink) { - let ply = self.game.node(self.cursor).map_or(0, |n| n.ply()); - ctx.open_url(egui::OpenUrl::new_tab(link.at(ply, self.flipped))); - } - fn subtitle(&self) -> String { if let Some(t) = &self.train { let up_to = trf( @@ -395,10 +317,7 @@ impl GameView { for t in ["Event", "Site", "Date", "ECO", "Annotator"] { if let Some(v) = g .tag(t) - // A web address is the globe's, not text. - .filter(|v| { - !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.') && !v.contains("://") - }) + .filter(|v| !v.is_empty() && !v.chars().all(|c| c == '?' || c == '.')) { parts.push(v.to_string()); } @@ -705,116 +624,7 @@ impl GameView { } } let comments = chess_core::with_shapes(node.comments_after(), &arrows, &squares); - if self - .game - .annotate(id, node.nags().to_vec(), comments) - .is_ok() - { - self.shape_drawn = true; - } - } - - /// The moves with arrows or circles in their comments, counted again after an edit. - fn shape_counts(&mut self) -> &HashMap { - let revision = self.game.revision(); - if self - .shape_counts - .as_ref() - .is_none_or(|(r, _)| *r != revision) - { - self.shape_counts = Some((revision, crate::notation::shape_counts(&self.game))); - } - &self.shape_counts.get_or_insert_default().1 - } - - /// Who this game is among those opened in the session (a hint counts a game once). - fn session_key(&self) -> String { - match &self.source { - Some(s) => format!("{}#{}", s.path.display(), s.index), - None => format!("view#{}", self.serial), - } - } - - /// Whether the hint about drawing on the board stands above the notation - /// (docs/design/tasks-42-43-2026-11-27.md §43.3). Decided once, as the notation is - /// first drawn: only where shapes go into the game, never with the translation strip - /// (then not counted either). Returns whether the hint's settings changed. - fn decide_shapes_hint( - &mut self, - hint: &mut crate::settings::Hint, - seen: &mut std::collections::HashSet, - translating: bool, - ) -> bool { - if self.shapes_hint.is_some() { - return false; - } - let possible = - !translating && self.preview.is_none() && self.play.is_none() && self.train.is_none(); - let key = self.session_key(); - let fresh = !seen.contains(&key); - let show = possible && hint.offer(fresh); - if show { - seen.insert(key); - } - self.shapes_hint = Some(show); - show && fresh - } - - /// The hint's strip: the translation strip's look, closed for good by its ×; dimmed - /// (its height kept) while the board shows an engine line and takes no drawing. - /// Returns whether the hint's settings changed. - fn shapes_hint_strip( - &mut self, - ui: &mut Ui, - hint: &mut crate::settings::Hint, - dim: bool, - ) -> bool { - let mut closed = false; - egui::Frame::new() - .fill(ui.visuals().faint_bg_color) - .inner_margin(egui::Margin::symmetric(8, 4)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - let row_h = ui.spacing().interact_size.y; - ui.horizontal_top(|ui| { - let close_w = 22.0 + ui.spacing().item_spacing.x; - ui.allocate_ui_with_layout( - vec2((ui.available_width() - close_w).max(120.0), 0.0), - egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true), - |ui| { - ui.set_min_height(row_h); - ui.add_enabled_ui(!dim, |ui| { - ui.add( - egui::Label::new(tr( - "Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.", - )) - .wrap(), - ) - .on_hover_text(tr( - "No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.", - )); - }); - }, - ); - ui.allocate_ui_with_layout( - vec2(22.0, row_h), - egui::Layout::left_to_right(egui::Align::Center), - |ui| { - if crate::widgets::small_close_button(ui) - .on_hover_text(tr("Don't show again")) - .clicked() - { - closed = true; - } - }, - ); - }); - }); - if closed { - hint.done = true; - self.shapes_hint = Some(false); - } - closed + let _ = self.game.annotate(id, node.nags().to_vec(), comments); } /// Assessment of the move that led to the current position, for the board: the @@ -874,33 +684,20 @@ impl GameView { ) -> Vec { let mut actions = Vec::new(); self.translation.update(ui.ctx(), &self.game, settings, hub); - let reviewed = self.review.poll(); - if reviewed { + if self.review.poll() { actions.push(GameAction::ResumeLive); if let Some(e) = &self.review.error { actions.push(GameAction::Toast(e.clone())); } } self.review.refresh(&self.game); - if reviewed - && self.review.error.is_none() - && !self.game.is_modified() - && self.review.missing() == 0 - && let Some(src) = &self.source - { - actions.push(GameAction::Reviewed { - path: src.path.clone(), - index: src.index, - entry: crate::brilliant::entry_of(&self.review.analysis, &self.game), - }); - } if analysis.status == Status::Running && let Some(e) = settings.active_engine() { self.review.note_live_speed(analysis.nps, e.threads); } self.play_tick(ui.ctx(), &mut actions); - if input_enabled && self.play_leave.is_none() { + if input_enabled && !self.review.dialog_open && self.play_leave.is_none() { self.editor_keys(ui, &mut actions); self.keyboard(ui, &mut actions); } @@ -975,39 +772,27 @@ impl GameView { egui::CentralPanel::default().show(ui, |ui| { self.board_area(ui, &*settings, analysis, hover, &mut actions) }); - // Drawn on the board: the hint has done its job (gone after the button is let go). - if std::mem::take(&mut self.shape_drawn) { - let hint = &mut settings.hints.board_shapes; - if !hint.done { - hint.done = true; - actions.push(GameAction::HintsChanged); - } - if self.shapes_hint == Some(true) { - self.shapes_hint = Some(false); - ui.ctx().request_repaint(); - } - } self.sync_analysis(analysis); - // «Analyse»: at once — the search is the same for everyone, nothing to choose. + // «Analyse»: at once with the options chosen before, else the dialog first. if std::mem::take(&mut self.review_asked) { - if self.engine_busy { - actions.push(GameAction::Toast( - self.engine_busy_why.clone().unwrap_or_else(|| { - tr("Opening errors are being searched — wait or stop it in the report") - .to_owned() - }), - )); + if settings.review.chosen { + self.start_review(settings, true, ui.ctx(), &mut actions); } else { - self.start_review(false, ui.ctx(), &mut actions); + self.review.dialog_open = true; } } + match self.review.dialog(ui.ctx(), settings) { + Some(DialogAction::Start) => { + settings.review.chosen = true; + self.start_review(settings, true, ui.ctx(), &mut actions); + } + Some(DialogAction::EngineSwitch) => actions.push(GameAction::EngineSwitch), + Some(DialogAction::OpenEngines) => actions.push(GameAction::OpenEngineSettings), + None => {} + } // A line from the clipboard: pasted, or asked about. - if let Some(text) = self.clipboard.as_ref().and_then(|r| r.poll()) { - self.clipboard = None; - self.paste_request = Some(text.unwrap_or_default()); - } if let Some(text) = self.paste_request.take() { self.paste_text(&text, &mut actions); } @@ -1050,15 +835,26 @@ impl GameView { actions } - /// Starts the game analysis with Stockfish 19 (ChessPenguin's, or the user's that - /// searches the same, `review_engine`); without it, the app finds one or offers to - /// download ours. - fn start_review(&mut self, full: bool, ctx: &egui::Context, actions: &mut Vec) { - let Some(path) = crate::review_engine::engine() else { - actions.push(GameAction::NeedEngine { full }); + fn start_review( + &mut self, + settings: &Settings, + full: bool, + ctx: &egui::Context, + actions: &mut Vec, + ) { + if !crate::engine_offer::EngineOffer::engine_ready(settings) { + self.review.dialog_open = false; + actions.push(GameAction::NeedEngine); + return; + } + let Some(engine) = settings.active_engine().cloned() else { + self.review.dialog_open = true; return; }; - if self.review.start(&self.game, &path, full, ctx) { + if self + .review + .start(&self.game, &engine, &settings.review, full, ctx) + { actions.push(GameAction::PauseLive); self.side_tab = SideTab::Report; } else if let Some(e) = &self.review.error { @@ -1092,18 +888,12 @@ impl GameView { .on_hover_text(tr( "Report: show or hide the evaluation graph and the report (Shift+A)", )); - } else if review_colored(ui, !self.engine_busy, |ui| { - ui.add_enabled(!self.engine_busy, egui::Button::new(big("📈"))) - }) - .on_hover_text(format!( - "{}\n{}", - tr("Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)"), - self.review.estimate() - )) - .on_disabled_hover_text(self.engine_busy_why.clone().unwrap_or_else(|| { - tr("Opening errors are being searched — wait or stop it in the report").to_owned() - })) - .clicked() + } else if ui + .button(big("📈")) + .on_hover_text(tr( + "Analyse game: accuracy, inaccuracies, mistakes, blunders (Shift+A)", + )) + .clicked() { self.review_asked = true; } @@ -1145,13 +935,10 @@ impl GameView { RichText::new(format!("ℹ {}", self.diagnostics.len())).weak() } }); - let back_to = self.previous.as_ref().map(|t| { - if self.previous_prep { - tr("⬅ Back to preparation").to_owned() - } else { - trf("⬅ Back to {game}", &[("game", t)]) - } - }); + let back_to = self + .previous + .as_ref() + .map(|t| trf("⬅ Back to {game}", &[("game", t)])); // The buttons are measured first: the title gets what they leave (shortened with // "…"; the result always shows). When it would get under 160 pt, the buttons // around it give up their words for their icons (the words go to the tooltips). @@ -1172,31 +959,15 @@ impl GameView { let right = |compact: bool| { button(ui, if compact { "⚙" } else { tr("⚙ Settings") }) + self.update.as_deref().map_or(0.0, |v| button(ui, v)) - + if cfg!(web) { - button( - ui, - if compact { - "⇩" - } else { - tr("⇩ Download PGN") - }, - ) - } else { - 0.0 - } - + if crate::platform::CAPS.reference { - button(ui, "⏷") - + button( - ui, - if compact { - "🔍" - } else { - tr("🔍 Find in database") - }, - ) - } else { - 0.0 - } + + button(ui, "⏷") + + button( + ui, + if compact { + "🔍" + } else { + tr("🔍 Find in database") + }, + ) + notes.as_ref().map_or(0.0, |n| button(ui, n.text())) }; // The result, or during a game against the computer its time control («5+3», «∞») @@ -1211,43 +982,24 @@ impl GameView { None => (None, ""), }, }; - // The game's page on Lichess or Chess.com: a globe after the result. - let link = self.link(); - let link_w = if link.is_some() { + let result_w = result.as_ref().map_or(0.0, |r| { ui.painter() .layout_no_wrap( - "🌐".to_owned(), - egui::TextStyle::Button.resolve(ui.style()), + format!(" {r} "), + egui::FontId::proportional(15.0), Color32::WHITE, ) .size() .x - + 2.0 * ui.spacing().button_padding.x + gap - } else { - 0.0 - }; - let result_w = link_w - + result.as_ref().map_or(0.0, |r| { - ui.painter() - .layout_no_wrap( - format!(" {r} "), - egui::FontId::proportional(15.0), - Color32::WHITE, - ) - .size() - .x - + gap - }); + }); let row = ui.available_width(); let compact = row - left(false) - right(false) - result_w < 160.0; let title_room = (row - left(compact) - right(compact)).max(0.0); ui.horizontal(|ui| { if ui .button(if compact { "⬅" } else { tr("⬅ Library") }) - .on_hover_text(if self.previous_prep { - tr("Back to the game list") - } else if self.previous.is_some() { + .on_hover_text(if self.previous.is_some() { tr("Back to the game list (Ctrl+W)") } else { tr("Back to the game list (Esc, Ctrl+W)") @@ -1259,13 +1011,13 @@ impl GameView { if let Some(b) = &back_to && ui .button(if compact { "⬅" } else { b.as_str() }) - .on_hover_text({ - let hint = if self.previous_prep { - tr("The preparation this game was opened from, as you left it (Esc, Ctrl+W)") - } else { + .on_hover_text(if compact { + format!( + "{b}\n{}", tr("The game this one was opened from, as you left it (Esc)") - }; - if compact { format!("{b}\n{hint}") } else { hint.to_owned() } + ) + } else { + tr("The game this one was opened from, as you left it (Esc)").to_owned() }) .clicked() { @@ -1313,11 +1065,6 @@ impl GameView { ) .on_hover_text(result_hint); } - if let Some(l) = &link - && ui.button("🌐").on_hover_text(l.hint()).clicked() - { - self.open_link(ui.ctx(), l); - } }); let sub: Vec = self .source_line() @@ -1330,31 +1077,24 @@ impl GameView { }, ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if crate::widgets::settings_button(ui, compact).clicked() { + if ui + .button(if compact { "⚙" } else { tr("⚙ Settings") }) + .on_hover_text(if compact { format!("{} (Ctrl+,)", tr("Settings")) } else { "Ctrl+,".to_owned() }) + .clicked() + { actions.push(GameAction::OpenSettings); } - #[cfg(not(web))] if let Some(v) = &self.update && crate::widgets::update_button(ui, v).clicked() { actions.push(GameAction::OpenUpdate); } - #[cfg(web)] - if ui - .button(if compact { "⇩" } else { tr("⇩ Download PGN") }) - .on_hover_text(tr( - "Download the game as a PGN file: the browser puts it where it puts downloads", - )) - .clicked() - { - actions.push(GameAction::DownloadPgn); - } // Find the position in a database: the last chosen one, or another. let searchable = self.search_line().is_some(); let why = tr("After a null move (--) this is a teaching scheme, not a position of a game: it is not searched"); // Not during a game against Maia: it would leave the game. let playing = self.play.is_some() || self.train.is_some(); - if !playing && crate::platform::CAPS.reference { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| { + if !playing { ui.add_enabled_ui(searchable && !databases.is_empty(), |ui| { ui.menu_button("⏷", |ui| { for db in databases { let name = db @@ -1602,7 +1342,6 @@ 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, @@ -1671,10 +1410,8 @@ impl GameView { egui::CentralPanel::default().show(ui, |ui| { ui.horizontal(|ui| { ui.selectable_value(&mut self.side_tab, SideTab::Notation, tr("Notation")); - if crate::platform::CAPS.reference { - ui.selectable_value(&mut self.side_tab, SideTab::Reference, tr("Reference")) - .on_hover_text(tr("What was played in this position in a database")); - } + ui.selectable_value(&mut self.side_tab, SideTab::Reference, tr("Reference")) + .on_hover_text(tr("What was played in this position in a database")); if report { ui.selectable_value(&mut self.side_tab, SideTab::Report, tr("Report")); } @@ -1723,33 +1460,15 @@ impl GameView { &[("n", &n)], ))); } - Some(ReportAction::Update) => self.start_review(false, ui.ctx(), actions), - Some(ReportAction::Analyse) => self.start_review(true, ui.ctx(), actions), + Some(ReportAction::Update) => { + self.start_review(settings, false, ui.ctx(), actions) + } + Some(ReportAction::Reanalyse) => self.review.dialog_open = true, None => {} } return; } - let strip_top = ui.cursor().top(); - let strip = if crate::platform::CAPS.translation { - self.translation.strip(ui, settings, hub) - } else { - None - }; - let translating = ui.cursor().top() > strip_top; - let seen_id = egui::Id::new("shapes_hint_games"); - let mut seen: std::collections::HashSet = - ui.data_mut(|d| d.get_temp(seen_id)).unwrap_or_default(); - let mut hints_changed = - self.decide_shapes_hint(&mut settings.hints.board_shapes, &mut seen, translating); - ui.data_mut(|d| d.insert_temp(seen_id, seen)); - if self.shapes_hint == Some(true) && !translating { - let dim = self.preview.is_some(); - hints_changed |= self.shapes_hint_strip(ui, &mut settings.hints.board_shapes, dim); - } - if hints_changed { - actions.push(GameAction::HintsChanged); - } - match strip { + match self.translation.strip(ui, settings, hub) { Some(crate::translate_ui::StripAction::OpenSettings) => { actions.push(GameAction::OpenTranslationSettings) } @@ -1761,8 +1480,6 @@ impl GameView { if std::mem::take(&mut self.translate_now) { self.translation.translate(ui.ctx(), settings, hub); } - self.shape_counts(); - self.debug_best_tick(ui.ctx()); egui::ScrollArea::vertical() .auto_shrink(false) .show(ui, |ui| { @@ -1780,7 +1497,6 @@ impl GameView { read_only: self.play.is_some(), dim_until: None, mistakes: None, - shapes: self.shape_counts.as_ref().map(|(_, c)| c), } .show(ui); if let Some(id) = resp.clicked { @@ -1823,14 +1539,11 @@ impl GameView { }); } if let Some((_, NotationCommand::Paste)) = resp.context { - self.paste_clipboard(ui.ctx()); + self.paste_clipboard(actions); } else if let Some((id, NotationCommand::PlayFrom)) = resp.context { self.play_from(id, actions); } else if let Some((id, NotationCommand::Train)) = resp.context { - #[cfg(not(web))] - self.add_repertoire_from(id, actions); - #[cfg(web)] - let _ = id; + self.train_from(id, actions); } else if let Some((id, cmd)) = resp.context { let result = match cmd { NotationCommand::Paste @@ -2213,28 +1926,15 @@ impl GameView { actions.push(GameAction::Save); ui.close(); } - if crate::platform::CAPS.own_databases - && ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() - { + if ui.button(tr("Add to database… (Ctrl+Shift+S)")).clicked() { actions.push(GameAction::AddToDatabase); ui.close(); } - if let Some(l) = self.link() - && ui.button(l.label()).clicked() - { - self.open_link(ui.ctx(), &l); - ui.close(); - } ui.separator(); if ui.button(tr("Copy PGN")).clicked() { actions.push(self.copy_pgn()); ui.close(); } - #[cfg(web)] - if ui.button(tr("⇩ Download PGN")).clicked() { - actions.push(GameAction::DownloadPgn); - ui.close(); - } if ui.button(tr("Copy FEN")).clicked() { if let Some(fen) = self.game.fen(self.cursor) { actions.push(GameAction::CopyText(fen, tr("FEN copied"))); @@ -2246,34 +1946,31 @@ impl GameView { .button(tr("Paste a line from the clipboard (Ctrl+V)")) .clicked() { - self.paste_clipboard(ui.ctx()); + self.paste_clipboard(actions); ui.close(); } - if self.play.is_none() && crate::platform::CAPS.play { + if self.play.is_none() { ui.separator(); if ui.button(tr("Play on from here… (Ctrl+G)")).clicked() { let at = self.cursor; self.play_from(at, actions); ui.close(); } - } - #[cfg(not(web))] - if self.play.is_none() && crate::platform::CAPS.training { - if !crate::platform::CAPS.play { - ui.separator(); - } let line = crate::train::TrainStart::from_game(&self.game, self.cursor); if ui - .add_enabled(line.is_some(), egui::Button::new(tr("Add to repertoire…"))) + .add_enabled( + line.is_some(), + egui::Button::new(tr("Learn the opening up to this move")), + ) .on_disabled_hover_text(if self.cursor == NodeId::ROOT { - tr("Select the move up to which to add") + tr("Select the move to learn up to") } else { tr("The line has a null move (--): it cannot be played on the board") }) .clicked() { let at = self.cursor; - self.add_repertoire_from(at, actions); + self.train_from(at, actions); ui.close(); } } @@ -2282,9 +1979,7 @@ impl GameView { ui.close(); } ui.separator(); - if crate::platform::CAPS.translation - && self.translation.can_translate() - && ui.button(tr("Translate comments")).clicked() + if self.translation.can_translate() && ui.button(tr("Translate comments")).clicked() { self.translate_now = true; self.side_tab = SideTab::Notation; @@ -2344,50 +2039,6 @@ impl GameView { } } - /// `debug_best_line` `delay` s after the notation is first drawn; closed (as by a - /// click on the game's move) `exit` s after it opened. - pub fn debug_best_line_later(&mut self, shown: usize, delay: f64, exit: Option) { - self.debug_best = Some(DebugBest { - shown, - delay, - exit, - start: None, - opened: false, - }); - } - - fn debug_best_tick(&mut self, ctx: &egui::Context) { - let Some(mut d) = self.debug_best.take() else { - return; - }; - let now = ctx.input(|i| i.time); - let start = *d.start.get_or_insert(now); - if !d.opened { - if now - start >= d.delay { - self.debug_best_line(d.shown); - d.opened = true; - d.start = Some(now); - } else { - ctx.request_repaint_after(std::time::Duration::from_secs_f64( - d.delay - (now - start), - )); - } - self.debug_best = Some(d); - return; - } - match d.exit { - Some(exit) if now - start >= exit => { - let base = self.cursor; - self.goto(base); - } - Some(exit) => { - ctx.request_repaint_after(std::time::Duration::from_secs_f64(exit - (now - start))); - self.debug_best = Some(d); - } - None => {} - } - } - /// Opens the better line of the first engine-marked move up to its `shown`-th move. pub fn debug_best_line(&mut self, shown: usize) { let mark = self @@ -2411,19 +2062,23 @@ impl GameView { } } - /// `how`: "ask" presses «Analyse», else the analysis starts. - pub fn debug_review(&mut self, ctx: &egui::Context, how: &str) { + /// `how`: "dialog" opens the dialog, "ask" presses «Analyse», else the analysis starts. + pub fn debug_review(&mut self, settings: &Settings, ctx: &egui::Context, how: &str) { match how { + "dialog" => self.review.dialog_open = true, "ask" => self.review_asked = true, - _ => self.start_review(false, ctx, &mut Vec::new()), + _ => self.start_review(settings, false, ctx, &mut Vec::new()), } } - /// Starts the game analysis right away (after an engine was found or installed for - /// it); `full` as it was asked. - pub fn start_review_now(&mut self, ctx: &egui::Context, full: bool) -> Vec { + /// Starts the game analysis right away (after an engine was installed for it). + pub fn start_review_now( + &mut self, + settings: &Settings, + ctx: &egui::Context, + ) -> Vec { let mut actions = Vec::new(); - self.start_review(full, ctx, &mut actions); + self.start_review(settings, true, ctx, &mut actions); actions } @@ -2462,9 +2117,7 @@ impl GameView { } pub fn show_reference_tab(&mut self) { - if crate::platform::CAPS.reference { - self.side_tab = SideTab::Reference; - } + self.side_tab = SideTab::Reference; } pub fn search_line(&self) -> Option<(Chess, Vec, bool)> { @@ -2472,19 +2125,6 @@ impl GameView { Some((start, line, self.flipped)) } - /// The cursor on move `ply` of the main line (0: the start; past the end: the - /// last move). - pub fn goto_ply(&mut self, ply: usize) { - let mut at = self.game.root(); - for _ in 0..ply { - match self.game.main_child(at) { - Some(n) => at = n, - None => break, - } - } - self.goto(at); - } - pub fn debug_advance(&mut self, plies: usize) { for _ in 0..plies { match self.game.main_child(self.cursor) { @@ -2506,7 +2146,7 @@ impl GameView { &mut self, start: crate::play::Start, (engine, file): (crate::play::Engine, std::path::PathBuf), - judge: Option, + judge: Option, record: Option, ctx: &egui::Context, ) { @@ -2616,7 +2256,7 @@ impl GameView { saved: &crate::play::Saved, to_move_left: Option, engine: (crate::play::Engine, std::path::PathBuf), - judge: Option, + judge: Option, journal: crate::player_games::Journal, ctx: &egui::Context, ) { @@ -2639,7 +2279,7 @@ impl GameView { let left = crate::play::times_left(&self.game, saved.floor, to_move_left); let clock = start .clock - .map(|tc| Clock::resumed(tc, left, to_move, web_time::Instant::now())); + .map(|tc| Clock::resumed(tc, left, to_move, std::time::Instant::now())); self.goto(end); self.begin_play(start, engine, judge, Some(journal), clock, floor, ctx); } @@ -2659,7 +2299,7 @@ impl GameView { &mut self, start: crate::play::Start, (engine, file): (crate::play::Engine, std::path::PathBuf), - judge: Option, + judge: Option, journal: Option, clock: Option, floor: NodeId, @@ -2673,7 +2313,7 @@ impl GameView { // it was heard before. let low_time_heard = clock .as_ref() - .is_some_and(|c| c.left(start.user, web_time::Instant::now()) <= c.low()); + .is_some_and(|c| c.left(start.user, std::time::Instant::now()) <= c.low()); self.play = Some(Session { journal, user: start.user, @@ -2684,18 +2324,20 @@ impl GameView { clock, opponent: match engine { crate::play::Engine::Maia(_) => Opponent::start(file, ctx), - #[cfg(not(web))] crate::play::Engine::Rodent(_) => { Opponent::start_rodent(file, start.style.clone(), Some(start.strength), ctx) } - #[cfg(web)] - crate::play::Engine::Rodent(_) => { - Opponent::not_started(tr("a browser cannot start it").to_owned()) - } }, resign_asked: false, low_time_heard, - judge: judge.and_then(|p| crate::play::start_judge(p, ctx)), + judge: judge.map(|p| { + let ctx = ctx.clone(); + crate::play::Judge::start( + uci::EngineConfig::new(p), + Vec::new(), + Box::new(move || ctx.request_repaint()), + ) + }), hopeless: 0, resign_offer: None, play_on: false, @@ -2865,7 +2507,7 @@ impl GameView { } return; } - let now = web_time::Instant::now(); + let now = std::time::Instant::now(); let clock = s .clock .as_ref() @@ -2902,7 +2544,7 @@ impl GameView { let Ok(id) = self.game.add_move(end, m) else { return; }; - let now = web_time::Instant::now(); + let now = std::time::Instant::now(); if let Some(s) = self.play.as_mut() { s.resign_asked = false; if let Some(c) = s.clock.as_mut() { @@ -2982,7 +2624,7 @@ impl GameView { && s.opponent.thinking { s.opponent.forget(); - s.resign_offer = Some(web_time::Instant::now()); + s.resign_offer = Some(std::time::Instant::now()); self.scroll_to_cursor = true; actions.push(GameAction::Sound(Sound::Defeat)); return; @@ -3022,7 +2664,7 @@ impl GameView { self.play_add(m, None, actions); } } - let now = web_time::Instant::now(); + let now = std::time::Instant::now(); let end_pos = self.game.position(self.play_end_node()).cloned(); let Some(s) = self.play.as_mut() else { return }; if let Some(c) = &s.clock @@ -3054,7 +2696,7 @@ impl GameView { }; s.opponent.forget(); self.board.clear_premove(); - let now = web_time::Instant::now(); + let now = std::time::Instant::now(); let left = s.clock.as_mut().map(|c| { c.stop(now); (c.left(s.user, now), c.left(!s.user, now)) @@ -3156,7 +2798,7 @@ impl GameView { let left = s .clock .as_ref() - .map(|c| c.left(to_move, web_time::Instant::now())); + .map(|c| c.left(to_move, std::time::Instant::now())); let aside = s .journal .take() @@ -3357,7 +2999,7 @@ impl GameView { self.goto(parent); let moved = self.user_moved(user); if let Some(c) = self.play.as_mut().and_then(|s| s.clock.as_mut()) { - c.take_back(user, moved, web_time::Instant::now()); + c.take_back(user, moved, std::time::Instant::now()); } } self.keep_journal(); @@ -3459,7 +3101,7 @@ impl GameView { pub fn ask_leave(&mut self, intent: crate::app::CloseIntent) { self.board.clear_premove(); if self.play_leave.is_none() { - self.play_leave = Some((intent, web_time::Instant::now())); + self.play_leave = Some((intent, std::time::Instant::now())); } } @@ -3657,7 +3299,6 @@ impl GameView { .and_then(|s| self.game.node(s.floor)) .map(|n| n.ply()), mistakes: None, - shapes: None, } .show(ui); if let Some(id) = resp.clicked { @@ -3678,7 +3319,7 @@ impl GameView { .into_iter() .chain(s.resign_offer) .min() - .unwrap_or_else(web_time::Instant::now); + .unwrap_or_else(std::time::Instant::now); let turn = self.play_turn(); let active = turn == side; let left = s.clock.as_ref().map(|c| c.left(side, now)); @@ -4122,21 +3763,6 @@ 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}]") @@ -4147,12 +3773,12 @@ impl GameView { match p { CommentPart::Annotation(Annotation::Arrows(list)) => { for (c, a, b) in list { - record(board::Drawn::Arrow(c, a, b)); + self.apply_shape(board::Drawn::Arrow(c, a, b)); } } CommentPart::Annotation(Annotation::Squares(list)) => { for (c, sq) in list { - record(board::Drawn::Circle(c, sq)); + self.apply_shape(board::Drawn::Circle(c, sq)); } } _ => {} @@ -4163,10 +3789,16 @@ impl GameView { // ----- learning an opening (docs/design/opening-trainer.md) ---------------------- - #[cfg(not(web))] - fn add_repertoire_from(&self, at: NodeId, actions: &mut Vec) { - if self.play.is_none() && crate::train::TrainStart::from_game(&self.game, at).is_some() { - actions.push(GameAction::AddToRepertoire(Box::new(self.game.clone()), at)); + /// «Learn the opening up to this move»: the training opens over this game. + fn train_from(&mut self, at: NodeId, actions: &mut Vec) { + if self.play.is_some() { + return; + } + self.commit_editor(); + self.preview = None; + if let Some(mut t) = crate::train::TrainStart::from_game(&self.game, at) { + t.flipped = self.flipped; + actions.push(GameAction::Train(Box::new(t))); } } @@ -4182,7 +3814,7 @@ impl GameView { if let Some(t) = self.train.as_mut() && let Some(f) = &t.flash { - let now = web_time::Instant::now(); + let now = std::time::Instant::now(); if now >= f.until { t.flash = None; } else { @@ -4231,7 +3863,7 @@ impl GameView { after, from: m.from().unwrap_or(m.to()), to: crate::board::ui_target(&m), - until: web_time::Instant::now() + crate::train::WRONG_SHOWN, + until: std::time::Instant::now() + crate::train::WRONG_SHOWN, }); actions.push(GameAction::Sound(Sound::Wrong)); } @@ -4321,7 +3953,6 @@ impl GameView { editor: None, read_only: true, dim_until: None, - shapes: None, mistakes: marks.as_ref(), } .show(ui); @@ -4367,18 +3998,17 @@ impl GameView { .size(15.0), ); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let white = pos.turn() == Color::White; - let long = if white { - tr("White to move") - } else { - tr("Black to move") + let (short, long) = match pos.turn() { + Color::White => ("♔", tr("♔ White to move")), + Color::Black => ("♚", tr("♚ Black to move")), }; // In a narrow panel the king alone says who moves. - let narrow = ui.available_width() < 110.0; - if !narrow { - ui.label(RichText::new(long).strong().size(15.0)); - } - ui.add(crate::widgets::side_king(white, 17.0).sense(egui::Sense::hover())) + let text = if ui.available_width() < 110.0 { + short + } else { + long + }; + ui.label(RichText::new(text).strong().size(15.0)) .on_hover_text(long); }); }); @@ -4724,12 +4354,6 @@ impl GameView { Some(t) } - #[cfg(not(web))] - pub fn debug_repertoire_source(&self) -> Option<(Game, NodeId)> { - crate::train::TrainStart::from_game(&self.game, self.cursor) - .map(|_| (self.game.clone(), self.cursor)) - } - /// Dev hook (`CP_TRAIN_MOVES`): moves of the training made as on the board (UCI; /// a wrong one is a mistake). pub fn debug_train_moves(&mut self, uci: &str) { @@ -4773,10 +4397,12 @@ impl GameView { // ----- a line from the clipboard (docs/design/paste-variation.md) ---------------- - /// The menu's «Paste a line from the clipboard»: the clipboard is read, the line - /// pasted once it is there (at once on a computer). - fn paste_clipboard(&mut self, ctx: &egui::Context) { - self.clipboard = Some(crate::platform::clipboard::read_text(ctx)); + /// The menu's «Paste a line from the clipboard»: the clipboard read now. + fn paste_clipboard(&mut self, actions: &mut Vec) { + let text = arboard::Clipboard::new() + .and_then(|mut c| c.get_text()) + .unwrap_or_default(); + self.paste_text(&text, actions); } /// Pastes `text` as a line: at once where the user stands, a question when it @@ -5088,16 +4714,6 @@ impl GameView { if i.consume_shortcut(&ctrl(Key::W)) { cmds.push("back"); } - // A browser keeps Ctrl+W, Ctrl+1…6 and Ctrl+Shift+C for itself - // (docs/design/web-version.md §4): Alt+←, plain 1…6 and Ctrl+C there. - if cfg!(web) { - if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::ALT, Key::ArrowLeft)) { - cmds.push("back"); - } - if i.consume_shortcut(&ctrl(Key::C)) { - cmds.push("copy"); - } - } if i.consume_shortcut(&ctrl(Key::G)) { cmds.push("play_from"); } @@ -5121,9 +4737,7 @@ impl GameView { (Key::Num5, "nag5"), (Key::Num6, "nag6"), ] { - if i.consume_shortcut(&ctrl(key)) - || (cfg!(web) && i.consume_key(Modifiers::NONE, key)) - { + if i.consume_shortcut(&ctrl(key)) { cmds.push(cmd); } } @@ -5176,16 +4790,14 @@ impl GameView { } "copy" => actions.push(self.copy_pgn()), "save" => actions.push(GameAction::Save), - "play_from" if crate::platform::CAPS.play => { + "play_from" => { let at = self.cursor; self.play_from(at, actions); } - "add_to_db" if crate::platform::CAPS.own_databases => { - actions.push(GameAction::AddToDatabase) - } + "add_to_db" => actions.push(GameAction::AddToDatabase), "game_data" => actions.push(GameAction::EditGameData), - "back" => actions.push(GameAction::BackKey), - "find" if crate::platform::CAPS.reference && self.search_line().is_some() => { + "back" => actions.push(GameAction::Back), + "find" if self.search_line().is_some() => { actions.push(GameAction::FindPosition(None)) } "back1" => self.step_back(), @@ -5210,7 +4822,7 @@ impl GameView { self.goto(end); } "flip" => self.flipped = !self.flipped, - "translate" if crate::platform::CAPS.translation => { + "translate" => { if self.translation.has_translation() { self.translation.toggle(); } else if self.translation.can_translate() { @@ -5382,20 +4994,13 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec format!("{} / {cores}", idx + 1), _ => format_mb(hash_steps[idx]), }; - // In a browser threads and memory are the platform's: one thread (the - // single-threaded engine), its memory (design §1.5). - let shown = if crate::platform::CAPS.engine_programs { - 4 - } else { - 2 - }; if slider >= 100.0 { ui.spacing_mut().slider_width = slider; egui::Grid::new("engine_settings_grid") .num_columns(3) .spacing(vec2(gap, 8.0)) .show(ui, |ui| { - for (i, (name, idx, len)) in rows.iter_mut().enumerate().take(shown) { + for (i, (name, idx, len)) in rows.iter_mut().enumerate() { ui.label(*name); settled |= index_slider(ui, idx, *len); ui.label(value(i, **idx)); @@ -5404,7 +5009,7 @@ fn engine_settings(ui: &mut Ui, settings: &mut Settings, actions: &mut Vec Option<(Square, Square)> { Some((m.from()?, board::ui_target(m))) } -pub(crate) fn shape_color(c: ShapeColor) -> Color32 { +fn shape_color(c: ShapeColor) -> Color32 { match c { ShapeColor::Red => Color32::from_rgba_unmultiplied(136, 32, 32, 170), ShapeColor::Green => Color32::from_rgba_unmultiplied(21, 120, 27, 170), @@ -5576,307 +5181,3 @@ fn paste_line_full(line: &[(u32, Color, String)]) -> String { .collect::>() .join(" ") } - -impl GameView { - /// The report tab and the graph shown (a game opened at a move the search for great - /// moves found). - pub fn show_report(&mut self) { - self.review.visible = true; - self.side_tab = SideTab::Report; - } -} - -/// «📈 Analyse game» in the colour of «!!» (task 26): the report it makes marks its finds -/// with it. Hover and press stay visible (egui's own states, shaded); a disabled button -/// keeps the usual look. -fn review_colored( - ui: &mut egui::Ui, - enabled: bool, - add: impl FnOnce(&mut egui::Ui) -> egui::Response, -) -> egui::Response { - if !enabled { - return add(ui); - } - let dark = ui.visuals().dark_mode; - let Some(fill) = crate::notation::assessment_text_color(Nag(3), dark) else { - return add(ui); - }; - // The icon dark on the dark theme's teal, white on the light one's (contrast ≥ 4.5:1). - let icon = if dark { - egui::Color32::from_rgb(0x1b, 0x1b, 0x1b) - } else { - egui::Color32::WHITE - }; - let (hover, press) = if dark { - ( - fill.lerp_to_gamma(egui::Color32::WHITE, 0.18), - fill.lerp_to_gamma(egui::Color32::BLACK, 0.15), - ) - } else { - ( - fill.lerp_to_gamma(egui::Color32::BLACK, 0.15), - fill.lerp_to_gamma(egui::Color32::BLACK, 0.3), - ) - }; - ui.scope(|ui| { - let w = &mut ui.visuals_mut().widgets; - for (state, color) in [ - (&mut w.inactive, fill), - (&mut w.hovered, hover), - (&mut w.active, press), - ] { - state.weak_bg_fill = color; - state.bg_fill = color; - state.fg_stroke.color = icon; - } - add(ui) - }) - .inner -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::settings::Hint; - use std::collections::HashSet; - - type Shapes = (Vec<(ShapeColor, Square, Square)>, Vec<(ShapeColor, Square)>); - - fn view(pgn: &str) -> GameView { - let parsed = chess_core::parse_str(pgn); - GameView::new(parsed.game, None, parsed.diagnostics) - } - - /// The node reached by these moves from the start, through any variation. - fn at(game: &Game, moves: &[&str]) -> NodeId { - moves.iter().fold(NodeId::ROOT, |node, san| { - *game - .children(node) - .iter() - .find(|c| game.game_move(**c).is_some_and(|m| m.san == *san)) - .unwrap_or_else(|| panic!("no {san} after {node:?}")) - }) - } - - fn sq(s: &str) -> Square { - s.parse().unwrap() - } - - fn arrow(color: ShapeColor, from: &str, to: &str) -> board::Drawn { - board::Drawn::Arrow(color, sq(from), sq(to)) - } - - fn shapes_at(game: &Game, id: NodeId) -> Shapes { - chess_core::shapes(game.node(id).unwrap().comments_after()) - } - - /// Written to PGN and read again: the shapes of the same node. - fn reread(game: &Game, moves: &[&str]) -> Shapes { - let text = chess_core::write_game(game, &Default::default()); - let back = chess_core::parse_str(&text).game; - shapes_at(&back, at(&back, moves)) - } - - #[test] - fn a_shape_goes_into_the_current_move_and_back_out() { - let mut v = view("1. e4 e5 {Open game [%clk 0:05:00]} $1 2. Nf3 *"); - let e5 = at(&v.game, &["e4", "e5"]); - v.goto(e5); - v.apply_shape(arrow(ShapeColor::Green, "g1", "f3")); - assert_eq!( - shapes_at(&v.game, e5), - (vec![(ShapeColor::Green, sq("g1"), sq("f3"))], vec![]) - ); - let node = v.game.node(e5).unwrap(); - assert_eq!(node.nags(), &[Nag(1)]); - let text = node.comments_after().join(" "); - assert!( - text.contains("Open game") && text.contains("[%clk 0:05:00]"), - "{text}" - ); - assert_eq!( - reread(&v.game, &["e4", "e5"]).0, - vec![(ShapeColor::Green, sq("g1"), sq("f3"))] - ); - - // Another colour repaints it, the same colour again takes it off. - v.apply_shape(arrow(ShapeColor::Red, "g1", "f3")); - assert_eq!( - shapes_at(&v.game, e5).0, - vec![(ShapeColor::Red, sq("g1"), sq("f3"))] - ); - v.apply_shape(arrow(ShapeColor::Red, "g1", "f3")); - assert!(shapes_at(&v.game, e5).0.is_empty()); - - // One step of undo per shape. - v.game.undo(); - assert_eq!( - shapes_at(&v.game, e5).0, - vec![(ShapeColor::Red, sq("g1"), sq("f3"))] - ); - v.game.undo(); - v.game.undo(); - assert_eq!(shapes_at(&v.game, e5), (vec![], vec![])); - assert!(!v.game.is_modified()); - } - - #[test] - fn circles_toggle_and_recolour() { - let mut v = view("1. d4 *"); - let d4 = at(&v.game, &["d4"]); - v.goto(d4); - v.apply_shape(board::Drawn::Circle(ShapeColor::Green, sq("d5"))); - v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5"))); - v.apply_shape(board::Drawn::Circle(ShapeColor::Yellow, sq("d5"))); - assert_eq!( - shapes_at(&v.game, d4).1, - vec![(ShapeColor::Yellow, sq("d5")), (ShapeColor::Blue, sq("e5"))] - ); - v.apply_shape(board::Drawn::Circle(ShapeColor::Blue, sq("e5"))); - assert_eq!( - shapes_at(&v.game, d4).1, - vec![(ShapeColor::Yellow, sq("d5"))] - ); - } - - #[test] - fn a_shape_at_the_start_stays_with_the_start() { - let mut v = view("{Intro} 1. e4 e5 *"); - v.apply_shape(arrow(ShapeColor::Blue, "e2", "e4")); - assert_eq!( - reread(&v.game, &[]).0, - vec![(ShapeColor::Blue, sq("e2"), sq("e4"))] - ); - let text = chess_core::write_game(&v.game, &Default::default()); - assert!(text.contains("Intro"), "{text}"); - assert!(shapes_at(&v.game, at(&v.game, &["e4"])).0.is_empty()); - } - - #[test] - fn a_shape_in_a_nested_variation_stays_there() { - let mut v = view("1. e4 e5 (1... c5 2. Nf3 (2. c3 d5) 2... d6) 2. Nf3 *"); - let path = ["e4", "c5", "c3", "d5"]; - let d5 = at(&v.game, &path); - v.goto(d5); - v.apply_shape(arrow(ShapeColor::Green, "e4", "d5")); - assert_eq!( - reread(&v.game, &path).0, - vec![(ShapeColor::Green, sq("e4"), sq("d5"))] - ); - assert!(reread(&v.game, &["e4", "e5"]).0.is_empty()); - } - - #[test] - fn a_shape_after_a_null_move_and_from_a_fen_with_move_zero() { - let mut v = view("1. e4 -- 2. d4 *"); - let null = at(&v.game, &["e4", "--"]); - v.goto(null); - v.apply_shape(board::Drawn::Circle(ShapeColor::Red, sq("d4"))); - assert_eq!( - reread(&v.game, &["e4", "--"]).1, - vec![(ShapeColor::Red, sq("d4"))] - ); - - let mut v = - view("[FEN \"4k3/8/8/8/8/8/8/4K3 b - - 0 0\"]\n[SetUp \"1\"]\n\n0... Kd7 1. Ke2 *"); - let kd7 = at(&v.game, &["Kd7"]); - v.goto(kd7); - v.apply_shape(arrow(ShapeColor::Yellow, "e1", "e2")); - assert_eq!( - reread(&v.game, &["Kd7"]).0, - vec![(ShapeColor::Yellow, sq("e1"), sq("e2"))] - ); - } - - #[test] - fn a_shape_drawn_marks_the_hint_done_and_counts_for_the_notation() { - let mut v = view("1. e4 e5 {[%csl Gd5]} *"); - assert_eq!(v.shape_counts().len(), 1); - let e4 = at(&v.game, &["e4"]); - v.goto(e4); - v.apply_shape(arrow(ShapeColor::Green, "g1", "f3")); - assert!(v.shape_drawn); - assert_eq!( - v.shape_counts().get(&e4), - Some(&ShapeCount { - arrows: 1, - circles: 0 - }) - ); - assert_eq!(v.shape_counts().len(), 2); - v.game.undo(); - assert_eq!(v.shape_counts().len(), 1); - } - - #[test] - fn the_hint_is_decided_once_per_game_and_not_beside_the_translation() { - let mut hint = Hint::default(); - let mut seen = HashSet::new(); - - // With the translation strip: not shown, not counted. - let mut v = view("1. e4 *"); - assert!(!v.decide_shapes_hint(&mut hint, &mut seen, true)); - assert_eq!(v.shapes_hint, Some(false)); - assert_eq!(hint.shown, 0); - assert!(seen.is_empty()); - - // Decided on the first frame only. - let mut v = view("1. e4 *"); - assert!(v.decide_shapes_hint(&mut hint, &mut seen, false)); - assert!(!v.decide_shapes_hint(&mut hint, &mut seen, false)); - assert_eq!((v.shapes_hint, hint.shown), (Some(true), 1)); - - // The same game opened again in the session: shown, not counted. - let source = |index| GameSource { - path: PathBuf::from("/tmp/a.pgn"), - index, - block: None, - }; - let open = |index| { - let mut v = view("1. e4 *"); - v.source = Some(source(index)); - v - }; - let mut a = open(0); - assert!(a.decide_shapes_hint(&mut hint, &mut seen, false)); - let mut again = open(0); - assert!(!again.decide_shapes_hint(&mut hint, &mut seen, false)); - assert_eq!((again.shapes_hint, hint.shown), (Some(true), 2)); - - let mut b = open(1); - b.decide_shapes_hint(&mut hint, &mut seen, false); - assert_eq!(hint.shown, 3); - // The third counted game opened again keeps the hint, uncounted. - let mut b_again = open(1); - assert!(!b_again.decide_shapes_hint(&mut hint, &mut seen, false)); - assert_eq!((b_again.shapes_hint, hint.shown), (Some(true), 3)); - // The fourth game: gone by itself. - let mut c = open(2); - assert!(!c.decide_shapes_hint(&mut hint, &mut seen, false)); - assert_eq!(c.shapes_hint, Some(false)); - } - - #[test] - fn the_hint_is_not_shown_while_playing_or_after_it_is_done() { - let mut seen = HashSet::new(); - let mut hint = Hint { - done: true, - shown: 0, - }; - let mut v = view("1. e4 *"); - v.decide_shapes_hint(&mut hint, &mut seen, false); - assert_eq!(v.shapes_hint, Some(false)); - - let mut hint = Hint::default(); - let mut v = view("1. e4 *"); - v.preview = Some(Preview { - base: NodeId::ROOT, - root: Chess::default(), - moves: Vec::new(), - san: Vec::new(), - shown: 0, - }); - v.decide_shapes_hint(&mut hint, &mut seen, false); - assert_eq!((v.shapes_hint, hint.shown), (Some(false), 0)); - } -} diff --git a/apps/desktop/src/graphics.rs b/apps/desktop/src/graphics.rs index 8a7091c..9ac715e 100644 --- a/apps/desktop/src/graphics.rs +++ b/apps/desktop/src/graphics.rs @@ -162,7 +162,7 @@ pub fn options(mode: Mode) -> WgpuConfiguration { /// and to stderr: a window that stops drawing says why there. One message repeated (a /// dropped frame each frame) is written once a minute with how many times it came. struct LibraryLog { - last: std::sync::Mutex>, + last: std::sync::Mutex>, /// `CP_LOG_FRAMES=1`: also how each frame reaches the screen (egui_wgpu's debug and /// trace messages: a frame skipped as "occluded" is said only there). frames: bool, @@ -194,7 +194,7 @@ impl log::Log for LibraryLog { } eprintln!("{text}"); log(&text); - *last = Some((text, web_time::Instant::now(), 0)); + *last = Some((text, std::time::Instant::now(), 0)); } fn flush(&self) {} @@ -227,8 +227,8 @@ pub fn log(line: &str) { if std::fs::metadata(&f).is_ok_and(|m| m.len() > 1 << 20) { let _ = std::fs::remove_file(&f); } - let now = web_time::SystemTime::now() - .duration_since(web_time::UNIX_EPOCH) + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) diff --git a/apps/desktop/src/i18n.rs b/apps/desktop/src/i18n.rs index d69cdc4..3b2e0c0 100644 --- a/apps/desktop/src/i18n.rs +++ b/apps/desktop/src/i18n.rs @@ -61,58 +61,46 @@ impl Lang { pub fn from_locales>(locales: impl IntoIterator) -> Lang { locales .into_iter() - .find_map(|l| Lang::from_locale(l.as_ref())) + .find_map(|l| { + // "ru-RU", "ru_RU.UTF-8", "de-CH", "es-419", "fr". + let code = l + .as_ref() + .split(['-', '_', '.', '@']) + .next()? + .to_ascii_lowercase(); + match code.as_str() { + "en" => Some(Lang::En), + "ru" => Some(Lang::Ru), + "fr" => Some(Lang::Fr), + "de" => Some(Lang::De), + "es" => Some(Lang::Es), + "it" => Some(Lang::It), + "pt" => Some(Lang::Pt), + "uz" => Some(Lang::Uz), + "kk" => Some(Lang::Kk), + _ => None, + } + }) .unwrap_or_default() } - /// The language of a locale ("ru-RU", "ru_RU.UTF-8", "de-CH", "es-419", "fr"), if - /// it is one of ours. - pub fn from_locale(locale: &str) -> Option { - let code = locale - .split(['-', '_', '.', '@']) - .next()? - .to_ascii_lowercase(); - match code.as_str() { - "en" => Some(Lang::En), - "ru" => Some(Lang::Ru), - "fr" => Some(Lang::Fr), - "de" => Some(Lang::De), - "es" => Some(Lang::Es), - "it" => Some(Lang::It), - "pt" => Some(Lang::Pt), - "uz" => Some(Lang::Uz), - "kk" => Some(Lang::Kk), - _ => None, - } - } - /// The language of this system (see [`Lang::from_locales`]). pub fn system() -> Lang { Lang::from_locales(sys_locale::get_locales()) } } -#[cfg(not(test))] static CURRENT: AtomicU8 = AtomicU8::new(0); -// Tests run in parallel threads: a test that switches the language switches only its own. -#[cfg(test)] -thread_local! { - static CURRENT: AtomicU8 = const { AtomicU8::new(0) }; -} pub fn set_lang(lang: Lang) { - #[cfg(not(test))] CURRENT.store(lang as u8, Ordering::Relaxed); - #[cfg(test)] - CURRENT.with(|c| c.store(lang as u8, Ordering::Relaxed)); } pub fn current() -> Lang { - #[cfg(not(test))] - let index = CURRENT.load(Ordering::Relaxed); - #[cfg(test)] - let index = CURRENT.with(|c| c.load(Ordering::Relaxed)); - Lang::ALL.get(index as usize).copied().unwrap_or_default() + Lang::ALL + .get(CURRENT.load(Ordering::Relaxed) as usize) + .copied() + .unwrap_or_default() } fn table() -> &'static HashMap<&'static str, &'static [&'static str; 9]> { @@ -132,17 +120,6 @@ pub fn tr(key: &'static str) -> &'static str { .unwrap_or(key) } -/// `key` in every language (English first; the same text once). -pub fn all_languages(key: &'static str) -> Vec<&'static str> { - let mut out = vec![key]; - for t in table().get(key).into_iter().flat_map(|row| row.iter()) { - if !out.contains(t) { - out.push(t); - } - } - out -} - /// "1 game", "5 games" in the interface language, with Russian plural forms /// ("1 партия", "3 партии", "5 партий"). pub fn games(n: usize) -> String { @@ -169,29 +146,6 @@ pub fn games(n: usize) -> String { } } -/// [`games`] as the object of a verb: «разберёт 1 партию» in Russian; the same as -/// [`games`] in the other languages. -pub fn games_object(n: usize) -> String { - match current() { - Lang::Ru if n % 10 == 1 && n % 100 != 11 => { - format!("{} партию", crate::large_db::grouped(n)) - } - _ => games(n), - } -} - -/// Whether `n` takes the singular in the current language (a verb or an adjective -/// after the number: «1 партия разобрана», «21 партия разобрана», «2 партии разобраны»). -pub fn is_one(n: usize) -> bool { - match current() { - Lang::Ru => n % 10 == 1 && n % 100 != 11, - Lang::Fr => n <= 1, - // The noun after a number stays singular, and so does what goes with it. - Lang::Uz | Lang::Kk => true, - _ => n == 1, - } -} - /// "1 text", "21 texts" (guiding texts of a database), with Russian plural forms /// ("1 текст", "3 текста", "5 текстов"). pub fn texts(n: usize) -> String { @@ -249,1877 +203,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]] = &[ - [ - "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", - "Повторить всё", - "Tout réviser", - "Alles wiederholen", - "Repasar todo", - "Ripassa tutto", - "Revisar tudo", - "Hammasini takrorlash", - "Барлығын қайталау", - ], - [ - "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", - "⬅ Партияға", - ], - [ - "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}", - ], - [ - "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 импорттаңыз немесе партиядан желі қосыңыз", - ], - [ - "review {n}", - "повторить {n}", - "réviser {n}", - "{n} wiederholen", - "repasar {n}", - "ripassare {n}", - "revisar {n}", - "takrorlash {n}", - "қайталау {n}", - ], - [ - "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", - "Новых ходов осталось", - "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}", - "{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", - "Бұл репертуарды оқу мүмкін болмады", - ], - [ - "Switch colour to Black", - "Сменить цвет на чёрные", - "Passer aux Noirs", - "Farbe auf Schwarz wechseln", - "Cambiar a negras", - "Passa al Nero", - "Mudar para pretas", - "Rangni qoraga almashtirish", - "Түсті қараға ауыстыру", - ], - [ - "Switch colour to White", - "Сменить цвет на белые", - "Passer aux Blancs", - "Farbe auf Weiß wechseln", - "Cambiar a blancas", - "Passa al Bianco", - "Mudar para brancas", - "Rangni oqqa almashtirish", - "Түсті аққа ауыстыру", - ], - [ - "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}", - ], - [ - "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} жаңасын үйрену", - ], - [ - "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}-партияда жүріс жоқ", - ], - [ - "Checking access to Lichess and Chess.com…", - "Проверяем доступность Lichess и Chess.com…", - "Vérification de l’accès à Lichess et Chess.com…", - "Zugriff auf Lichess und Chess.com wird geprüft…", - "Comprobando el acceso a Lichess y Chess.com…", - "Verifica dell’accesso a Lichess e Chess.com…", - "Verificando o acesso ao Lichess e ao Chess.com…", - "Lichess va Chess.com mavjudligi tekshirilmoqda…", - "Lichess пен Chess.com қолжетімділігі тексерілуде…", - ], - [ - "Saving progress…", - "Сохранение прогресса…", - "Enregistrement du progrès…", - "Fortschritt wird gespeichert…", - "Guardando progreso…", - "Salvataggio progressi…", - "Salvando progresso…", - "Natija saqlanmoqda…", - "Нәтиже сақталуда…", - ], - [ - "Train", - "Тренироваться", - "S’entraîner", - "Trainieren", - "Entrenar", - "Allenati", - "Treinar", - "Mashq qilish", - "Жаттығу", - ], - [ - "Learn new moves", - "Учить новые", - "Apprendre des coups", - "Neue Züge lernen", - "Aprender jugadas", - "Impara mosse", - "Aprender lances", - "Yangi yurishlar", - "Жаңа жүрістер", - ], - // --- the web version --- - [ - "This database is too big for the browser ({size}, the limit is {limit}). Sorry — open it in the desktop program.", - "База слишком большая для браузера ({size}, предел {limit}). Извините — откройте её в программе для компьютера.", - "Cette base est trop grande pour le navigateur ({size}, la limite est de {limit}). Désolé — ouvrez-la dans le programme pour ordinateur.", - "Diese Datenbank ist zu groß für den Browser ({size}, die Grenze liegt bei {limit}). Entschuldigung – öffnen Sie sie im Programm für den Computer.", - "Esta base es demasiado grande para el navegador ({size}, el límite es {limit}). Lo sentimos: ábrela en el programa para ordenador.", - "Questo database è troppo grande per il browser ({size}, il limite è {limit}). Ci dispiace: aprilo nel programma per computer.", - "Esta base é grande demais para o navegador ({size}, o limite é {limit}). Desculpe — abra no programa para computador.", - "Bu baza brauzer uchun juda katta ({size}, chegara {limit}). Kechirasiz — uni kompyuter dasturida oching.", - "Бұл база браузер үшін тым үлкен ({size}, шегі {limit}). Кешіріңіз — оны компьютерге арналған бағдарламада ашыңыз.", - ], - [ - "Download ChessPenguin for the computer", - "Скачать ChessPenguin для компьютера", - "Télécharger ChessPenguin pour ordinateur", - "ChessPenguin für den Computer herunterladen", - "Descargar ChessPenguin para ordenador", - "Scarica ChessPenguin per computer", - "Baixar o ChessPenguin para computador", - "ChessPenguin’ni kompyuter uchun yuklab olish", - "ChessPenguin-ді компьютерге жүктеп алу", - ], - [ - "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", - "База ChessBase состоит из нескольких файлов (.cbh, .cbg, .cba…). Выберите её папку или сразу все её файлы.", - "Une base ChessBase se compose de plusieurs fichiers (.cbh, .cbg, .cba…). Choisissez son dossier ou tous ses fichiers à la fois.", - "Eine ChessBase-Datenbank besteht aus mehreren Dateien (.cbh, .cbg, .cba…). Wählen Sie ihren Ordner oder alle ihre Dateien auf einmal.", - "Una base de ChessBase consta de varios archivos (.cbh, .cbg, .cba…). Elige su carpeta o todos sus archivos a la vez.", - "Un database ChessBase è composto da più file (.cbh, .cbg, .cba…). Scegli la sua cartella o tutti i suoi file insieme.", - "Uma base do ChessBase é formada por vários arquivos (.cbh, .cbg, .cba…). Escolha a pasta dela ou todos os arquivos de uma vez.", - "ChessBase bazasi bir nechta fayldan iborat (.cbh, .cbg, .cba…). Uning papkasini yoki barcha fayllarini birdaniga tanlang.", - "ChessBase базасы бірнеше файлдан тұрады (.cbh, .cbg, .cba…). Оның қалтасын немесе барлық файлдарын бірден таңдаңыз.", - ], - [ - "Allow access to the database's folder — its other files will be found by themselves.", - "Разрешите доступ к папке базы — остальные файлы базы найдутся сами.", - "Autorisez l'accès au dossier de la base — ses autres fichiers seront trouvés automatiquement.", - "Erlauben Sie den Zugriff auf den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.", - "Permite el acceso a la carpeta de la base: sus demás archivos se encontrarán solos.", - "Consenti l'accesso alla cartella del database: gli altri suoi file verranno trovati da soli.", - "Permita o acesso à pasta da base — os outros arquivos dela serão encontrados sozinhos.", - "Baza papkasiga ruxsat bering — uning qolgan fayllari o‘zi topiladi.", - "База қалтасына рұқсат беріңіз — оның қалған файлдары өздігінен табылады.", - ], - [ - "Choose the database's folder — its other files will be found by themselves.", - "Выберите папку базы — остальные файлы базы найдутся сами.", - "Choisissez le dossier de la base — ses autres fichiers seront trouvés automatiquement.", - "Wählen Sie den Ordner der Datenbank – ihre übrigen Dateien werden von selbst gefunden.", - "Elige la carpeta de la base: sus demás archivos se encontrarán solos.", - "Scegli la cartella del database: gli altri suoi file verranno trovati da soli.", - "Escolha a pasta da base — os outros arquivos dela serão encontrados sozinhos.", - "Baza papkasini tanlang — uning qolgan fayllari o‘zi topiladi.", - "База қалтасын таңдаңыз — оның қалған файлдары өздігінен табылады.", - ], - [ - "📁 Choose the database's folder", - "📁 Выбрать папку базы", - "📁 Choisir le dossier de la base", - "📁 Ordner der Datenbank wählen", - "📁 Elegir la carpeta de la base", - "📁 Scegli la cartella del database", - "📁 Escolher a pasta da base", - "📁 Baza papkasini tanlash", - "📁 База қалтасын таңдау", - ], - [ - "Choose the database's files", - "Выбрать файлы базы", - "Choisir les fichiers de la base", - "Dateien der Datenbank wählen", - "Elegir los archivos de la base", - "Scegli i file del database", - "Escolher os arquivos da base", - "Baza fayllarini tanlash", - "База файлдарын таңдау", - ], - [ - "There is no database in this folder (.pgn, .cbh, .cbv, .zip, .7z).", - "В этой папке нет базы (.pgn, .cbh, .cbv, .zip, .7z).", - "Ce dossier ne contient aucune base (.pgn, .cbh, .cbv, .zip, .7z).", - "In diesem Ordner gibt es keine Datenbank (.pgn, .cbh, .cbv, .zip, .7z).", - "En esta carpeta no hay ninguna base (.pgn, .cbh, .cbv, .zip, .7z).", - "In questa cartella non c'è nessun database (.pgn, .cbh, .cbv, .zip, .7z).", - "Não há nenhuma base nesta pasta (.pgn, .cbh, .cbv, .zip, .7z).", - "Bu papkada baza yo‘q (.pgn, .cbh, .cbv, .zip, .7z).", - "Бұл қалтада база жоқ (.pgn, .cbh, .cbv, .zip, .7z).", - ], - [ - "The browser doesn't have enough memory for this database. Open it in the desktop program.", - "Браузеру не хватает памяти для этой базы. Откройте её в программе для компьютера.", - "Le navigateur n'a pas assez de mémoire pour cette base. Ouvrez-la dans le programme pour ordinateur.", - "Dem Browser fehlt der Speicher für diese Datenbank. Öffnen Sie sie im Programm für den Computer.", - "Al navegador le falta memoria para esta base. Ábrela en el programa para ordenador.", - "Al browser manca la memoria per questo database. Aprilo nel programma per computer.", - "O navegador não tem memória suficiente para esta base. Abra no programa para computador.", - "Brauzerda bu baza uchun xotira yetmaydi. Uni kompyuter dasturida oching.", - "Браузерге бұл база үшін жад жетпейді. Оны компьютерге арналған бағдарламада ашыңыз.", - ], - [ - "A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.", - "Перетащенный файл не запоминается: после перезагрузки выберите его снова или сохраните копию в браузере.", - "Un fichier déposé n'est pas mémorisé : après un rechargement, choisissez-le à nouveau ou gardez-en une copie dans le navigateur.", - "Eine hineingezogene Datei wird nicht gemerkt: Wählen Sie sie nach dem Neuladen erneut oder behalten Sie eine Kopie im Browser.", - "Un archivo arrastrado no se recuerda: tras recargar, elíjalo de nuevo o guarde una copia en el navegador.", - "Un file trascinato non viene ricordato: dopo il ricaricamento sceglilo di nuovo o conserva una copia nel browser.", - "Um arquivo arrastado não é lembrado: após recarregar, escolha-o novamente ou guarde uma cópia no navegador.", - "Sudrab tashlangan fayl eslab qolinmaydi: qayta yuklangandan keyin uni yana tanlang yoki brauzerda nusxasini saqlang.", - "Сүйреп әкелінген файл есте сақталмайды: қайта жүктегеннен кейін оны қайта таңдаңыз немесе браузерде көшірмесін сақтаңыз.", - ], - [ - "🔒 Allow reading", - "🔒 Разрешить чтение", - "🔒 Autoriser la lecture", - "🔒 Lesen erlauben", - "🔒 Permitir lectura", - "🔒 Consenti la lettura", - "🔒 Permitir leitura", - "🔒 O‘qishga ruxsat berish", - "🔒 Оқуға рұқсат беру", - ], - [ - "The browser remembers this file and asks before the page reads it again.", - "Браузер помнит этот файл и спрашивает, прежде чем страница прочитает его снова.", - "Le navigateur se souvient de ce fichier et demande avant que la page le relise.", - "Der Browser merkt sich diese Datei und fragt, bevor die Seite sie erneut liest.", - "El navegador recuerda este archivo y pregunta antes de que la página vuelva a leerlo.", - "Il browser ricorda questo file e chiede prima che la pagina lo rilegga.", - "O navegador lembra este arquivo e pergunta antes que a página o leia novamente.", - "Brauzer bu faylni eslab qoladi va sahifa uni qayta o‘qishidan oldin so‘raydi.", - "Браузер бұл файлды есте сақтайды және бет оны қайта оқымас бұрын сұрайды.", - ], - [ - "There is an unsaved game: {title}, moves: {n}.", - "Есть несохранённая партия: {title}, ходов: {n}.", - "Il y a une partie non enregistrée : {title}, coups : {n}.", - "Es gibt eine nicht gespeicherte Partie: {title}, Züge: {n}.", - "Hay una partida sin guardar: {title}, jugadas: {n}.", - "C'è una partita non salvata: {title}, mosse: {n}.", - "Há uma partida não salva: {title}, lances: {n}.", - "Saqlanmagan partiya bor: {title}, yurishlar: {n}.", - "Сақталмаған партия бар: {title}, жүрістер: {n}.", - ], - [ - "📋 Keep a copy in the browser", - "📋 Оставить копию в браузере", - "📋 Garder une copie dans le navigateur", - "📋 Kopie im Browser behalten", - "📋 Guardar una copia en el navegador", - "📋 Tieni una copia nel browser", - "📋 Manter uma cópia no navegador", - "📋 Brauzerda nusxa qoldirish", - "📋 Браузерде көшірме қалдыру", - ], - [ - "The copy opens right away, without choosing the file. It is stored in this browser on this device and is lost if you clear the site's data. The file on disk is not changed.", - "Копия откроется сразу, без выбора файла. Она хранится в этом браузере на этом устройстве и пропадёт, если очистить данные сайта. Файл на диске не меняется.", - "La copie s'ouvre aussitôt, sans choisir le fichier. Elle est stockée dans ce navigateur sur cet appareil et disparaît si vous effacez les données du site. Le fichier sur le disque n'est pas modifié.", - "Die Kopie öffnet sich sofort, ohne die Datei zu wählen. Sie ist in diesem Browser auf diesem Gerät gespeichert und geht verloren, wenn Sie die Daten der Website löschen. Die Datei auf der Festplatte bleibt unverändert.", - "La copia se abre al instante, sin elegir el archivo. Se guarda en este navegador en este dispositivo y se pierde si borras los datos del sitio. El archivo del disco no cambia.", - "La copia si apre subito, senza scegliere il file. È salvata in questo browser su questo dispositivo e si perde se cancelli i dati del sito. Il file sul disco non cambia.", - "A cópia abre na hora, sem escolher o arquivo. Ela fica guardada neste navegador neste aparelho e se perde se você limpar os dados do site. O arquivo no disco não muda.", - "Nusxa faylni tanlamasdan darhol ochiladi. U shu qurilmadagi shu brauzerda saqlanadi va sayt ma’lumotlari tozalansa, yo‘qoladi. Diskdagi fayl o‘zgarmaydi.", - "Көшірме файлды таңдамай-ақ бірден ашылады. Ол осы құрылғыдағы осы браузерде сақталады және сайт деректерін тазаласаңыз, жоғалады. Дисктегі файл өзгермейді.", - ], - [ - "↻ Choose the file again", - "↻ Выбрать файл снова", - "↻ Choisir le fichier à nouveau", - "↻ Datei erneut wählen", - "↻ Elegir el archivo de nuevo", - "↻ Scegli di nuovo il file", - "↻ Escolher o arquivo de novo", - "↻ Faylni qayta tanlash", - "↻ Файлды қайта таңдау", - ], - [ - "This browser doesn't remember files: after a reload, choose the file again or keep a copy in the browser.", - "Этот браузер не запоминает файлы: после перезагрузки выберите файл снова или оставьте копию в браузере.", - "Ce navigateur ne retient pas les fichiers : après un rechargement, choisissez à nouveau le fichier ou gardez-en une copie dans le navigateur.", - "Dieser Browser merkt sich keine Dateien: Wählen Sie die Datei nach einem Neuladen erneut oder behalten Sie eine Kopie im Browser.", - "Este navegador no recuerda los archivos: tras recargar, elige el archivo de nuevo o guarda una copia en el navegador.", - "Questo browser non ricorda i file: dopo un ricaricamento scegli di nuovo il file o tienine una copia nel browser.", - "Este navegador não lembra os arquivos: depois de recarregar, escolha o arquivo de novo ou mantenha uma cópia no navegador.", - "Bu brauzer fayllarni eslab qolmaydi: qayta yuklangandan keyin faylni yana tanlang yoki brauzerda nusxa qoldiring.", - "Бұл браузер файлдарды есте сақтамайды: қайта жүктегеннен кейін файлды қайта таңдаңыз немесе браузерде көшірме қалдырыңыз.", - ], - [ - "A copy is kept in the browser", - "Копия оставлена в браузере", - "Une copie est gardée dans le navigateur", - "Eine Kopie ist im Browser gespeichert", - "Se guardó una copia en el navegador", - "Una copia è conservata nel browser", - "Uma cópia ficou no navegador", - "Nusxa brauzerda qoldirildi", - "Көшірме браузерде қалдырылды", - ], - [ - "Doesn't fit: the copy needs {need}, and the browser gives the site only {free} more. Free up space in “Browser data” or open the file from disk.", - "Не помещается: копии нужно {need}, а браузер даёт сайту ещё {free}. Освободите место в «Данных в браузере» или открывайте файл с диска.", - "Ne tient pas : la copie a besoin de {need}, et le navigateur ne donne plus que {free} au site. Libérez de la place dans « Données du navigateur » ou ouvrez le fichier depuis le disque.", - "Passt nicht: Die Kopie braucht {need}, der Browser gibt der Website nur noch {free}. Schaffen Sie Platz unter „Daten im Browser“ oder öffnen Sie die Datei von der Festplatte.", - "No cabe: la copia necesita {need} y el navegador solo da al sitio {free} más. Libera espacio en «Datos del navegador» o abre el archivo desde el disco.", - "Non ci sta: la copia richiede {need} e il browser concede al sito solo altri {free}. Libera spazio in «Dati del browser» o apri il file dal disco.", - "Não cabe: a cópia precisa de {need}, e o navegador dá ao site só mais {free}. Libere espaço em “Dados do navegador” ou abra o arquivo do disco.", - "Sig‘maydi: nusxaga {need} kerak, brauzer esa saytga yana {free} beradi. «Brauzerdagi ma’lumotlar»da joy bo‘shating yoki faylni diskdan oching.", - "Сыймайды: көшірмеге {need} керек, ал браузер сайтқа тағы {free} береді. «Браузердегі деректер» бөлімінде орын босатыңыз немесе файлды дисктен ашыңыз.", - ], - [ - "My games", - "Мои партии", - "Mes parties", - "Meine Partien", - "Mis partidas", - "Le mie partite", - "Minhas partidas", - "Mening partiyalarim", - "Менің партияларым", - ], - [ - "Browser data", - "Данные в браузере", - "Données du navigateur", - "Daten im Browser", - "Datos del navegador", - "Dati del browser", - "Dados do navegador", - "Brauzerdagi ma’lumotlar", - "Браузердегі деректер", - ], - [ - "Everything below is stored only here, on this device. Files on disk are not changed.", - "Всё ниже хранится только здесь, на этом устройстве. Файлы на диске не меняются.", - "Tout ce qui suit est stocké uniquement ici, sur cet appareil. Les fichiers sur le disque ne sont pas modifiés.", - "Alles Folgende ist nur hier auf diesem Gerät gespeichert. Dateien auf der Festplatte werden nicht geändert.", - "Todo lo de abajo se guarda solo aquí, en este dispositivo. Los archivos del disco no cambian.", - "Tutto ciò che segue è salvato solo qui, su questo dispositivo. I file sul disco non cambiano.", - "Tudo abaixo fica guardado só aqui, neste aparelho. Os arquivos no disco não mudam.", - "Quyidagilarning barchasi faqat shu yerda, shu qurilmada saqlanadi. Diskdagi fayllar o‘zgarmaydi.", - "Төмендегінің бәрі тек осында, осы құрылғыда сақталады. Дисктегі файлдар өзгермейді.", - ], - [ - "Used {used} · free for the site {free}", - "Занято {used} · свободно для сайта {free}", - "Utilisé {used} · libre pour le site {free}", - "Belegt {used} · frei für die Website {free}", - "Ocupado {used} · libre para el sitio {free}", - "Occupato {used} · libero per il sito {free}", - "Ocupado {used} · livre para o site {free}", - "Band {used} · sayt uchun bo‘sh {free}", - "Бос емес {used} · сайт үшін бос {free}", - ], - [ - "Persistent storage: on", - "Постоянное хранение: включено", - "Stockage persistant : activé", - "Dauerhafte Speicherung: an", - "Almacenamiento persistente: activado", - "Archiviazione persistente: attiva", - "Armazenamento persistente: ativado", - "Doimiy saqlash: yoqilgan", - "Тұрақты сақтау: қосулы", - ], - [ - "Persistent storage: not allowed by the browser", - "Постоянное хранение: не разрешено браузером", - "Stockage persistant : refusé par le navigateur", - "Dauerhafte Speicherung: vom Browser nicht erlaubt", - "Almacenamiento persistente: no permitido por el navegador", - "Archiviazione persistente: non consentita dal browser", - "Armazenamento persistente: não permitido pelo navegador", - "Doimiy saqlash: brauzer ruxsat bermagan", - "Тұрақты сақтау: браузер рұқсат етпеген", - ], - [ - "Ask the browser", - "Спросить браузер", - "Demander au navigateur", - "Browser fragen", - "Pedírselo al navegador", - "Chiedi al browser", - "Pedir ao navegador", - "Brauzerdan so‘rash", - "Браузерден сұрау", - ], - [ - "My games · {n}", - "Мои партии · {n}", - "Mes parties · {n}", - "Meine Partien · {n}", - "Mis partidas · {n}", - "Le mie partite · {n}", - "Minhas partidas · {n}", - "Mening partiyalarim · {n}", - "Менің партияларым · {n}", - ], - [ - "Download all as PGN", - "Скачать всё в PGN", - "Tout télécharger en PGN", - "Alles als PGN herunterladen", - "Descargar todo en PGN", - "Scarica tutto in PGN", - "Baixar tudo em PGN", - "Hammasini PGN qilib yuklab olish", - "Барлығын PGN етіп жүктеп алу", - ], - [ - "Stockfish 19 engine", - "Движок Stockfish 19", - "Moteur Stockfish 19", - "Engine Stockfish 19", - "Motor Stockfish 19", - "Motore Stockfish 19", - "Motor Stockfish 19", - "Stockfish 19 dvijogi", - "Stockfish 19 қозғалтқышы", - ], - [ - "If you clear the site's data in the browser, all of this is lost. Download your games as PGN to keep them.", - "Если очистить данные сайта в браузере, всё это пропадёт. Скачайте свои партии в PGN, чтобы не потерять их.", - "Si vous effacez les données du site dans le navigateur, tout cela est perdu. Téléchargez vos parties en PGN pour les garder.", - "Wenn Sie die Daten der Website im Browser löschen, geht all das verloren. Laden Sie Ihre Partien als PGN herunter, um sie zu behalten.", - "Si borras los datos del sitio en el navegador, todo esto se pierde. Descarga tus partidas en PGN para conservarlas.", - "Se cancelli i dati del sito nel browser, tutto questo va perso. Scarica le tue partite in PGN per conservarle.", - "Se você limpar os dados do site no navegador, tudo isso se perde. Baixe suas partidas em PGN para não perdê-las.", - "Agar brauzerda sayt ma’lumotlarini tozalasangiz, bularning barchasi yo‘qoladi. Partiyalaringizni saqlab qolish uchun ularni PGN qilib yuklab oling.", - "Браузерде сайт деректерін тазаласаңыз, мұның бәрі жоғалады. Партияларыңызды сақтау үшін оларды PGN етіп жүктеп алыңыз.", - ], - [ - "It evaluates the position, shows the best moves and reviews the game. It is downloaded once and kept in this browser.", - "Оценивает позицию, показывает лучшие ходы и разбирает партию. Скачивается один раз и хранится в этом браузере.", - "Il évalue la position, montre les meilleurs coups et analyse la partie. Il est téléchargé une fois et gardé dans ce navigateur.", - "Sie bewertet die Stellung, zeigt die besten Züge und analysiert die Partie. Sie wird einmal heruntergeladen und in diesem Browser gespeichert.", - "Evalúa la posición, muestra las mejores jugadas y analiza la partida. Se descarga una vez y se guarda en este navegador.", - "Valuta la posizione, mostra le mosse migliori e analizza la partita. Si scarica una volta e resta in questo browser.", - "Avalia a posição, mostra os melhores lances e analisa a partida. É baixado uma vez e fica guardado neste navegador.", - "U pozitsiyani baholaydi, eng yaxshi yurishlarni ko‘rsatadi va partiyani tahlil qiladi. Bir marta yuklab olinadi va shu brauzerda saqlanadi.", - "Ол позицияны бағалайды, ең жақсы жүрістерді көрсетеді және партияны талдайды. Бір рет жүктеліп, осы браузерде сақталады.", - ], - [ - "Size: {size}", - "Размер: {size}", - "Taille : {size}", - "Größe: {size}", - "Tamaño: {size}", - "Dimensione: {size}", - "Tamanho: {size}", - "Hajmi: {size}", - "Көлемі: {size}", - ], - [ - "free for the site: {free}", - "свободно для сайта: {free}", - "libre pour le site : {free}", - "frei für die Website: {free}", - "libre para el sitio: {free}", - "libero per il sito: {free}", - "livre para o site: {free}", - "sayt uchun bo‘sh: {free}", - "сайт үшін бос: {free}", - ], - [ - "Not a database: {files}. ChessPenguin opens .pgn, .cbh, .cbv, .zip and .7z files.", - "Это не база: {files}. ChessPenguin открывает файлы .pgn, .cbh, .cbv, .zip и .7z.", - "Ce n’est pas une base : {files}. ChessPenguin ouvre les fichiers .pgn, .cbh, .cbv, .zip et .7z.", - "Keine Datenbank: {files}. ChessPenguin öffnet .pgn-, .cbh-, .cbv-, .zip- und .7z-Dateien.", - "No es una base: {files}. ChessPenguin abre archivos .pgn, .cbh, .cbv, .zip y .7z.", - "Non è un database: {files}. ChessPenguin apre i file .pgn, .cbh, .cbv, .zip e .7z.", - "Não é uma base: {files}. O ChessPenguin abre arquivos .pgn, .cbh, .cbv, .zip e .7z.", - "Bu baza emas: {files}. ChessPenguin .pgn, .cbh, .cbv, .zip va .7z fayllarini ochadi.", - "Бұл база емес: {files}. ChessPenguin .pgn, .cbh, .cbv, .zip және .7z файлдарын ашады.", - ], - [ - "Release to open", - "Отпустите, чтобы открыть", - "Relâchez pour ouvrir", - "Zum Öffnen loslassen", - "Suelta para abrir", - "Rilascia per aprire", - "Solte para abrir", - "Ochish uchun qo‘yib yuboring", - "Ашу үшін жіберіңіз", - ], - [ - "⇩ Download PGN", - "⇩ Скачать PGN", - "⇩ Télécharger le PGN", - "⇩ PGN herunterladen", - "⇩ Descargar PGN", - "⇩ Scarica PGN", - "⇩ Baixar PGN", - "⇩ PGN yuklab olish", - "⇩ PGN жүктеп алу", - ], - [ - "Download the game as a PGN file: the browser puts it where it puts downloads", - "Скачать партию файлом PGN: браузер положит его туда же, куда все загрузки", - "Télécharger la partie en fichier PGN : le navigateur le met avec les autres téléchargements", - "Die Partie als PGN-Datei herunterladen: Der Browser legt sie zu den anderen Downloads", - "Descargar la partida como archivo PGN: el navegador lo guarda con las demás descargas", - "Scarica la partita come file PGN: il browser lo mette insieme agli altri download", - "Baixar a partida como arquivo PGN: o navegador o coloca junto dos outros downloads", - "Partiyani PGN fayl sifatida yuklab olish: brauzer uni boshqa yuklamalar qatoriga qo‘yadi", - "Партияны PGN файлы ретінде жүктеп алу: браузер оны басқа жүктемелермен бірге сақтайды", - ], - [ - "The PGN could not be downloaded: {e}", - "Не удалось скачать PGN: {e}", - "Impossible de télécharger le PGN : {e}", - "PGN konnte nicht heruntergeladen werden: {e}", - "No se pudo descargar el PGN: {e}", - "Impossibile scaricare il PGN: {e}", - "Não foi possível baixar o PGN: {e}", - "PGN yuklab olinmadi: {e}", - "PGN жүктеп алынбады: {e}", - ], - [ - "a browser cannot start it", - "браузер не может его запустить", - "un navigateur ne peut pas le lancer", - "ein Browser kann ihn nicht starten", - "un navegador no puede iniciarlo", - "un browser non può avviarlo", - "um navegador não consegue iniciá-lo", - "brauzer uni ishga tushira olmaydi", - "браузер оны іске қоса алмайды", - ], // --- engine download --- [ "Stockfish installed — game analysis started", @@ -3518,83 +1601,6 @@ const ROWS: &[[&str; 9]] = &[ "Bu partiya uchun yashirish", "Бұл партия үшін жасыру", ], - [ - "Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game.", - "Стрелки и круги: правая кнопка мыши на доске — протяните или щёлкните. Сохраняются в партии.", - "Flèches et cercles : faites glisser ou cliquez avec le bouton droit de la souris sur l’échiquier. Ils sont enregistrés dans la partie.", - "Pfeile und Kreise: mit der rechten Maustaste auf dem Brett ziehen oder klicken. Sie werden in der Partie gespeichert.", - "Flechas y círculos: arrastra o haz clic con el botón derecho del ratón en el tablero. Se guardan en la partida.", - "Frecce e cerchi: trascina o fai clic con il tasto destro del mouse sulla scacchiera. Vengono salvati nella partita.", - "Setas e círculos: arraste ou clique com o botão direito do mouse no tabuleiro. Eles são salvos na partida.", - "Strelkalar va doiralar: taxtada sichqonchaning o‘ng tugmasi bilan torting yoki bosing. Ular partiyada saqlanadi.", - "Көрсеткілер мен шеңберлер: тақтада тышқанның оң жақ батырмасымен сүйреңіз немесе басыңыз. Олар партияда сақталады.", - ], - [ - "No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes.", - "Без клавиши — зелёный, Shift — красный, Alt — синий, Shift+Alt — жёлтый. Та же фигура ещё раз — убрать. Ctrl+Z — отменить.", - "Sans touche — vert, Maj — rouge, Alt — bleu, Maj+Alt — jaune. Tracez la même forme à nouveau pour la retirer. Ctrl+Z annule.", - "Ohne Taste — grün, Umschalt — rot, Alt — blau, Umschalt+Alt — gelb. Dieselbe Form noch einmal zeichnen entfernt sie. Strg+Z macht rückgängig.", - "Sin tecla — verde, Mayús — rojo, Alt — azul, Mayús+Alt — amarillo. Dibuja la misma otra vez para quitarla. Ctrl+Z deshace.", - "Senza tasto — verde, Maiusc — rosso, Alt — blu, Maiusc+Alt — giallo. Disegna di nuovo la stessa per toglierla. Ctrl+Z annulla.", - "Sem tecla — verde, Shift — vermelho, Alt — azul, Shift+Alt — amarelo. Desenhe a mesma de novo para removê-la. Ctrl+Z desfaz.", - "Tugmasiz — yashil, Shift — qizil, Alt — ko‘k, Shift+Alt — sariq. Xuddi shuni yana chizsangiz, olib tashlanadi. Ctrl+Z — bekor qilish.", - "Пернесіз — жасыл, Shift — қызыл, Alt — көк, Shift+Alt — сары. Сол пішінді қайта салсаңыз — алынып тасталады. Ctrl+Z — болдырмау.", - ], - [ - "Don't show again", - "Больше не показывать", - "Ne plus afficher", - "Nicht mehr anzeigen", - "No volver a mostrar", - "Non mostrare più", - "Não mostrar novamente", - "Boshqa ko‘rsatilmasin", - "Енді көрсетпеу", - ], - [ - "Arrows: {a} · circles: {c} — shown on the board at this move", - "Стрелки: {a} · круги: {c} — видны на доске на этом ходу", - "Flèches : {a} · cercles : {c} — affichés sur l’échiquier à ce coup", - "Pfeile: {a} · Kreise: {c} — bei diesem Zug auf dem Brett zu sehen", - "Flechas: {a} · círculos: {c} — se ven en el tablero en esta jugada", - "Frecce: {a} · cerchi: {c} — visibili sulla scacchiera a questa mossa", - "Setas: {a} · círculos: {c} — aparecem no tabuleiro neste lance", - "Strelkalar: {a} · doiralar: {c} — shu yurishda taxtada ko‘rinadi", - "Көрсеткілер: {a} · шеңберлер: {c} — осы жүрісте тақтада көрінеді", - ], - [ - "Arrows: {a} — shown on the board at this move", - "Стрелки: {a} — видны на доске на этом ходу", - "Flèches : {a} — affichées sur l’échiquier à ce coup", - "Pfeile: {a} — bei diesem Zug auf dem Brett zu sehen", - "Flechas: {a} — se ven en el tablero en esta jugada", - "Frecce: {a} — visibili sulla scacchiera a questa mossa", - "Setas: {a} — aparecem no tabuleiro neste lance", - "Strelkalar: {a} — shu yurishda taxtada ko‘rinadi", - "Көрсеткілер: {a} — осы жүрісте тақтада көрінеді", - ], - [ - "Circles: {c} — shown on the board at this move", - "Круги: {c} — видны на доске на этом ходу", - "Cercles : {c} — affichés sur l’échiquier à ce coup", - "Kreise: {c} — bei diesem Zug auf dem Brett zu sehen", - "Círculos: {c} — se ven en el tablero en esta jugada", - "Cerchi: {c} — visibili sulla scacchiera a questa mossa", - "Círculos: {c} — aparecem no tabuleiro neste lance", - "Doiralar: {c} — shu yurishda taxtada ko‘rinadi", - "Шеңберлер: {c} — осы жүрісте тақтада көрінеді", - ], - [ - "Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).", - "Стрелки и круги — правая кнопка мыши на доске; Shift — красный, Alt — синий, Shift+Alt — жёлтый. Сохраняются в комментарии хода ([%cal], [%csl]).", - "Flèches et cercles : bouton droit de la souris sur l’échiquier ; Maj — rouge, Alt — bleu, Maj+Alt — jaune. Enregistrés dans le commentaire du coup ([%cal], [%csl]).", - "Pfeile und Kreise: rechte Maustaste auf dem Brett; Umschalt — rot, Alt — blau, Umschalt+Alt — gelb. Gespeichert im Kommentar des Zuges ([%cal], [%csl]).", - "Flechas y círculos: botón derecho del ratón en el tablero; Mayús — rojo, Alt — azul, Mayús+Alt — amarillo. Se guardan en el comentario de la jugada ([%cal], [%csl]).", - "Frecce e cerchi: tasto destro del mouse sulla scacchiera; Maiusc — rosso, Alt — blu, Maiusc+Alt — giallo. Salvati nel commento della mossa ([%cal], [%csl]).", - "Setas e círculos: botão direito do mouse no tabuleiro; Shift — vermelho, Alt — azul, Shift+Alt — amarelo. Salvos no comentário do lance ([%cal], [%csl]).", - "Strelkalar va doiralar — taxtada sichqonchaning o‘ng tugmasi; Shift — qizil, Alt — ko‘k, Shift+Alt — sariq. Yurish izohida saqlanadi ([%cal], [%csl]).", - "Көрсеткілер мен шеңберлер — тақтада тышқанның оң жақ батырмасы; Shift — қызыл, Alt — көк, Shift+Alt — сары. Жүріс түсініктемесінде сақталады ([%cal], [%csl]).", - ], [ "The model is loading into memory — this can take up to a minute…", "Модель загружается в память — это бывает до минуты…", @@ -5307,17 +3313,6 @@ const ROWS: &[[&str; 9]] = &[ "Tiklash", "Қалпына келтіру", ], - [ - "Reset statistics for this repertoire and color?", - "Сбросить статистику этого репертуара и цвета?", - "Réinitialiser les statistiques de ce répertoire et de cette couleur ?", - "Statistik für dieses Repertoire und diese Farbe zurücksetzen?", - "¿Restablecer las estadísticas de este repertorio y color?", - "Azzerare le statistiche di questo repertorio e colore?", - "Redefinir as estatísticas deste repertório e cor?", - "Ushbu repertuar va rang statistikasi tiklansinmi?", - "Осы репертуар мен түстің статистикасы қалпына келтірилсін бе?", - ], [ "Starting position (Ctrl+Backspace)", "Начальная позиция (Ctrl+Backspace)", @@ -9897,17 +7892,6 @@ const ROWS: &[[&str; 9]] = &[ "PGNdagi baholar ([%eval])", "PGN-дағы бағалар ([%eval])", ], - [ - "Analyse again", - "Обновить", - "Mettre à jour", - "Aktualisieren", - "Actualizar", - "Aggiorna", - "Atualizar", - "Yangilash", - "Жаңарту", - ], [ "Update", "Дополнить", @@ -9941,6 +7925,17 @@ const ROWS: &[[&str; 9]] = &[ "Partiyaga baholar, !!/!/?!/?/?? belgilari, izohlar va yaxshiroq liniyalarni qo‘shadi (bekor qilish: Ctrl+Z)", "Партияға бағаларды, !!/!/?!/?/?? белгілерін, түсініктемелер мен жақсырақ варианттарды қосады (болдырмау — Ctrl+Z)", ], + [ + "Analyse again…", + "Проанализировать заново…", + "Analyser de nouveau…", + "Erneut analysieren…", + "Analizar de nuevo…", + "Analizza di nuovo…", + "Analisar de novo…", + "Qayta tahlil qilish…", + "Қайта талдау…", + ], [ "Go to the next one", "Перейти к следующей", @@ -9974,6 +7969,50 @@ const ROWS: &[[&str; 9]] = &[ "Aniqlik", "Дәлдік", ], + [ + "The engine evaluates every position of the main line. The game itself is not changed.", + "Движок оценит каждую позицию основной линии. Сама партия не изменится.", + "Le moteur évalue chaque position de la ligne principale. La partie elle-même n'est pas modifiée.", + "Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.", + "El motor evalúa cada posición de la línea principal. La partida en sí no cambia.", + "Il motore valuta ogni posizione della linea principale. La partita non viene modificata.", + "O motor avalia cada posição da linha principal. A partida em si não é alterada.", + "Dvigatel asosiy liniyaning har bir pozitsiyasini baholaydi. Partiyaning o‘zi o‘zgarmaydi.", + "Қозғалтқыш негізгі варианттың әр позициясын бағалайды. Партияның өзі өзгермейді.", + ], + [ + "Quality", + "Качество", + "Qualité", + "Qualität", + "Calidad", + "Qualità", + "Qualidade", + "Sifat", + "Сапа", + ], + [ + "Analyse", + "Анализировать", + "Analyser", + "Analysieren", + "Analizar", + "Analizza", + "Analisar", + "Tahlil qilish", + "Талдау", + ], + [ + "Add an engine first", + "Сначала добавьте движок", + "Ajoutez d'abord un moteur", + "Zuerst eine Engine hinzufügen", + "Primero añade un motor", + "Aggiungi prima un motore", + "Adicione um motor primeiro", + "Avval dvigatel qo‘shing", + "Алдымен қозғалтқыш қосыңыз", + ], [ "Inaccuracy", "Неточность", @@ -10073,6 +8112,17 @@ const ROWS: &[[&str; 9]] = &[ "Bahosiz pozitsiyalar: {n}", "Бағасыз позициялар: {n}", ], + [ + "{quality} · {nodes} nodes", + "{quality} · {nodes} узлов", + "{quality} · {nodes} nœuds", + "{quality} · {nodes} Knoten", + "{quality} · {nodes} nodos", + "{quality} · {nodes} nodi", + "{quality} · {nodes} nós", + "{quality} · {nodes} tugun", + "{quality} · {nodes} түйін", + ], [ "{n} positions, about {time}", "Позиций: {n}, примерно {time}", @@ -10117,6 +8167,17 @@ const ROWS: &[[&str; 9]] = &[ "Oddiy", "Қалыпты", ], + [ + "Deep", + "Глубоко", + "Approfondi", + "Gründlich", + "Profundo", + "Approfondito", + "Profunda", + "Chuqur", + "Терең", + ], // Engines [ "The built-in engine is not part of this build", @@ -12544,6 +10605,17 @@ const ROWS: &[[&str; 9]] = &[ "Rangingiz", "Түсіңіз", ], + [ + "♔ White", + "♔ Белые", + "♔ Blancs", + "♔ Weiß", + "♔ Blancas", + "♔ Bianco", + "♔ Brancas", + "♔ Oqlar", + "♔ Ақтар", + ], [ "Random", "Случайно", @@ -12555,6 +10627,17 @@ const ROWS: &[[&str; 9]] = &[ "Tasodifiy", "Кездейсоқ", ], + [ + "♚ Black", + "♚ Чёрные", + "♚ Noirs", + "♚ Schwarz", + "♚ Negras", + "♚ Nero", + "♚ Pretas", + "♚ Qoralar", + "♚ Қаралар", + ], [ "Time", "Время", @@ -14998,6 +13081,28 @@ const ROWS: &[[&str; 9]] = &[ "Yurish {n} / {last}", "Жүріс {n} / {last}", ], + [ + "♔ White to move", + "♔ ход белых", + "♔ Trait aux Blancs", + "♔ Weiß am Zug", + "♔ Juegan blancas", + "♔ Muove il Bianco", + "♔ Brancas jogam", + "♔ Oqlar yuradi", + "♔ Ақтар жүреді", + ], + [ + "♚ Black to move", + "♚ ход чёрных", + "♚ Trait aux Noirs", + "♚ Schwarz am Zug", + "♚ Juegan negras", + "♚ Muove il Nero", + "♚ Pretas jogam", + "♚ Qoralar yuradi", + "♚ Қаралар жүреді", + ], [ "Mistakes: {n}", "Ошибок: {n}", @@ -15636,5313 +13741,6 @@ const ROWS: &[[&str; 9]] = &[ "Keyinga qoldirilgan o‘yin", "Кейінге қалдырылған ойын", ], - [ - "Opening errors are being searched — wait or stop it in the report", - "Идёт поиск ошибок в дебютах — дождитесь или остановите его в отчёте", - "La recherche d'erreurs d'ouverture est en cours — attendez ou arrêtez-la dans le rapport", - "Die Suche nach Eröffnungsfehlern läuft — warten Sie oder stoppen Sie sie im Bericht", - "Se están buscando errores de apertura — espere o deténgala en el informe", - "È in corso la ricerca degli errori di apertura — attendi o fermala nel rapporto", - "A busca de erros de abertura está em andamento — aguarde ou pare-a no relatório", - "Debyut xatolari qidirilmoqda — kuting yoki hisobotda to‘xtating", - "Дебют қателері ізделуде — күтіңіз немесе есепте тоқтатыңыз", - ], - [ - "⬅ Back to preparation", - "⬅ К подготовке", - "⬅ Retour à la préparation", - "⬅ Zurück zur Vorbereitung", - "⬅ Volver a la preparación", - "⬅ Torna alla preparazione", - "⬅ Voltar à preparação", - "⬅ Tayyorgarlikka qaytish", - "⬅ Дайындыққа оралу", - ], - [ - "♟ Prepare against an opponent…", - "♟ Подготовиться к сопернику…", - "♟ Se préparer contre un adversaire…", - "♟ Auf einen Gegner vorbereiten…", - "♟ Prepararse contra un rival…", - "♟ Prepararsi contro un avversario…", - "♟ Preparar-se contra um adversário…", - "♟ Raqibga tayyorlanish…", - "♟ Қарсыласқа дайындалу…", - ], - [ - "The player's openings by colour, with names, and the opening errors the engine finds (Ctrl+Shift+P)", - "Дебюты игрока по цветам, с названиями, и ошибки в дебюте, которые находит движок (Ctrl+Shift+P)", - "Les ouvertures du joueur par couleur, avec leurs noms, et les erreurs d'ouverture trouvées par le moteur (Ctrl+Maj+P)", - "Die Eröffnungen des Spielers nach Farbe, mit Namen, und die Eröffnungsfehler, die die Engine findet (Strg+Umschalt+P)", - "Las aperturas del jugador por color, con nombres, y los errores de apertura que encuentra el motor (Ctrl+Mayús+P)", - "Le aperture del giocatore per colore, con i nomi, e gli errori di apertura trovati dal motore (Ctrl+Maiusc+P)", - "As aberturas do jogador por cor, com nomes, e os erros de abertura que o motor encontra (Ctrl+Shift+P)", - "O‘yinchining ranglar bo‘yicha debyutlari, nomlari bilan, va dvijok topgan debyut xatolari (Ctrl+Shift+P)", - "Ойыншының түстер бойынша дебюттері, атауларымен, және қозғалтқыш тапқан дебют қателері (Ctrl+Shift+P)", - ], - [ - "♟ Prepare against {name}…", - "♟ Подготовиться к {name}…", - "♟ Se préparer contre {name}…", - "♟ Auf {name} vorbereiten…", - "♟ Prepararse contra {name}…", - "♟ Prepararsi contro {name}…", - "♟ Preparar-se contra {name}…", - "♟ {name} ga tayyorlanish…", - "♟ {name} қарсыласына дайындалу…", - ], - [ - "Stockfish installed — the search for opening errors started", - "Stockfish установлен — поиск ошибок в дебютах начат", - "Stockfish installé — la recherche d'erreurs d'ouverture a commencé", - "Stockfish installiert — die Suche nach Eröffnungsfehlern hat begonnen", - "Stockfish instalado — la búsqueda de errores de apertura ha comenzado", - "Stockfish installato — la ricerca degli errori di apertura è iniziata", - "Stockfish instalado — a busca de erros de abertura começou", - "Stockfish o‘rnatildi — debyut xatolarini qidirish boshlandi", - "Stockfish орнатылды — дебют қателерін іздеу басталды", - ], - [ - "The search for opening errors will start by itself when the download finishes.", - "Поиск ошибок в дебютах начнётся сам, когда загрузка закончится.", - "La recherche d'erreurs d'ouverture démarrera d'elle-même à la fin du téléchargement.", - "Die Suche nach Eröffnungsfehlern startet von selbst, wenn der Download fertig ist.", - "La búsqueda de errores de apertura empezará sola cuando termine la descarga.", - "La ricerca degli errori di apertura partirà da sola al termine del download.", - "A busca de erros de abertura começará sozinha quando o download terminar.", - "Yuklab olish tugagach debyut xatolarini qidirish o‘zi boshlanadi.", - "Жүктеу аяқталғанда дебют қателерін іздеу өзі басталады.", - ], - [ - "Both", - "Оба", - "Les deux", - "Beide", - "Ambos", - "Entrambi", - "Ambas", - "Ikkalasi", - "Екеуі", - ], - [ - "None", "Нет", "Aucun", "Keines", "Ninguno", "Nessuno", "Nenhum", "Yo‘q", "Жоқ", - ], - [ - "Preparing against an opponent", - "Подготовка к сопернику", - "Préparation contre un adversaire", - "Vorbereitung auf einen Gegner", - "Preparación contra un rival", - "Preparazione contro un avversario", - "Preparação contra um adversário", - "Raqibga tayyorgarlik", - "Қарсыласқа дайындық", - ], - [ - "Name or part of it", - "Имя или его часть", - "Nom ou une partie", - "Name oder ein Teil davon", - "Nombre o parte de él", - "Nome o parte di esso", - "Nome ou parte dele", - "Ism yoki uning qismi", - "Аты немесе оның бөлігі", - ], - [ - "Colour", "Цвет", "Couleur", "Farbe", "Color", "Colore", "Cor", "Rang", "Түс", - ], - [ - "Book", - "Книга", - "Livre", - "Buch", - "Libro", - "Libro", - "Livro", - "Kitob", - "Кітап", - ], - [ - "Open report", - "Открыть отчёт", - "Ouvrir le rapport", - "Bericht öffnen", - "Abrir informe", - "Apri rapporto", - "Abrir relatório", - "Hisobotni ochish", - "Есепті ашу", - ], - [ - "Tick a player", - "Отметьте игрока", - "Cochez un joueur", - "Wählen Sie einen Spieler", - "Marque un jugador", - "Spunta un giocatore", - "Marque um jogador", - "O‘yinchini belgilang", - "Ойыншыны белгілеңіз", - ], - [ - "Searching…", - "Ищу…", - "Recherche…", - "Suche…", - "Buscando…", - "Ricerca…", - "Procurando…", - "Qidirilmoqda…", - "Ізделуде…", - ], - [ - "Type a name: the players of the database are offered", - "Введите имя: будут предложены игроки базы", - "Tapez un nom : les joueurs de la base sont proposés", - "Geben Sie einen Namen ein: die Spieler der Datenbank werden angeboten", - "Escriba un nombre: se ofrecen los jugadores de la base", - "Digita un nome: vengono proposti i giocatori del database", - "Digite um nome: os jogadores da base são sugeridos", - "Ism kiriting: bazadagi o‘yinchilar taklif qilinadi", - "Атын теріңіз: базадағы ойыншылар ұсынылады", - ], - [ - "No such player in this database", - "В этой базе нет такого игрока", - "Aucun joueur de ce nom dans cette base", - "Kein solcher Spieler in dieser Datenbank", - "No hay tal jugador en esta base", - "Nessun giocatore così in questo database", - "Não há tal jogador nesta base", - "Bu bazada bunday o‘yinchi yo‘q", - "Бұл базада мұндай ойыншы жоқ", - ], - [ - "Similar names — most likely other people", - "Похожие имена — скорее всего, другие люди", - "Noms proches — probablement d'autres personnes", - "Ähnliche Namen — wahrscheinlich andere Personen", - "Nombres parecidos — probablemente otras personas", - "Nomi simili — probabilmente altre persone", - "Nomes parecidos — provavelmente outras pessoas", - "O‘xshash ismlar — ehtimol boshqa odamlar", - "Ұқсас есімдер — бәлкім, басқа адамдар", - ], - [ - "The games could not be read", - "Партии не удалось прочитать", - "Les parties n'ont pas pu être lues", - "Die Partien konnten nicht gelesen werden", - "No se pudieron leer las partidas", - "Impossibile leggere le partite", - "Não foi possível ler as partidas", - "Partiyalarni o‘qib bo‘lmadi", - "Партияларды оқу мүмкін болмады", - ], - [ - "Opening errors", - "Ошибки в дебютах", - "Erreurs d'ouverture", - "Eröffnungsfehler", - "Errores de apertura", - "Errori di apertura", - "Erros de abertura", - "Debyut xatolari", - "Дебют қателері", - ], - [ - "identical positions are counted once", - "одинаковые позиции считаются один раз", - "les positions identiques ne sont comptées qu'une fois", - "gleiche Stellungen werden einmal gezählt", - "las posiciones idénticas se cuentan una vez", - "le posizioni identiche si contano una volta", - "posições idênticas são contadas uma vez", - "bir xil pozitsiyalar bir marta hisoblanadi", - "бірдей позициялар бір рет саналады", - ], - [ - "Find errors", - "Найти ошибки", - "Chercher les erreurs", - "Fehler suchen", - "Buscar errores", - "Trova errori", - "Procurar erros", - "Xatolarni topish", - "Қателерді табу", - ], - [ - "Settings (Ctrl+,)", - "Настройки (Ctrl+,)", - "Paramètres (Ctrl+,)", - "Einstellungen (Strg+,)", - "Ajustes (Ctrl+,)", - "Impostazioni (Ctrl+,)", - "Configurações (Ctrl+,)", - "Sozlamalar (Ctrl+,)", - "Баптаулар (Ctrl+,)", - ], - [ - "How deep the tree and the engine look", - "Как глубоко смотрят дерево и движок", - "Profondeur de l'arbre et du moteur", - "Wie tief Baum und Engine schauen", - "Hasta dónde miran el árbol y el motor", - "Quanto in profondità guardano l'albero e il motore", - "Até onde a árvore e o motor olham", - "Daraxt va dvijok qanchalik chuqur qaraydi", - "Ағаш пен қозғалтқыш қаншалықты терең қарайды", - ], - [ - "The board of the chosen position", - "Доска выбранной позиции", - "L'échiquier de la position choisie", - "Das Brett der gewählten Stellung", - "El tablero de la posición elegida", - "La scacchiera della posizione scelta", - "O tabuleiro da posição escolhida", - "Tanlangan pozitsiya taxtasi", - "Таңдалған позиция тақтасы", - ], - [ - "Errors found", - "Ошибки найдены", - "Erreurs trouvées", - "Fehler gefunden", - "Errores encontrados", - "Errori trovati", - "Erros encontrados", - "Xatolar topildi", - "Қателер табылды", - ], - [ - "The engine finds the opening errors in his games (Shift+A)", - "Движок находит ошибки в дебютах его партий (Shift+A)", - "Le moteur trouve les erreurs d'ouverture dans ses parties (Maj+A)", - "Die Engine findet die Eröffnungsfehler in seinen Partien (Umschalt+A)", - "El motor encuentra los errores de apertura en sus partidas (Mayús+A)", - "Il motore trova gli errori di apertura nelle sue partite (Maiusc+A)", - "O motor encontra os erros de abertura nas partidas dele (Shift+A)", - "Dvijok uning partiyalaridagi debyut xatolarini topadi (Shift+A)", - "Қозғалтқыш оның партияларындағы дебют қателерін табады (Shift+A)", - ], - [ - "Options…", - "Параметры…", - "Options…", - "Optionen…", - "Opciones…", - "Opzioni…", - "Opções…", - "Parametrlar…", - "Параметрлер…", - ], - [ - "As White", - "Белыми", - "Avec les Blancs", - "Mit Weiß", - "Con blancas", - "Con il Bianco", - "De brancas", - "Oq bilan", - "Ақпен", - ], - [ - "As Black", - "Чёрными", - "Avec les Noirs", - "Mit Schwarz", - "Con negras", - "Con il Nero", - "De pretas", - "Qora bilan", - "Қарамен", - ], - [ - "No engine yet. Stockfish finds the opening errors in his games; add it to start the search.", - "Движка пока нет. Stockfish ищет ошибки в его дебютах; добавьте его, чтобы начать поиск.", - "Pas encore de moteur. Stockfish trouve les erreurs d’ouverture de ses parties ; ajoutez-le pour lancer la recherche.", - "Noch keine Engine. Stockfish findet die Eröffnungsfehler in seinen Partien; fügen Sie sie hinzu, um die Suche zu starten.", - "Aún no hay motor. Stockfish encuentra los errores de apertura de sus partidas; añádelo para empezar la búsqueda.", - "Ancora nessun motore. Stockfish trova gli errori di apertura delle sue partite; aggiungilo per iniziare la ricerca.", - "Ainda não há motor. O Stockfish encontra os erros de abertura das suas partidas; adicione-o para começar a procura.", - "Hali dvijok yo‘q. Stockfish uning partiyalaridagi debyut xatolarini topadi; qidiruvni boshlash uchun uni qo‘shing.", - "Әзірге движок жоқ. Stockfish оның партияларындағы дебют қателерін табады; іздеуді бастау үшін оны қосыңыз.", - ], - [ - "Choose a move in the tree, an opening or an error: its position is shown here", - "Выберите ход в дереве, дебют или ошибку: здесь будет его позиция", - "Choisissez un coup dans l'arbre, une ouverture ou une erreur : sa position s'affiche ici", - "Wählen Sie einen Zug im Baum, eine Eröffnung oder einen Fehler: seine Stellung erscheint hier", - "Elija una jugada del árbol, una apertura o un error: su posición se muestra aquí", - "Scegli una mossa nell'albero, un'apertura o un errore: la sua posizione appare qui", - "Escolha um lance na árvore, uma abertura ou um erro: a posição aparece aqui", - "Daraxtdan yurish, debyut yoki xatoni tanlang: uning pozitsiyasi shu yerda ko‘rinadi", - "Ағаштан жүріс, дебют немесе қате таңдаңыз: оның позициясы осында көрінеді", - ], - [ - "Open as a game", - "Открыть как партию", - "Ouvrir comme partie", - "Als Partie öffnen", - "Abrir como partida", - "Apri come partita", - "Abrir como partida", - "Partiya sifatida ochish", - "Партия ретінде ашу", - ], - [ - "The line as a new game, to add moves and comments", - "Линия как новая партия — чтобы дописать ходы и комментарии", - "La ligne comme nouvelle partie, pour ajouter des coups et des commentaires", - "Die Linie als neue Partie, um Züge und Kommentare hinzuzufügen", - "La línea como partida nueva, para añadir jugadas y comentarios", - "La linea come nuova partita, per aggiungere mosse e commenti", - "A linha como nova partida, para acrescentar lances e comentários", - "Chiziq yangi partiya sifatida — yurishlar va izohlar qo‘shish uchun", - "Желі жаңа партия ретінде — жүрістер мен түсініктемелер қосу үшін", - ], - [ - "Repertoire", - "Репертуар", - "Répertoire", - "Repertoire", - "Repertorio", - "Repertorio", - "Repertório", - "Repertuar", - "Репертуар", - ], - [ - "Openings", - "Дебюты", - "Ouvertures", - "Eröffnungen", - "Aperturas", - "Aperture", - "Aberturas", - "Debyutlar", - "Дебюттер", - ], - [ - "Errors", - "Ошибки", - "Erreurs", - "Fehler", - "Errores", - "Errori", - "Erros", - "Xatolar", - "Қателер", - ], - [ - "Collapse", - "Свернуть", - "Replier", - "Einklappen", - "Contraer", - "Comprimi", - "Recolher", - "Yig‘ish", - "Жию", - ], - [ - "Expand all", - "Раскрыть всё", - "Tout déplier", - "Alles ausklappen", - "Expandir todo", - "Espandi tutto", - "Expandir tudo", - "Hammasini yoyish", - "Барлығын жаю", - ], - [ - "Moves with fewer games fold into «other moves»", - "Ходы с меньшим числом партий сворачиваются в «другие ходы»", - "Les coups avec moins de parties sont regroupés dans « autres coups »", - "Züge mit weniger Partien werden zu „andere Züge“ zusammengefasst", - "Las jugadas con menos partidas se agrupan en «otras jugadas»", - "Le mosse con meno partite si raggruppano in «altre mosse»", - "Lances com menos partidas são agrupados em «outros lances»", - "Partiyasi kamroq yurishlar «boshqa yurishlar»ga yig‘iladi", - "Партиясы азырақ жүрістер «басқа жүрістерге» жиналады", - ], - [ - "His moves plain, the opponents' weak; ⇄ — the position is reached by another move order too", - "Его ходы — обычным, ходы соперников — слабым; ⇄ — к позиции приходят и другим порядком ходов", - "Ses coups en clair, ceux des adversaires en pâle ; ⇄ — la position est aussi atteinte par un autre ordre de coups", - "Seine Züge normal, die der Gegner blass; ⇄ — die Stellung wird auch über eine andere Zugfolge erreicht", - "Sus jugadas en normal, las de los rivales en tenue; ⇄ — la posición también se alcanza por otro orden de jugadas", - "Le sue mosse in chiaro, quelle degli avversari attenuate; ⇄ — la posizione si raggiunge anche con un altro ordine di mosse", - "Os lances dele em normal, os dos adversários esmaecidos; ⇄ — a posição também é alcançada por outra ordem de lances", - "Uning yurishlari oddiy, raqiblarniki xira; ⇄ — pozitsiyaga boshqa tartibda ham kelinadi", - "Оның жүрістері әдеттегі, қарсыластарынікі күңгірт; ⇄ — позицияға басқа жүріс ретімен де келеді", - ], - [ - "Share of the games of the move above", - "Доля от партий хода выше", - "Part des parties du coup au-dessus", - "Anteil an den Partien des Zuges darüber", - "Parte de las partidas de la jugada superior", - "Quota delle partite della mossa sopra", - "Parte das partidas do lance acima", - "Yuqoridagi yurish partiyalaridan ulush", - "Жоғарыдағы жүріс партияларынан үлес", - ], - [ - "Score", - "Счёт", - "Score", - "Ergebnis", - "Puntuación", - "Punteggio", - "Pontuação", - "Hisob", - "Есеп", - ], - [ - "The opponent's points in these games", - "Очки соперника в этих партиях", - "Les points de l'adversaire dans ces parties", - "Die Punkte des Gegners in diesen Partien", - "Los puntos del rival en estas partidas", - "I punti dell'avversario in queste partite", - "Os pontos do adversário nestas partidas", - "Raqibning bu partiyalardagi ochkolari", - "Қарсыластың осы партиялардағы ұпайлары", - ], - [ - "Last", - "Последняя", - "Dernière", - "Letzte", - "Última", - "Ultima", - "Última", - "Oxirgi", - "Соңғы", - ], - [ - "Few games: percentages are unreliable", - "Мало партий — проценты ненадёжны", - "Peu de parties : les pourcentages ne sont pas fiables", - "Wenige Partien: die Prozente sind unzuverlässig", - "Pocas partidas: los porcentajes no son fiables", - "Poche partite: le percentuali non sono affidabili", - "Poucas partidas: as porcentagens não são confiáveis", - "Partiyalar kam: foizlar ishonchsiz", - "Партиялар аз: пайыздар сенімсіз", - ], - [ - "First moves", - "Первые ходы", - "Premiers coups", - "Erste Züge", - "Primeras jugadas", - "Prime mosse", - "Primeiros lances", - "Birinchi yurishlar", - "Алғашқы жүрістер", - ], - [ - "no name", - "без названия", - "sans nom", - "ohne Namen", - "sin nombre", - "senza nome", - "sem nome", - "nomsiz", - "атаусыз", - ], - [ - "no deeper name", - "без названия глубже", - "sans nom plus loin", - "kein tieferer Name", - "sin nombre más adelante", - "nessun nome più avanti", - "sem nome mais adiante", - "chuqurroq nom yo‘q", - "тереңірек атау жоқ", - ], - [ - "in both colours", - "обоими цветами", - "avec les deux couleurs", - "mit beiden Farben", - "con ambos colores", - "con entrambi i colori", - "com ambas as cores", - "ikkala rang bilan", - "екі түспен де", - ], - [ - "▶ Find opening errors", - "▶ Найти ошибки в дебютах", - "▶ Chercher les erreurs d'ouverture", - "▶ Eröffnungsfehler suchen", - "▶ Buscar errores de apertura", - "▶ Trova gli errori di apertura", - "▶ Procurar erros de abertura", - "▶ Debyut xatolarini topish", - "▶ Дебют қателерін табу", - ], - [ - "Repeated errors — the same position, the same move", - "Повторяющиеся ошибки — одна и та же позиция, тот же ход", - "Erreurs répétées — même position, même coup", - "Wiederholte Fehler — dieselbe Stellung, derselbe Zug", - "Errores repetidos — la misma posición, la misma jugada", - "Errori ripetuti — la stessa posizione, la stessa mossa", - "Erros repetidos — a mesma posição, o mesmo lance", - "Takrorlanuvchi xatolar — o‘sha pozitsiya, o‘sha yurish", - "Қайталанатын қателер — сол позиция, сол жүріс", - ], - [ - "Played", - "Сыграл", - "Joué", - "Gespielt", - "Jugó", - "Giocata", - "Jogou", - "O‘ynadi", - "Жүрді", - ], - [ - "Better", - "Лучше", - "Mieux", - "Besser", - "Mejor", - "Meglio", - "Melhor", - "Yaxshiroq", - "Жақсырақ", - ], - [ - "start", - "начало", - "début", - "Anfang", - "inicio", - "inizio", - "início", - "boshlanish", - "басы", - ], - [ - "By opening", - "По дебютам", - "Par ouverture", - "Nach Eröffnung", - "Por apertura", - "Per apertura", - "Por abertura", - "Debyutlar bo‘yicha", - "Дебюттер бойынша", - ], - [ - "All games", - "Все партии", - "Toutes les parties", - "Alle Partien", - "Todas las partidas", - "Tutte le partite", - "Todas as partidas", - "Barcha partiyalar", - "Барлық партиялар", - ], - [ - "His marked moves in the opening of this game", - "Его отмеченные ходы в дебюте этой партии", - "Ses coups marqués dans l'ouverture de cette partie", - "Seine markierten Züge in der Eröffnung dieser Partie", - "Sus jugadas marcadas en la apertura de esta partida", - "Le sue mosse segnate nell'apertura di questa partita", - "Os lances marcados dele na abertura desta partida", - "Bu partiya debyutidagi uning belgilangan yurishlari", - "Осы партия дебютіндегі оның белгіленген жүрістері", - ], - [ - "Selected: {names} · {n}", - "Отмечено: {names} · {n}", - "Sélection : {names} · {n}", - "Gewählt: {names} · {n}", - "Marcados: {names} · {n}", - "Selezionati: {names} · {n}", - "Marcados: {names} · {n}", - "Belgilandi: {names} · {n}", - "Белгіленді: {names} · {n}", - ], - [ - "White — {n}", - "Белые — {n}", - "Blancs — {n}", - "Weiß — {n}", - "Blancas — {n}", - "Bianco — {n}", - "Brancas — {n}", - "Oq — {n}", - "Ақ — {n}", - ], - [ - "Black — {n}", - "Чёрные — {n}", - "Noirs — {n}", - "Schwarz — {n}", - "Negras — {n}", - "Nero — {n}", - "Pretas — {n}", - "Qora — {n}", - "Қара — {n}", - ], - [ - "Preparing against {name}", - "Подготовка к сопернику: {name}", - "Préparation contre {name}", - "Vorbereitung auf {name}", - "Preparación contra {name}", - "Preparazione contro {name}", - "Preparação contra {name}", - "Tayyorgarlik: {name}", - "Дайындық: {name}", - ], - [ - "The engine evaluates the first {n} moves of every game of the opponent. The games are not changed.", - "Движок оценит первые {n} ходов каждой партии соперника. Партии не меняются.", - "Le moteur évalue les {n} premiers coups de chaque partie de l'adversaire. Les parties ne sont pas modifiées.", - "Die Engine bewertet die ersten {n} Züge jeder Partie des Gegners. Die Partien werden nicht verändert.", - "El motor evalúa las primeras {n} jugadas de cada partida del rival. Las partidas no se modifican.", - "Il motore valuta le prime {n} mosse di ogni partita dell'avversario. Le partite non vengono modificate.", - "O motor avalia os primeiros {n} lances de cada partida do adversário. As partidas não são alteradas.", - "Dvijok raqibning har bir partiyasidagi dastlabki {n} yurishni baholaydi. Partiyalar o‘zgarmaydi.", - "Қозғалтқыш қарсыластың әр партиясының алғашқы {n} жүрісін бағалайды. Партиялар өзгермейді.", - ], - [ - "identical positions are counted once; {n} already evaluated earlier", - "одинаковые позиции считаются один раз; {n} уже оценены раньше", - "les positions identiques ne sont comptées qu'une fois ; {n} déjà évaluées", - "gleiche Stellungen werden einmal gezählt; {n} schon früher bewertet", - "las posiciones idénticas se cuentan una vez; {n} ya evaluadas antes", - "le posizioni identiche si contano una volta; {n} già valutate prima", - "posições idênticas são contadas uma vez; {n} já avaliadas antes", - "bir xil pozitsiyalar bir marta hisoblanadi; {n} tasi avval baholangan", - "бірдей позициялар бір рет саналады; {n} бұрын бағаланған", - ], - [ - "+{n} spelling", - "+{n} написание", - "+{n} orthographe", - "+{n} Schreibweise", - "+{n} grafía", - "+{n} grafia", - "+{n} grafia", - "+{n} yozilish", - "+{n} жазылу", - ], - [ - "not counted: from a set position — {n}", - "не учтены: с заданной позиции — {n}", - "non comptées : depuis une position donnée — {n}", - "nicht gezählt: aus einer Ausgangsstellung — {n}", - "no contadas: desde una posición dada — {n}", - "non contate: da una posizione data — {n}", - "não contadas: de uma posição dada — {n}", - "hisobga olinmadi: berilgan pozitsiyadan — {n}", - "есептелмеді: берілген позициядан — {n}", - ], - [ - "Opening: {n} moves", - "Дебют: {n} ходов", - "Ouverture : {n} coups", - "Eröffnung: {n} Züge", - "Apertura: {n} jugadas", - "Apertura: {n} mosse", - "Abertura: {n} lances", - "Debyut: {n} yurish", - "Дебют: {n} жүріс", - ], - [ - "Finding errors: {done} of {total} positions · ≈ {time}", - "Ищу ошибки: {done} из {total} позиций · ≈ {time}", - "Recherche d'erreurs : {done} sur {total} positions · ≈ {time}", - "Fehlersuche: {done} von {total} Stellungen · ≈ {time}", - "Buscando errores: {done} de {total} posiciones · ≈ {time}", - "Ricerca errori: {done} di {total} posizioni · ≈ {time}", - "Procurando erros: {done} de {total} posições · ≈ {time}", - "Xatolar qidirilmoqda: {total} dan {done} pozitsiya · ≈ {time}", - "Қателер ізделуде: {total} ішінен {done} позиция · ≈ {time}", - ], - [ - "▶ Errors ≈ {time}", - "▶ Ошибки ≈ {time}", - "▶ Erreurs ≈ {time}", - "▶ Fehler ≈ {time}", - "▶ Errores ≈ {time}", - "▶ Errori ≈ {time}", - "▶ Erros ≈ {time}", - "▶ Xatolar ≈ {time}", - "▶ Қателер ≈ {time}", - ], - [ - "▶ Find opening errors ≈ {time}", - "▶ Найти ошибки в дебютах ≈ {time}", - "▶ Chercher les erreurs d'ouverture ≈ {time}", - "▶ Eröffnungsfehler suchen ≈ {time}", - "▶ Buscar errores de apertura ≈ {time}", - "▶ Trova gli errori di apertura ≈ {time}", - "▶ Procurar erros de abertura ≈ {time}", - "▶ Debyut xatolarini topish ≈ {time}", - "▶ Дебют қателерін табу ≈ {time}", - ], - [ - "Errors found · {engine} · {n} positions", - "Ошибки найдены · {engine} · {n} позиций", - "Erreurs trouvées · {engine} · {n} positions", - "Fehler gefunden · {engine} · {n} Stellungen", - "Errores encontrados · {engine} · {n} posiciones", - "Errori trovati · {engine} · {n} posizioni", - "Erros encontrados · {engine} · {n} posições", - "Xatolar topildi · {engine} · {n} pozitsiya", - "Қателер табылды · {engine} · {n} позиция", - ], - [ - "opponents ≈ {elo}", - "соперники ≈ {elo}", - "adversaires ≈ {elo}", - "Gegner ≈ {elo}", - "rivales ≈ {elo}", - "avversari ≈ {elo}", - "adversários ≈ {elo}", - "raqiblar ≈ {elo}", - "қарсыластар ≈ {elo}", - ], - [ - "last {date}", - "последняя {date}", - "dernière {date}", - "letzte {date}", - "última {date}", - "ultima {date}", - "última {date}", - "oxirgisi {date}", - "соңғысы {date}", - ], - [ - "Few games ({n}): percentages and scores are unreliable", - "Партий мало ({n}) — проценты и счёт ненадёжны", - "Peu de parties ({n}) : pourcentages et scores ne sont pas fiables", - "Wenige Partien ({n}): Prozente und Ergebnisse sind unzuverlässig", - "Pocas partidas ({n}): porcentajes y puntuaciones no son fiables", - "Poche partite ({n}): percentuali e punteggi non sono affidabili", - "Poucas partidas ({n}): porcentagens e pontuações não são confiáveis", - "Partiyalar kam ({n}): foizlar va hisob ishonchsiz", - "Партиялар аз ({n}): пайыздар мен есеп сенімсіз", - ], - [ - "Collecting games… {p} %", - "Собираю партии… {p} %", - "Collecte des parties… {p} %", - "Partien werden gesammelt… {p} %", - "Reuniendo partidas… {p} %", - "Raccolta delle partite… {p} %", - "Reunindo partidas… {p} %", - "Partiyalar yig‘ilmoqda… {p} %", - "Партиялар жиналуда… {p} %", - ], - [ - "Branches from {n} games", - "Ветви от {n} партий", - "Branches dès {n} parties", - "Zweige ab {n} Partien", - "Ramas desde {n} partidas", - "Rami da {n} partite", - "Ramos a partir de {n} partidas", - "{n} partiyadan shoxlar", - "{n} партиядан тармақтар", - ], - [ - "other moves ({n})", - "другие ходы ({n})", - "autres coups ({n})", - "andere Züge ({n})", - "otras jugadas ({n})", - "altre mosse ({n})", - "outros lances ({n})", - "boshqa yurishlar ({n})", - "басқа жүрістер ({n})", - ], - [ - "Reached by another move order too: {orders}", - "К позиции приходили и другим порядком: {orders}", - "Aussi atteinte par un autre ordre de coups : {orders}", - "Auch über eine andere Zugfolge erreicht: {orders}", - "También alcanzada por otro orden de jugadas: {orders}", - "Raggiunta anche con un altro ordine di mosse: {orders}", - "Também alcançada por outra ordem de lances: {orders}", - "Boshqa tartibda ham kelingan: {orders}", - "Басқа жүріс ретімен де келген: {orders}", - ], - [ - "No games as {colour}. As {other} — {n}", - "{colour} партий нет. {other} — {n}", - "Aucune partie avec les {colour}. Avec les {other} — {n}", - "Keine Partien mit {colour}. Mit {other} — {n}", - "No hay partidas con {colour}. Con {other} — {n}", - "Nessuna partita con il {colour}. Con il {other} — {n}", - "Nenhuma partida de {colour}. De {other} — {n}", - "{colour} bilan partiyalar yo‘q. {other} bilan — {n}", - "{colour} партиялар жоқ. {other} — {n}", - ], - [ - "Show {other}", - "Показать {other}", - "Afficher {other}", - "{other} zeigen", - "Mostrar {other}", - "Mostra {other}", - "Mostrar {other}", - "{other} ko‘rsatish", - "{other} көрсету", - ], - [ - "The engine has not searched for errors yet. It will check the first {n} moves of {games} games {colour} — {positions} positions, about {time}.", - "Движок ещё не искал ошибки. Он проверит первые {n} ходов {games} партий {colour} — {positions} позиций, около {time}.", - "Le moteur n'a pas encore cherché d'erreurs. Il vérifiera les {n} premiers coups de {games} parties {colour} — {positions} positions, environ {time}.", - "Die Engine hat noch nicht nach Fehlern gesucht. Sie prüft die ersten {n} Züge von {games} Partien {colour} — {positions} Stellungen, etwa {time}.", - "El motor aún no ha buscado errores. Comprobará las primeras {n} jugadas de {games} partidas {colour} — {positions} posiciones, unos {time}.", - "Il motore non ha ancora cercato errori. Controllerà le prime {n} mosse di {games} partite {colour} — {positions} posizioni, circa {time}.", - "O motor ainda não procurou erros. Ele verificará os primeiros {n} lances de {games} partidas {colour} — {positions} posições, cerca de {time}.", - "Dvijok hali xatolarni qidirmadi. U {colour} {games} partiyaning dastlabki {n} yurishini tekshiradi — {positions} pozitsiya, taxminan {time}.", - "Қозғалтқыш әлі қателерді іздеген жоқ. Ол {colour} {games} партияның алғашқы {n} жүрісін тексереді — {positions} позиция, шамамен {time}.", - ], - [ - "Checked {done} of {total} positions", - "Проверено {done} из {total} позиций", - "{done} positions vérifiées sur {total}", - "{done} von {total} Stellungen geprüft", - "Comprobadas {done} de {total} posiciones", - "Verificate {done} di {total} posizioni", - "Verificadas {done} de {total} posições", - "{total} dan {done} pozitsiya tekshirildi", - "{total} ішінен {done} позиция тексерілді", - ], - [ - "No errors in the first {n} moves ({i} inaccuracies).", - "В первых {n} ходах ошибок не нашлось (неточностей {i}).", - "Pas d'erreur dans les {n} premiers coups ({i} imprécisions).", - "Keine Fehler in den ersten {n} Zügen ({i} Ungenauigkeiten).", - "Sin errores en las primeras {n} jugadas ({i} imprecisiones).", - "Nessun errore nelle prime {n} mosse ({i} imprecisioni).", - "Sem erros nos primeiros {n} lances ({i} imprecisões).", - "Dastlabki {n} yurishda xato topilmadi ({i} noaniqlik).", - "Алғашқы {n} жүрісте қате табылмады ({i} дәлсіздік).", - ], - [ - "Deeper: {n} moves", - "Глубже: {n} ходов", - "Plus loin : {n} coups", - "Tiefer: {n} Züge", - "Más profundo: {n} jugadas", - "Più a fondo: {n} mosse", - "Mais fundo: {n} lances", - "Chuqurroq: {n} yurish", - "Тереңірек: {n} жүріс", - ], - [ - "better {best}", - "лучше {best}", - "mieux {best}", - "besser {best}", - "mejor {best}", - "meglio {best}", - "melhor {best}", - "yaxshisi {best}", - "жақсысы {best}", - ], - [ - "Games · {n}", - "Партии · {n}", - "Parties · {n}", - "Partien · {n}", - "Partidas · {n}", - "Partite · {n}", - "Partidas · {n}", - "Partiyalar · {n}", - "Партиялар · {n}", - ], - [ - "Games · after {move} · {n}", - "Партии · после {move} · {n}", - "Parties · après {move} · {n}", - "Partien · nach {move} · {n}", - "Partidas · tras {move} · {n}", - "Partite · dopo {move} · {n}", - "Partidas · após {move} · {n}", - "Partiyalar · {move} dan keyin · {n}", - "Партиялар · {move} кейін · {n}", - ], - [ - "Games · {opening} · {n}", - "Партии · {opening} · {n}", - "Parties · {opening} · {n}", - "Partien · {opening} · {n}", - "Partidas · {opening} · {n}", - "Partite · {opening} · {n}", - "Partidas · {opening} · {n}", - "Partiyalar · {opening} · {n}", - "Партиялар · {opening} · {n}", - ], - [ - "Games · {move} · {n}", - "Партии · {move} · {n}", - "Parties · {move} · {n}", - "Partien · {move} · {n}", - "Partidas · {move} · {n}", - "Partite · {move} · {n}", - "Partidas · {move} · {n}", - "Partiyalar · {move} · {n}", - "Партиялар · {move} · {n}", - ], - [ - "{played} — better {best} · {before} → {after}", - "{played} — лучше {best} · {before} → {after}", - "{played} — mieux {best} · {before} → {after}", - "{played} — besser {best} · {before} → {after}", - "{played} — mejor {best} · {before} → {after}", - "{played} — meglio {best} · {before} → {after}", - "{played} — melhor {best} · {before} → {after}", - "{played} — yaxshisi {best} · {before} → {after}", - "{played} — жақсысы {best} · {before} → {after}", - ], - [ - "Opening errors are being searched. Quit and stop?", - "Идёт поиск ошибок в дебютах. Выйти и остановить?", - "La recherche d'erreurs d'ouverture est en cours. Quitter et l'arrêter ?", - "Die Suche nach Eröffnungsfehlern läuft. Beenden und stoppen?", - "Se están buscando errores de apertura. ¿Salir y detenerla?", - "È in corso la ricerca degli errori di apertura. Uscire e fermarla?", - "A busca de erros de abertura está em andamento. Sair e parar?", - "Debyut xatolari qidirilmoqda. Chiqib, to‘xtatilsinmi?", - "Дебют қателері ізделуде. Шығып, тоқтату керек пе?", - ], - [ - "What was found is kept.", - "Найденное сохранится.", - "Ce qui a été trouvé est conservé.", - "Was gefunden wurde, bleibt erhalten.", - "Lo encontrado se conserva.", - "Quanto trovato viene conservato.", - "O que foi encontrado é mantido.", - "Topilganlar saqlanadi.", - "Табылғаны сақталады.", - ], - [ - "Quit", - "Выйти", - "Quitter", - "Beenden", - "Salir", - "Esci", - "Sair", - "Chiqish", - "Шығу", - ], - [ - "Back to the game list", - "Назад к списку партий", - "Retour à la liste des parties", - "Zurück zur Partienliste", - "Volver a la lista de partidas", - "Torna all'elenco delle partite", - "Voltar à lista de partidas", - "Partiyalar ro‘yxatiga qaytish", - "Партиялар тізіміне оралу", - ], - [ - "The preparation this game was opened from, as you left it (Esc, Ctrl+W)", - "Подготовка, из которой открыта партия, — такой, как вы её оставили (Esc, Ctrl+W)", - "La préparation d'où cette partie a été ouverte, telle que vous l'avez laissée (Échap, Ctrl+W)", - "Die Vorbereitung, aus der diese Partie geöffnet wurde, so wie Sie sie verlassen haben (Esc, Strg+W)", - "La preparación desde la que se abrió esta partida, tal como la dejó (Esc, Ctrl+W)", - "La preparazione da cui è stata aperta questa partita, come l'hai lasciata (Esc, Ctrl+W)", - "A preparação de onde esta partida foi aberta, como você a deixou (Esc, Ctrl+W)", - "Bu partiya ochilgan tayyorgarlik — siz qoldirgan holatda (Esc, Ctrl+W)", - "Осы партия ашылған дайындық — сіз қалдырған күйінде (Esc, Ctrl+W)", - ], - [ - "no errors", - "ошибок нет", - "aucune erreur", - "keine Fehler", - "sin errores", - "nessun errore", - "sem erros", - "xatolar yo‘q", - "қателер жоқ", - ], - [ - "Share of the colour's games; a variation's — of its family's", - "Доля от партий цветом; у варианта — от семейства", - "Part des parties de cette couleur ; pour une variante — de sa famille", - "Anteil an den Partien dieser Farbe; bei einer Variante — an ihrer Familie", - "Parte de las partidas de ese color; de una variante — de su familia", - "Quota delle partite di quel colore; di una variante — della sua famiglia", - "Parte das partidas dessa cor; de uma variante — da sua família", - "Shu rangdagi partiyalardan ulush; variantda — oilasidan", - "Осы түстегі партиялардан үлес; нұсқада — тобынан", - ], - [ - "The counts are of the checked positions", - "Числа — по проверенным позициям", - "Les nombres portent sur les positions vérifiées", - "Die Zahlen gelten für die geprüften Stellungen", - "Las cifras son de las posiciones comprobadas", - "I numeri riguardano le posizioni verificate", - "Os números são das posições verificadas", - "Sonlar tekshirilgan pozitsiyalar bo‘yicha", - "Сандар тексерілген позициялар бойынша", - ], - [ - "Show the inaccuracies (?!) with the mistakes and blunders", - "Показывать неточности (?!) вместе с ошибками и зевками", - "Afficher les imprécisions (?!) avec les erreurs et les gaffes", - "Ungenauigkeiten (?!) mit Fehlern und groben Fehlern zeigen", - "Mostrar las imprecisiones (?!) con los errores y errores graves", - "Mostra le imprecisioni (?!) con errori e svarioni", - "Mostrar as imprecisões (?!) com os erros e erros graves", - "Noaniqliklarni (?!) xato va qo‘pol xatolar bilan ko‘rsatish", - "Дәлсіздіктерді (?!) қателер мен өрескел қателермен бірге көрсету", - ], - [ - "White wins {w} % · draws {d} % · Black wins {b} %", - "Победы белых {w} % · ничьи {d} % · победы чёрных {b} %", - "Victoires des Blancs {w} % · nulles {d} % · victoires des Noirs {b} %", - "Weißsiege {w} % · Remis {d} % · Schwarzsiege {b} %", - "Victorias blancas {w} % · tablas {d} % · victorias negras {b} %", - "Vittorie del Bianco {w} % · patte {d} % · vittorie del Nero {b} %", - "Vitórias das brancas {w} % · empates {d} % · vitórias das pretas {b} %", - "Oq g‘alabalari {w} % · durang {d} % · qora g‘alabalari {b} %", - "Ақ жеңістері {w} % · тең {d} % · қара жеңістері {b} %", - ], - [ - "{n} moves", - "{n} ходов", - "{n} coups", - "{n} Züge", - "{n} jugadas", - "{n} mosse", - "{n} lances", - "{n} yurish", - "{n} жүріс", - ], - [ - "{n} m.", "{n} х.", "{n} c.", "{n} Z.", "{n} j.", "{n} m.", "{n} l.", "{n} yur.", "{n} ж.", - ], - [ - "Continue ≈ {time}", - "Продолжить ≈ {time}", - "Continuer ≈ {time}", - "Fortsetzen ≈ {time}", - "Continuar ≈ {time}", - "Continua ≈ {time}", - "Continuar ≈ {time}", - "Davom ettirish ≈ {time}", - "Жалғастыру ≈ {time}", - ], - [ - "Errors found · {n} positions", - "Ошибки найдены · {n} позиций", - "Erreurs trouvées · {n} positions", - "Fehler gefunden · {n} Stellungen", - "Errores encontrados · {n} posiciones", - "Errori trovati · {n} posizioni", - "Erros encontrados · {n} posições", - "Xatolar topildi · {n} pozitsiya", - "Қателер табылды · {n} позиция", - ], - [ - "in {p} % of games", - "в {p} % партий", - "dans {p} % des parties", - "in {p} % der Partien", - "en el {p} % de las partidas", - "nel {p} % delle partite", - "em {p} % das partidas", - "partiyalarning {p} % ida", - "партиялардың {p} % інде", - ], - [ - "others ({n})", - "другие ({n})", - "autres ({n})", - "andere ({n})", - "otras ({n})", - "altre ({n})", - "outros ({n})", - "boshqalar ({n})", - "басқалары ({n})", - ], - [ - "{judgement}: better {best} ({before} → {after}) · in {n} games", - "{judgement}: лучше {best} (оценка {before} → {after}) · в {n} партиях", - "{judgement} : mieux {best} ({before} → {after}) · dans {n} parties", - "{judgement}: besser {best} ({before} → {after}) · in {n} Partien", - "{judgement}: mejor {best} ({before} → {after}) · en {n} partidas", - "{judgement}: meglio {best} ({before} → {after}) · in {n} partite", - "{judgement}: melhor {best} ({before} → {after}) · em {n} partidas", - "{judgement}: yaxshisi {best} ({before} → {after}) · {n} partiyada", - "{judgement}: жақсысы {best} ({before} → {after}) · {n} партияда", - ], - [ - "Checking whether your engine can run the analysis…", - "Проверяю, подойдёт ли ваш движок для разбора…", - "Vérification : votre moteur peut-il faire l’analyse…", - "Es wird geprüft, ob Ihre Engine die Analyse machen kann…", - "Comprobando si su motor puede hacer el análisis…", - "Verifica se il tuo motore può fare l’analisi…", - "Verificando se o seu motor pode fazer a análise…", - "Dvigatelingiz tahlilga yaraydimi, tekshirilmoqda…", - "Қозғалтқышыңыз талдауға жарай ма, тексерілуде…", - ], - [ - "Your Stockfish 19 calculates differently from ChessPenguin's build (another build or network).", - "Ваш Stockfish 19 считает иначе, чем сборка ChessPenguin (другая сборка или сеть).", - "Votre Stockfish 19 calcule autrement que la version de ChessPenguin (autre compilation ou autre réseau).", - "Ihr Stockfish 19 rechnet anders als der Build von ChessPenguin (anderer Build oder anderes Netz).", - "Su Stockfish 19 calcula de otra manera que la compilación de ChessPenguin (otra compilación u otra red).", - "Il tuo Stockfish 19 calcola diversamente dalla build di ChessPenguin (un’altra build o un’altra rete).", - "Seu Stockfish 19 calcula de outro jeito que a versão do ChessPenguin (outra compilação ou outra rede).", - "Sizning Stockfish 19 ChessPenguin yig‘masidan boshqacha hisoblaydi (boshqa yig‘ma yoki tarmoq).", - "Сіздің Stockfish 19 ChessPenguin жинағынан басқаша есептейді (басқа жинақ немесе желі).", - ], - [ - "{engine} did not finish the check in time; it will be checked again next time.", - "{engine} не успел ответить на проверку — проверю снова в следующий раз.", - "{engine} n’a pas répondu à temps à la vérification ; il sera vérifié à nouveau la prochaine fois.", - "{engine} hat die Prüfung nicht rechtzeitig beantwortet; beim nächsten Mal wird erneut geprüft.", - "{engine} no respondió a tiempo a la comprobación; se comprobará de nuevo la próxima vez.", - "{engine} non ha risposto in tempo alla verifica; sarà verificato di nuovo la prossima volta.", - "{engine} não respondeu a tempo à verificação; será verificado de novo na próxima vez.", - "{engine} tekshiruvga o‘z vaqtida javob bermadi — keyingi safar yana tekshiriladi.", - "{engine} тексеруге уақытында жауап бермеді — келесі жолы қайта тексеріледі.", - ], - [ - "{engine} could not be started.", - "Не удалось запустить {engine}.", - "Impossible de lancer {engine}.", - "{engine} konnte nicht gestartet werden.", - "No se pudo iniciar {engine}.", - "Impossibile avviare {engine}.", - "Não foi possível iniciar {engine}.", - "{engine} ishga tushmadi.", - "{engine} іске қосылмады.", - ], - [ - "The settings name {engine}.", - "В настройках указан {engine}.", - "Les réglages indiquent {engine}.", - "In den Einstellungen steht {engine}.", - "En los ajustes figura {engine}.", - "Nelle impostazioni è indicato {engine}.", - "Nas configurações está {engine}.", - "Sozlamalarda {engine} ko‘rsatilgan.", - "Баптауларда {engine} көрсетілген.", - ], - [ - "The system has {engine}.", - "В системе найден {engine}.", - "Le système contient {engine}.", - "Im System gefunden: {engine}.", - "En el sistema se encontró {engine}.", - "Nel sistema è stato trovato {engine}.", - "No sistema foi encontrado {engine}.", - "Tizimda {engine} topildi.", - "Жүйеде {engine} табылды.", - ], - [ - "So that the marks are the same on every computer, game analysis runs on the official build.", - "Чтобы отметки совпадали на всех компьютерах, разбор партии идёт на официальной сборке.", - "Pour que les signes soient les mêmes sur tous les ordinateurs, l’analyse de partie se fait avec la version officielle.", - "Damit die Zeichen auf jedem Computer gleich sind, läuft die Partieanalyse mit dem offiziellen Build.", - "Para que los signos sean iguales en cualquier ordenador, el análisis de partidas usa la compilación oficial.", - "Perché i segni siano uguali su ogni computer, l’analisi della partita usa la build ufficiale.", - "Para que as marcas sejam iguais em qualquer computador, a análise de partidas usa a versão oficial.", - "Belgilar har qanday kompyuterda bir xil bo‘lishi uchun partiya tahlili rasmiy yig‘mada bo‘ladi.", - "Белгілер кез келген компьютерде бірдей болуы үшін партияны талдау ресми жинақта жүреді.", - ], - [ - "So that the marks are the same on every computer, the search for opening errors runs on the official build.", - "Чтобы отметки совпадали на всех компьютерах, поиск ошибок в дебютах идёт на официальной сборке.", - "Pour que les signes soient les mêmes sur tous les ordinateurs, la recherche d’erreurs d’ouverture se fait avec la version officielle.", - "Damit die Zeichen auf jedem Computer gleich sind, läuft die Suche nach Eröffnungsfehlern mit dem offiziellen Build.", - "Para que los signos sean iguales en cualquier ordenador, la búsqueda de errores de apertura usa la compilación oficial.", - "Perché i segni siano uguali su ogni computer, la ricerca degli errori d’apertura usa la build ufficiale.", - "Para que as marcas sejam iguais em qualquer computador, a procura de erros de abertura usa a versão oficial.", - "Belgilar har qanday kompyuterda bir xil bo‘lishi uchun debyut xatolarini qidirish rasmiy yig‘mada bo‘ladi.", - "Белгілер кез келген компьютерде бірдей болуы үшін дебют қателерін іздеу ресми жинақта жүреді.", - ], - [ - "Game analysis needs Stockfish 19 itself, so that the marks are the same on every computer.", - "Для разбора партии нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере.", - "L’analyse de partie a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs.", - "Die Partieanalyse braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind.", - "El análisis de partidas necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador.", - "L’analisi della partita richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer.", - "A análise de partidas precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador.", - "Partiya tahlili uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi.", - "Партияны талдау үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады.", - ], - [ - "The search for opening errors needs Stockfish 19 itself, so that the marks are the same on every computer.", - "Для поиска ошибок в дебютах нужен именно Stockfish 19 — так отметки одинаковы на любом компьютере.", - "La recherche d’erreurs d’ouverture a besoin de Stockfish 19 lui-même, pour que les signes soient les mêmes sur tous les ordinateurs.", - "Die Suche nach Eröffnungsfehlern braucht genau Stockfish 19, damit die Zeichen auf jedem Computer gleich sind.", - "La búsqueda de errores de apertura necesita justamente Stockfish 19, para que los signos sean iguales en cualquier ordenador.", - "La ricerca degli errori d’apertura richiede proprio Stockfish 19, perché i segni siano uguali su ogni computer.", - "A procura de erros de abertura precisa justamente do Stockfish 19, para que as marcas sejam iguais em qualquer computador.", - "Debyut xatolarini qidirish uchun aynan Stockfish 19 kerak — belgilar har qanday kompyuterda bir xil chiqadi.", - "Дебют қателерін іздеу үшін дәл Stockfish 19 керек — белгілер кез келген компьютерде бірдей болады.", - ], - [ - "Download it?", - "Скачать её?", - "La télécharger ?", - "Herunterladen?", - "¿Descargarla?", - "Scaricarla?", - "Baixá-la?", - "Yuklab olinsinmi?", - "Жүктеп алу керек пе?", - ], - [ - "Download Stockfish 19?", - "Скачать Stockfish 19?", - "Télécharger Stockfish 19 ?", - "Stockfish 19 herunterladen?", - "¿Descargar Stockfish 19?", - "Scaricare Stockfish 19?", - "Baixar o Stockfish 19?", - "Stockfish 19 yuklab olinsinmi?", - "Stockfish 19 жүктеп алу керек пе?", - ], - [ - "Your engine stays for position analysis.", - "Ваш движок остаётся для анализа позиции.", - "Votre moteur reste pour l’analyse de position.", - "Ihre Engine bleibt für die Stellungsanalyse.", - "Su motor sigue para el análisis de posiciones.", - "Il tuo motore resta per l’analisi della posizione.", - "Seu motor continua para a análise de posição.", - "Dvigatelingiz pozitsiya tahlili uchun qoladi.", - "Қозғалтқышыңыз позицияны талдау үшін қалады.", - ], - [ - "Not found: {files}", - "Не найдено: {files}", - "Introuvable : {files}", - "Nicht gefunden: {files}", - "No encontrado: {files}", - "Non trovato: {files}", - "Não encontrado: {files}", - "Topilmadi: {files}", - "Табылмады: {files}", - ], - [ - "Added to the shelf: {files}", - "Добавлено на полку: {files}", - "Ajouté à l’étagère : {files}", - "Zum Regal hinzugefügt: {files}", - "Añadido al estante: {files}", - "Aggiunto allo scaffale: {files}", - "Adicionado à estante: {files}", - "Javonga qo‘shildi: {files}", - "Сөреге қосылды: {files}", - ], - [ - "The engine is no longer the Stockfish 19 that was checked. Start the analysis again.", - "Движок уже не тот Stockfish 19, что прошёл проверку. Запустите разбор снова.", - "Le moteur n’est plus le Stockfish 19 vérifié. Relancez l’analyse.", - "Die Engine ist nicht mehr der geprüfte Stockfish 19. Starten Sie die Analyse erneut.", - "El motor ya no es el Stockfish 19 comprobado. Inicie el análisis de nuevo.", - "Il motore non è più lo Stockfish 19 verificato. Avvia di nuovo l’analisi.", - "O motor não é mais o Stockfish 19 verificado. Inicie a análise de novo.", - "Dvigatel endi tekshirilgan Stockfish 19 emas. Tahlilni qaytadan boshlang.", - "Қозғалтқыш енді тексерілген Stockfish 19 емес. Талдауды қайта бастаңыз.", - ], - [ - "Analysis needs Stockfish 19", - "Для анализа нужен Stockfish 19", - "L’analyse nécessite Stockfish 19", - "Die Analyse braucht Stockfish 19", - "El análisis necesita Stockfish 19", - "L’analisi richiede Stockfish 19", - "A análise precisa do Stockfish 19", - "Tahlil uchun Stockfish 19 kerak", - "Талдау үшін Stockfish 19 керек", - ], - [ - "Game analysis and the search for opening errors always use ChessPenguin's Stockfish 19, so that their marks are the same on every computer. Download it? The analysis will start as soon as the download finishes.", - "Анализ партии и поиск ошибок в дебютах всегда идут на Stockfish 19 из ChessPenguin — так отметки одинаковы на любом компьютере. Скачать его? Анализ начнётся, как только загрузка закончится.", - "L’analyse de partie et la recherche d’erreurs d’ouverture utilisent toujours le Stockfish 19 de ChessPenguin, pour que leurs signes soient les mêmes sur tous les ordinateurs. Le télécharger ? L’analyse commencera dès la fin du téléchargement.", - "Die Partieanalyse und die Suche nach Eröffnungsfehlern verwenden immer das Stockfish 19 von ChessPenguin, damit ihre Zeichen auf jedem Computer gleich sind. Herunterladen? Die Analyse beginnt, sobald der Download fertig ist.", - "El análisis de partidas y la búsqueda de errores de apertura usan siempre el Stockfish 19 de ChessPenguin, para que sus signos sean iguales en cualquier ordenador. ¿Descargarlo? El análisis empezará en cuanto termine la descarga.", - "L’analisi della partita e la ricerca degli errori d’apertura usano sempre lo Stockfish 19 di ChessPenguin, perché i segni siano uguali su ogni computer. Scaricarlo? L’analisi partirà appena finito il download.", - "A análise de partidas e a procura de erros de abertura usam sempre o Stockfish 19 do ChessPenguin, para que as marcas sejam iguais em qualquer computador. Descarregá-lo? A análise começa assim que o download terminar.", - "Partiya tahlili va debyut xatolarini qidirish doim ChessPenguin’ning Stockfish 19 dvigatelida bo‘ladi — belgilar har qanday kompyuterda bir xil chiqadi. Yuklab olinsinmi? Yuklash tugashi bilan tahlil boshlanadi.", - "Партияны талдау мен дебют қателерін іздеу әрқашан ChessPenguin-нің Stockfish 19 қозғалтқышында жүреді — белгілер кез келген компьютерде бірдей болады. Жүктеп алу керек пе? Жүктеу біткен соң талдау басталады.", - ], - [ - "This analysis was made with other engine settings", - "Этот анализ сделан с прежними настройками движка", - "Cette analyse a été faite avec d’autres réglages du moteur", - "Diese Analyse wurde mit anderen Engine-Einstellungen gemacht", - "Este análisis se hizo con otros ajustes del motor", - "Questa analisi è stata fatta con altre impostazioni del motore", - "Esta análise foi feita com outras definições do motor", - "Bu tahlil dvigatelning boshqa sozlamalari bilan qilingan", - "Бұл талдау қозғалтқыштың басқа баптауларымен жасалған", - ], - [ - "Every position is analysed again, the same way on every computer", - "Все позиции анализируются заново — одинаково на любом компьютере", - "Toutes les positions sont analysées de nouveau, de la même façon sur tous les ordinateurs", - "Alle Stellungen werden neu analysiert, auf jedem Computer gleich", - "Todas las posiciones se analizan de nuevo, igual en cualquier ordenador", - "Tutte le posizioni vengono analizzate di nuovo, allo stesso modo su ogni computer", - "Todas as posições são analisadas de novo, da mesma forma em qualquer computador", - "Barcha pozitsiyalar qayta tahlil qilinadi — har qanday kompyuterda bir xil", - "Барлық позиция қайта талданады — кез келген компьютерде бірдей", - ], - [ - "Analyse with the engine", - "Проанализировать движком", - "Analyser avec le moteur", - "Mit der Engine analysieren", - "Analizar con el motor", - "Analizza con il motore", - "Analisar com o motor", - "Dvigatel bilan tahlil qilish", - "Қозғалтқышпен талдау", - ], - [ - "Last year", - "За год", - "La dernière année", - "Letztes Jahr", - "Último año", - "Ultimo anno", - "Último ano", - "Oxirgi yil", - "Соңғы жыл", - ], - [ - "Last 2 years", - "За 2 года", - "Les 2 dernières années", - "Letzte 2 Jahre", - "Últimos 2 años", - "Ultimi 2 anni", - "Últimos 2 anos", - "Oxirgi 2 yil", - "Соңғы 2 жыл", - ], - [ - "Last 3 months", - "За 3 месяца", - "Les 3 derniers mois", - "Letzte 3 Monate", - "Últimos 3 meses", - "Ultimi 3 mesi", - "Últimos 3 meses", - "Oxirgi 3 oy", - "Соңғы 3 ай", - ], - [ - "Last 6 months", - "За полгода", - "Les 6 derniers mois", - "Letzte 6 Monate", - "Últimos 6 meses", - "Ultimi 6 mesi", - "Últimos 6 meses", - "Oxirgi 6 oy", - "Соңғы 6 ай", - ], - [ - "Last {n} months", - "За {n} мес.", - "Les {n} derniers mois", - "Letzte {n} Monate", - "Últimos {n} meses", - "Ultimi {n} mesi", - "Últimos {n} meses", - "Oxirgi {n} oy", - "Соңғы {n} ай", - ], - [ - "Last {n} games", - "Последние {n} партий", - "Les {n} dernières parties", - "Letzte {n} Partien", - "Últimas {n} partidas", - "Ultime {n} partite", - "Últimas {n} partidas", - "Oxirgi {n} partiya", - "Соңғы {n} партия", - ], - [ - "The games have no dates: by number only", - "У партий нет дат: выбор только по числу", - "Les parties n’ont pas de date : par nombre seulement", - "Die Partien haben kein Datum: nur nach Anzahl", - "Las partidas no tienen fecha: solo por número", - "Le partite non hanno data: solo per numero", - "As partidas não têm data: só por número", - "Partiyalarda sana yo‘q: faqat soni bo‘yicha", - "Партиялардың күні жоқ: тек саны бойынша", - ], - [ - "Without a date: {n} — taken only with all games", - "Без даты: {n} — учитываются только во «Всех партиях»", - "Sans date : {n} — prises seulement avec toutes les parties", - "Ohne Datum: {n} — nur bei allen Partien berücksichtigt", - "Sin fecha: {n} — solo se cuentan con todas las partidas", - "Senza data: {n} — contate solo con tutte le partite", - "Sem data: {n} — contadas só com todas as partidas", - "Sanasiz: {n} — faqat «Barcha partiyalar»da hisoblanadi", - "Күнсіз: {n} — тек «Барлық партиялар» кезінде есептеледі", - ], - [ - "Which of his games: by date — counted back from his newest game; by number — the newest of each colour", - "Какие его партии брать: по времени — считая назад от его последней партии; по числу — самые свежие каждым цветом", - "Quelles parties prendre : par date — en remontant depuis sa dernière partie ; par nombre — les plus récentes de chaque couleur", - "Welche seiner Partien: nach Zeit — rückwärts ab seiner letzten Partie; nach Anzahl — die neuesten mit jeder Farbe", - "Qué partidas tomar: por fecha — contando hacia atrás desde su última partida; por número — las más recientes con cada color", - "Quali partite prendere: per data — a ritroso dalla sua ultima partita; per numero — le più recenti con ogni colore", - "Quais partidas usar: por data — contando para trás da sua última partida; por número — as mais recentes com cada cor", - "Qaysi partiyalarini olish: vaqt bo‘yicha — oxirgi partiyasidan orqaga sanab; soni bo‘yicha — har bir rangda eng yangilari", - "Қай партияларын алу: уақыт бойынша — соңғы партиясынан кері санап; саны бойынша — әр түспен ең жаңалары", - ], - [ - "Preparations", - "Подготовки", - "Préparations", - "Vorbereitungen", - "Preparaciones", - "Preparazioni", - "Preparações", - "Tayyorgarliklar", - "Дайындықтар", - ], - [ - "🗐 Preparations", - "🗐 Подготовки", - "🗐 Préparations", - "🗐 Vorbereitungen", - "🗐 Preparaciones", - "🗐 Preparazioni", - "🗐 Preparações", - "🗐 Tayyorgarliklar", - "🗐 Дайындықтар", - ], - [ - "Preparations against opponents: the saved ones and a new one", - "Подготовки к соперникам: сохранённые и новая", - "Préparations contre des adversaires : les enregistrées et une nouvelle", - "Vorbereitungen auf Gegner: die gespeicherten und eine neue", - "Preparaciones contra rivales: las guardadas y una nueva", - "Preparazioni contro avversari: quelle salvate e una nuova", - "Preparações contra adversários: as salvas e uma nova", - "Raqiblarga tayyorgarliklar: saqlanganlari va yangisi", - "Қарсыластарға дайындықтар: сақталғандары және жаңасы", - ], - [ - "Nothing yet. A preparation is saved by itself as soon as you start it: prepare against a player.", - "Пока пусто. Подготовка сохраняется сама сразу при запуске: подготовьтесь к сопернику.", - "Rien pour l’instant. Une préparation s’enregistre d’elle-même dès son lancement : préparez-vous contre un joueur.", - "Noch nichts. Eine Vorbereitung wird von selbst gespeichert, sobald sie begonnen wird: bereiten Sie sich auf einen Spieler vor.", - "Nada todavía. Una preparación se guarda sola en cuanto la inicias: prepárate contra un jugador.", - "Ancora niente. Una preparazione si salva da sola appena la avvii: preparati contro un giocatore.", - "Nada ainda. Uma preparação é guardada sozinha assim que a inicias: prepara-te contra um jogador.", - "Hozircha bo‘sh. Tayyorgarlik boshlanishi bilan o‘zi saqlanadi: raqibga tayyorlaning.", - "Әзірге бос. Дайындық басталғанымен өзі сақталады: қарсыласқа дайындалыңыз.", - ], - [ - "Could not save: {e}", - "Не удалось сохранить: {e}", - "Impossible d’enregistrer : {e}", - "Speichern fehlgeschlagen: {e}", - "No se pudo guardar: {e}", - "Impossibile salvare: {e}", - "Não foi possível salvar: {e}", - "Saqlab bo‘lmadi: {e}", - "Сақтау мүмкін болмады: {e}", - ], - [ - "♟ New preparation…", - "♟ Новая подготовка…", - "♟ Nouvelle préparation…", - "♟ Neue Vorbereitung…", - "♟ Nueva preparación…", - "♟ Nuova preparazione…", - "♟ Nova preparação…", - "♟ Yangi tayyorgarlik…", - "♟ Жаңа дайындық…", - ], - [ - "Add a database to the shelf first", - "Сначала добавьте базу на полку", - "Ajoutez d’abord une base à l’étagère", - "Fügen Sie zuerst eine Datenbank zum Regal hinzu", - "Primero añada una base a la estantería", - "Aggiungi prima un database allo scaffale", - "Primeiro adicione uma base à estante", - "Avval javonga baza qo‘shing", - "Алдымен сөреге база қосыңыз", - ], - [ - "Choose a player in the current database", - "Выбрать игрока в текущей базе", - "Choisir un joueur dans la base actuelle", - "Einen Spieler in der aktuellen Datenbank wählen", - "Elegir un jugador en la base actual", - "Scegli un giocatore nel database attuale", - "Escolher um jogador na base atual", - "Joriy bazadan o‘yinchini tanlash", - "Ағымдағы базадан ойыншыны таңдау", - ], - ["OK", "ОК", "OK", "OK", "Aceptar", "OK", "OK", "OK", "ОК"], - [ - "Delete?", - "Удалить?", - "Supprimer ?", - "Löschen?", - "¿Eliminar?", - "Eliminare?", - "Excluir?", - "O‘chirilsinmi?", - "Жою керек пе?", - ], - [ - "Rename", - "Переименовать", - "Renommer", - "Umbenennen", - "Renombrar", - "Rinomina", - "Renomear", - "Qayta nomlash", - "Атын өзгерту", - ], - [ - "errors: ?? {b} · ? {m} · ?! {i}", - "ошибки: ?? {b} · ? {m} · ?! {i}", - "erreurs : ?? {b} · ? {m} · ?! {i}", - "Fehler: ?? {b} · ? {m} · ?! {i}", - "errores: ?? {b} · ? {m} · ?! {i}", - "errori: ?? {b} · ? {m} · ?! {i}", - "erros: ?? {b} · ? {m} · ?! {i}", - "xatolar: ?? {b} · ? {m} · ?! {i}", - "қателер: ?? {b} · ? {m} · ?! {i}", - ], - [ - "errors not searched", - "ошибки ещё не искали", - "erreurs non cherchées", - "Fehler nicht gesucht", - "errores no buscados", - "errori non cercati", - "erros não procurados", - "xatolar qidirilmagan", - "қателер ізделмеген", - ], - [ - "saved {date}", - "сохранено {date}", - "enregistrée le {date}", - "gespeichert am {date}", - "guardada el {date}", - "salvata il {date}", - "salva em {date}", - "saqlangan: {date}", - "сақталған: {date}", - ], - [ - "database not found: {path}", - "база не найдена: {path}", - "base introuvable : {path}", - "Datenbank nicht gefunden: {path}", - "base no encontrada: {path}", - "database non trovato: {path}", - "base não encontrada: {path}", - "baza topilmadi: {path}", - "база табылмады: {path}", - ], - [ - "All", - "Все", - "Toutes", - "Alle", - "Todas", - "Tutte", - "Todas", - "Hammasi", - "Барлығы", - ], - [ - "1 yr", "1 год", "1 an", "1 J.", "1 año", "1 anno", "1 ano", "1 yil", "1 жыл", - ], - [ - "2 yrs", - "2 года", - "2 ans", - "2 J.", - "2 años", - "2 anni", - "2 anos", - "2 yil", - "2 жыл", - ], - [ - "{n} mo.", - "{n} мес.", - "{n} mois", - "{n} Mon.", - "{n} m.", - "{n} mesi", - "{n} m.", - "{n} oy", - "{n} ай", - ], - [ - "Last {n}", - "Посл. {n}", - "{n} dern.", - "Letzte {n}", - "Últ. {n}", - "Ult. {n}", - "Últ. {n}", - "Oxirgi {n}", - "Соңғы {n}", - ], - [ - "Counted back from his newest game — {date}", - "Считая от его последней партии — {date}", - "En remontant depuis sa dernière partie — {date}", - "Ab seiner letzten Partie gezählt — {date}", - "Contando desde su última partida — {date}", - "Contando dalla sua ultima partita — {date}", - "Contando a partir da sua última partida — {date}", - "Oxirgi partiyasidan sanaladi — {date}", - "Соңғы партиясынан бастап саналады — {date}", - ], - [ - "Without a date, not counted: {n} (only with all games)", - "Без даты не учтено: {n} (только во «Всех партиях»)", - "Sans date, non comptées : {n} (seulement avec toutes les parties)", - "Ohne Datum, nicht gezählt: {n} (nur bei allen Partien)", - "Sin fecha, no contadas: {n} (solo con todas las partidas)", - "Senza data, non contate: {n} (solo con tutte le partite)", - "Sem data, não contadas: {n} (só com todas as partidas)", - "Sanasiz, hisobga olinmagan: {n} (faqat «Barcha partiyalar»da)", - "Күнсіз, есепке алынбаған: {n} (тек «Барлық партиялар» кезінде)", - ], - [ - "No games in this period", - "За этот период партий нет", - "Aucune partie sur cette période", - "Keine Partien in diesem Zeitraum", - "No hay partidas en este periodo", - "Nessuna partita in questo periodo", - "Nenhuma partida neste período", - "Bu davrda partiyalar yo‘q", - "Бұл кезеңде партиялар жоқ", - ], - [ - "both colours", - "обоими цветами", - "des deux couleurs", - "mit beiden Farben", - "con ambos colores", - "con entrambi i colori", - "com ambas as cores", - "ikkala rangda", - "екі түспен", - ], - [ - "Double-click to open", - "Двойной щелчок — открыть", - "Double-clic pour ouvrir", - "Doppelklick zum Öffnen", - "Doble clic para abrir", - "Doppio clic per aprire", - "Clique duplo para abrir", - "Ochish uchun ikki marta bosing", - "Ашу үшін екі рет басыңыз", - ], - [ - "The database is not found: put the file back or delete the preparation", - "База не найдена: верните файл на место или удалите подготовку", - "Base introuvable : remettez le fichier en place ou supprimez la préparation", - "Datenbank nicht gefunden: Datei zurücklegen oder Vorbereitung löschen", - "Base no encontrada: devuelva el archivo a su sitio o elimine la preparación", - "Database non trovato: rimetti il file al suo posto o elimina la preparazione", - "Base não encontrada: devolva o arquivo ao lugar ou exclua a preparação", - "Baza topilmadi: faylni joyiga qaytaring yoki tayyorgarlikni o‘chiring", - "База табылмады: файлды орнына қайтарыңыз немесе дайындықты жойыңыз", - ], - [ - "The player is not in the database: {name}", - "Игрока нет в базе: {name}", - "Le joueur n’est pas dans la base : {name}", - "Der Spieler ist nicht in der Datenbank: {name}", - "El jugador no está en la base: {name}", - "Il giocatore non è nel database: {name}", - "O jogador não está na base: {name}", - "O‘yinchi bazada yo‘q: {name}", - "Ойыншы базада жоқ: {name}", - ], - [ - "No games as White in this period", - "Белыми за этот период партий нет", - "Aucune partie avec les Blancs sur cette période", - "Keine Partien mit Weiß in diesem Zeitraum", - "No hay partidas con blancas en este periodo", - "Nessuna partita con il Bianco in questo periodo", - "Nenhuma partida de brancas neste período", - "Bu davrda oqlar bilan partiyalar yo‘q", - "Бұл кезеңде ақтармен партиялар жоқ", - ], - [ - "No games as Black in this period", - "Чёрными за этот период партий нет", - "Aucune partie avec les Noirs sur cette période", - "Keine Partien mit Schwarz in diesem Zeitraum", - "No hay partidas con negras en este periodo", - "Nessuna partita con il Nero in questo periodo", - "Nenhuma partida de pretas neste período", - "Bu davrda qoralar bilan partiyalar yo‘q", - "Бұл кезеңде қаралармен партиялар жоқ", - ], - [ - "last {n}", - "последние {n}", - "les {n} dernières", - "letzte {n}", - "últimas {n}", - "ultime {n}", - "últimas {n}", - "oxirgi {n}", - "соңғы {n}", - ], - [ - "🌐 Open on Lichess", - "🌐 Открыть на Lichess", - "🌐 Ouvrir sur Lichess", - "🌐 Auf Lichess öffnen", - "🌐 Abrir en Lichess", - "🌐 Apri su Lichess", - "🌐 Abrir no Lichess", - "🌐 Lichess’da ochish", - "🌐 Lichess-те ашу", - ], - [ - "🌐 Open on Chess.com", - "🌐 Открыть на Chess.com", - "🌐 Ouvrir sur Chess.com", - "🌐 Auf Chess.com öffnen", - "🌐 Abrir en Chess.com", - "🌐 Apri su Chess.com", - "🌐 Abrir no Chess.com", - "🌐 Chess.com’da ochish", - "🌐 Chess.com-да ашу", - ], - [ - "🌐 Open the game's link", - "🌐 Открыть ссылку партии", - "🌐 Ouvrir le lien de la partie", - "🌐 Link der Partie öffnen", - "🌐 Abrir el enlace de la partida", - "🌐 Apri il link della partita", - "🌐 Abrir o link da partida", - "🌐 Partiya havolasini ochish", - "🌐 Партия сілтемесін ашу", - ], - [ - "Open on Lichess (in the browser, at this move)", - "Открыть на Lichess (в браузере, с этого хода)", - "Ouvrir sur Lichess (dans le navigateur, à ce coup)", - "Auf Lichess öffnen (im Browser, bei diesem Zug)", - "Abrir en Lichess (en el navegador, en esta jugada)", - "Apri su Lichess (nel browser, a questa mossa)", - "Abrir no Lichess (no navegador, neste lance)", - "Lichess’da ochish (brauzerda, shu yurishdan)", - "Lichess-те ашу (браузерде, осы жүрістен)", - ], - [ - "Open on Lichess (in the browser)", - "Открыть на Lichess (в браузере)", - "Ouvrir sur Lichess (dans le navigateur)", - "Auf Lichess öffnen (im Browser)", - "Abrir en Lichess (en el navegador)", - "Apri su Lichess (nel browser)", - "Abrir no Lichess (no navegador)", - "Lichess’da ochish (brauzerda)", - "Lichess-те ашу (браузерде)", - ], - [ - "Open on Chess.com (in the browser)", - "Открыть на Chess.com (в браузере)", - "Ouvrir sur Chess.com (dans le navigateur)", - "Auf Chess.com öffnen (im Browser)", - "Abrir en Chess.com (en el navegador)", - "Apri su Chess.com (nel browser)", - "Abrir no Chess.com (no navegador)", - "Chess.com’da ochish (brauzerda)", - "Chess.com-да ашу (браузерде)", - ], - [ - "Open the game's link (in the browser)", - "Открыть ссылку партии (в браузере)", - "Ouvrir le lien de la partie (dans le navigateur)", - "Link der Partie öffnen (im Browser)", - "Abrir el enlace de la partida (en el navegador)", - "Apri il link della partita (nel browser)", - "Abrir o link da partida (no navegador)", - "Partiya havolasini ochish (brauzerda)", - "Партия сілтемесін ашу (браузерде)", - ], - // --- opening repertoires --- - [ - "Already in the repertoire — no changes", - "Уже в репертуаре — изменений нет", - "Déjà dans le répertoire — aucun changement", - "Bereits im Repertoire — keine Änderungen", - "Ya está en el repertorio — sin cambios", - "Già nel repertorio — nessuna modifica", - "Já está no repertório — sem alterações", - "Repertuarda bor — o‘zgarish yo‘q", - "Репертуарда бар — өзгеріс жоқ", - ], - [ - "The path was already in the repertoire; annotations added: {n}", - "Путь уже был в репертуаре; добавлены аннотации: {n}", - "Le chemin était déjà dans le répertoire ; annotations ajoutées : {n}", - "Der Pfad war bereits im Repertoire; hinzugefügte Anmerkungen: {n}", - "La ruta ya estaba en el repertorio; anotaciones añadidas: {n}", - "Il percorso era già nel repertorio; annotazioni aggiunte: {n}", - "O caminho já estava no repertório; anotações adicionadas: {n}", - "Yo‘l repertuarda bor edi; qo‘shilgan izohlar: {n}", - "Жол репертуарда болды; қосылған түсініктемелер: {n}", - ], - [ - "Added to “{name}”: new moves: {added} · matched: {matched}", - "Добавлено в «{name}»: новых ходов: {added} · совпало: {matched}", - "Ajouté à « {name} » : nouveaux coups : {added} · correspondants : {matched}", - "Zu „{name}“ hinzugefügt: neue Züge: {added} · übereinstimmend: {matched}", - "Añadido a «{name}»: jugadas nuevas: {added} · coincidentes: {matched}", - "Aggiunto a «{name}»: nuove mosse: {added} · corrispondenti: {matched}", - "Adicionado a “{name}”: novos lances: {added} · coincidentes: {matched}", - "“{name}” repertuariga qo‘shildi: yangi yurishlar: {added} · mos: {matched}", - "«{name}» репертуарына қосылды: жаңа жүрістер: {added} · сәйкес: {matched}", - ], - [ - "Add to repertoire…", - "Добавить в репертуар…", - "Ajouter au répertoire…", - "Zum Repertoire hinzufügen…", - "Añadir al repertorio…", - "Aggiungi al repertorio…", - "Adicionar ao repertório…", - "Repertuariga qo‘shish…", - "Репертуарға қосу…", - ], - [ - "Select the move up to which to add", - "Выберите ход, до которого добавить", - "Sélectionnez le coup jusqu’auquel ajouter", - "Zug auswählen, bis zu dem hinzugefügt wird", - "Selecciona la jugada hasta la que añadir", - "Seleziona la mossa fino alla quale aggiungere", - "Selecione o lance até o qual adicionar", - "Qaysi yurishgacha qo‘shishni tanlang", - "Қай жүріске дейін қосуды таңдаңыз", - ], - [ - "Opening training (α version)", - "Тренировка дебюта (α версия)", - "Entraînement aux ouvertures (version α)", - "Eröffnungstraining (α-Version)", - "Entrenamiento de aperturas (versión α)", - "Allenamento nelle aperture (versione α)", - "Treino de aberturas (versão α)", - "Debyut mashg‘uloti (α versiya)", - "Дебют жаттығуы (α нұсқасы)", - ], - [ - "Add only the path from the start through this move, with its comments and NAGs", - "Добавить только путь от начала до этого хода со всеми комментариями и NAG", - "Ajouter uniquement le chemin du début jusqu’à ce coup, avec ses commentaires et NAG", - "Nur den Pfad vom Beginn bis zu diesem Zug mit Kommentaren und NAGs hinzufügen", - "Añadir solo la ruta desde el inicio hasta esta jugada, con sus comentarios y NAG", - "Aggiungi solo il percorso dall’inizio fino a questa mossa, con commenti e NAG", - "Adicionar apenas o caminho do início até este lance, com seus comentários e NAGs", - "Faqat boshlang‘ichdan shu yurishgacha bo‘lgan yo‘lni izohlar va NAG bilan qo‘shish", - "Тек басынан осы жүріске дейінгі жолды түсініктемелері мен NAG арқылы қосу", - ], - [ - "No enabled moves in this repertoire", - "В репертуаре нет включённых ходов", - "Aucun coup actif dans ce répertoire", - "Keine aktiven Züge in diesem Repertoire", - "No hay jugadas activas en este repertorio", - "Nessuna mossa attiva in questo repertorio", - "Não há lances ativos neste repertório", - "Bu repertuarda faol yurishlar yo‘q", - "Бұл репертуарда белсенді жүрістер жоқ", - ], - [ - "Choose a repertoire", - "Выберите репертуар", - "Choisissez un répertoire", - "Repertoire auswählen", - "Elige un repertorio", - "Scegli un repertorio", - "Escolha um repertório", - "Repertuarni tanlang", - "Репертуарды таңдаңыз", - ], - [ - "Import PGN…", - "Импорт PGN…", - "Importer un PGN…", - "PGN importieren…", - "Importar PGN…", - "Importa PGN…", - "Importar PGN…", - "PGN import…", - "PGN импорт…", - ], - [ - "Export PGN…", - "Экспорт PGN…", - "Exporter le PGN…", - "PGN exportieren…", - "Exportar PGN…", - "Esporta PGN…", - "Exportar PGN…", - "PGN eksport…", - "PGN экспорт…", - ], - [ - "Repertoires", - "Репертуары", - "Répertoires", - "Repertoires", - "Repertorios", - "Repertori", - "Repertórios", - "Repertuarlar", - "Репертуарлар", - ], - [ - "Name", - "Название", - "Nom", - "Name", - "Nombre", - "Nome", - "Nome", - "Nomi", - "Аты", - ], - [ - "Import into one repertoire", - "Импортировать в один репертуар", - "Importer dans un seul répertoire", - "In ein Repertoire importieren", - "Importar en un solo repertorio", - "Importa in un solo repertorio", - "Importar para um único repertório", - "Bitta repertuarga import qilish", - "Бір репертуарға импорттау", - ], - [ - "No repertoires yet", - "Репертуаров пока нет", - "Aucun répertoire pour le moment", - "Noch keine Repertoires", - "Aún no hay repertorios", - "Ancora nessun repertorio", - "Ainda não há repertórios", - "Hozircha repertuarlar yo‘q", - "Әзірге репертуар жоқ", - ], - [ - "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", - "Сицилия қорғанысы: Найдорф", - ], - [ - "The record of example repertoires is damaged; examples were not added", - "Запись о примерах репертуаров повреждена; примеры не добавлены", - "L’enregistrement des répertoires d’exemple est endommagé ; les exemples n’ont pas été ajoutés", - "Die Liste der Beispielrepertoires ist beschädigt; Beispiele wurden nicht hinzugefügt", - "El registro de repertorios de ejemplo está dañado; no se añadieron ejemplos", - "Il registro dei repertori di esempio è danneggiato; gli esempi non sono stati aggiunti", - "O registro dos repertórios de exemplo está danificado; os exemplos não foram adicionados", - "Namuna repertuarlar yozuvi buzilgan; namunalar qo‘shilmadi", - "Мысал репертуарлар жазбасы бүлінген; мысалдар қосылмады", - ], - [ - "Queen's Gambit", - "Ферзевый гамбит", - "Gambit dame", - "Damengambit", - "Gambito de dama", - "Gambetto di donna", - "Gambito da Dama", - "Farzin gambiti", - "Ферзь гамбиті", - ], - [ - "Semi-Slav: Triangle", - "Полуславянская защита: треугольник", - "Semi-slave : triangle", - "Halbslawisch: Dreieck", - "Semieslava: triángulo", - "Semi-Slava: triangolo", - "Semi-Eslava: triângulo", - "Yarim slavyan himoyasi: uchburchak", - "Жартылай славян қорғанысы: үшбұрыш", - ], - [ - "New repertoire", - "Новый репертуар", - "Nouveau répertoire", - "Neues Repertoire", - "Nuevo repertorio", - "Nuovo repertorio", - "Novo repertório", - "Yangi repertuar", - "Жаңа репертуар", - ], - [ - "Enabled moves", - "Включено ходов", - "Coups actifs", - "Aktive Züge", - "Jugadas activas", - "Mosse attive", - "Lances ativos", - "Faol yurishlar", - "Белсенді жүрістер", - ], - [ - "White: due", - "Белые: к повт.", - "Blancs : à réviser", - "Weiß: fällig", - "Blancas: por repasar", - "Bianco: da ripassare", - "Brancas: por revisar", - "Oq: takrorlash", - "Ақ: қайталау", - ], - [ - "Black: due", - "Чёрные: к повт.", - "Noirs : à réviser", - "Schwarz: fällig", - "Negras: por repasar", - "Nero: da ripassare", - "Pretas: por revisar", - "Qora: takrorlash", - "Қара: қайталау", - ], - [ - "Both sides", - "Обе стороны", - "Les deux camps", - "Beide Seiten", - "Ambos bandos", - "Entrambi i lati", - "Ambos os lados", - "Ikkala tomon", - "Екі тарап", - ], - [ - "This mode has not been used yet", - "Этот режим ещё не использовался", - "Ce mode n’a pas encore été utilisé", - "Dieser Modus wurde noch nicht verwendet", - "Este modo aún no se ha utilizado", - "Questa modalità non è ancora stata usata", - "Este modo ainda não foi usado", - "Bu rejim hali ishlatilmagan", - "Бұл режим әлі қолданылмады", - ], - [ - "Due", - "К повторению", - "À réviser", - "Fällig", - "Por repasar", - "Da ripassare", - "Por revisar", - "Takrorlash", - "Қайталау", - ], - [ - "Delete…", - "Удалить…", - "Supprimer…", - "Löschen…", - "Eliminar…", - "Elimina…", - "Excluir…", - "O‘chirish…", - "Жою…", - ], - [ - "Line", - "Линия", - "Ligne", - "Linie", - "Línea", - "Linea", - "Linha", - "Chiziq", - "Жол", - ], - [ - "Runs", - "Прохождения", - "Parcours", - "Durchgänge", - "Recorridos", - "Percorsi", - "Percursos", - "O‘tishlar", - "Өтулер", - ], - [ - "Last mistakes", - "Ошибки последнего", - "Erreurs du dernier parcours", - "Fehler im letzten Durchgang", - "Errores del último recorrido", - "Errori dell’ultimo percorso", - "Erros do último percurso", - "Oxirgi o‘tishdagi xatolar", - "Соңғы өтудегі қателер", - ], - [ - "Clean streak", - "Чистая серия", - "Série sans erreur", - "Fehlerfreie Serie", - "Racha sin errores", - "Serie senza errori", - "Sequência sem erros", - "Xatosiz seriya", - "Қатесіз серия", - ], - [ - "Recent", - "Последние", - "Récents", - "Zuletzt", - "Recientes", - "Recenti", - "Recentes", - "So‘nggi", - "Соңғы", - ], - [ - "Add to repertoire", - "Добавить в репертуар", - "Ajouter au répertoire", - "Zum Repertoire hinzufügen", - "Añadir al repertorio", - "Aggiungi al repertorio", - "Adicionar ao repertório", - "Repertuariga qo‘shish", - "Репертуарға қосу", - ], - [ - "← Repertoires", - "← Репертуары", - "← Répertoires", - "← Repertoires", - "← Repertorios", - "← Repertori", - "← Repertórios", - "← Repertuarlar", - "← Репертуарлар", - ], - [ - "Start over", - "Начать заново", - "Recommencer", - "Neu beginnen", - "Empezar de nuevo", - "Ricomincia", - "Recomeçar", - "Qaytadan boshlash", - "Қайта бастау", - ], - [ - "Queue", - "Очередь", - "File d’attente", - "Warteschlange", - "Cola", - "Coda", - "Fila", - "Navbat", - "Кезек", - ], - [ - "Path queues are not available in the current core API", - "Очереди путей недоступны в текущем API ядра", - "Les files de chemins ne sont pas disponibles dans l’API actuelle du moteur", - "Pfad-Warteschlangen sind in der aktuellen Core-API nicht verfügbar", - "Las colas de rutas no están disponibles en la API actual del núcleo", - "Le code dei percorsi non sono disponibili nell’API attuale del core", - "As filas de caminhos não estão disponíveis na API atual do núcleo", - "Yo‘l navbatlari joriy yadro API sida mavjud emas", - "Жол кезектері ағымдағы ядро API-інде жоқ", - ], - [ - "half-moves", - "полуходов", - "demi-coups", - "Halbzüge", - "medias jugadas", - "mezze mosse", - "meio-lances", - "yarim yurishlar", - "жарты жүрістер", - ], - [ - "No limit", - "Без ограничения", - "Sans limite", - "Unbegrenzt", - "Sin límite", - "Senza limite", - "Sem limite", - "Cheksiz", - "Шектеусіз", - ], - [ - "Start branch run", - "Начать проход веток", - "Commencer un parcours de variante", - "Variantendurchgang starten", - "Iniciar recorrido de variantes", - "Avvia percorso della variante", - "Iniciar percurso de variantes", - "Variantlar o‘tishini boshlash", - "Нұсқалар өтісін бастау", - ], - [ - "No enabled moves for this mode and depth", - "Нет включённых ходов для этого режима и глубины", - "Aucun coup actif pour ce mode et cette profondeur", - "Keine aktiven Züge für diesen Modus und diese Tiefe", - "No hay jugadas activas para este modo y profundidad", - "Nessuna mossa attiva per questa modalità e profondità", - "Não há lances ativos para este modo e profundidade", - "Bu rejim va chuqurlikda faol yurishlar yo‘q", - "Бұл режим мен тереңдікте белсенді жүрістер жоқ", - ], - [ - "Tree", - "Дерево", - "Arbre", - "Baum", - "Árbol", - "Albero", - "Árvore", - "Daraxt", - "Ағаш", - ], - [ - "Enable for training", - "Вернуть в тренировку", - "Réactiver pour l’entraînement", - "Wieder trainieren", - "Reactivar para entrenar", - "Riattiva per l’allenamento", - "Reativar para treino", - "Mashg‘ulotga qaytarish", - "Жаттығуға қайтару", - ], - [ - "Disable branch", - "Не учить ветку", - "Ne pas apprendre la variante", - "Variante nicht lernen", - "No aprender la variante", - "Non imparare la variante", - "Não aprender a variante", - "Variantni o‘rganmaslik", - "Нұсқаны үйренмеу", - ], - [ - "There are no moves in this repertoire yet", - "В репертуаре пока нет ходов", - "Ce répertoire ne contient encore aucun coup", - "Dieses Repertoire enthält noch keine Züge", - "Este repertorio aún no tiene jugadas", - "Questo repertorio non contiene ancora mosse", - "Este repertório ainda não tem lances", - "Bu repertuarda hali yurishlar yo‘q", - "Бұл репертуарда әлі жүрістер жоқ", - ], - [ - "Or open a game, select the last move of a line and choose “Add to repertoire…”.", - "Или откройте партию, выберите последний ход нужной линии и нажмите «Добавить в репертуар…».", - "Ou ouvrez une partie, sélectionnez le dernier coup d’une ligne et choisissez « Ajouter au répertoire… ».", - "Oder öffnen Sie eine Partie, wählen Sie den letzten Zug einer Linie und „Zum Repertoire hinzufügen…“.", - "O abre una partida, selecciona la última jugada de una línea y elige «Añadir al repertorio…».", - "Oppure apri una partita, seleziona l’ultima mossa di una linea e scegli «Aggiungi al repertorio…».", - "Ou abra uma partida, selecione o último lance de uma linha e escolha “Adicionar ao repertório…”.", - "Yoki partiyani oching, yo‘ldagi oxirgi yurishni tanlang va “Repertuariga qo‘shish…”ni bosing.", - "Немесе партияны ашыңыз, жолдың соңғы жүрісін таңдап, «Репертуарға қосу…» басыңыз.", - ], - [ - " ∅ not trained", - " ∅ не учить", - " ∅ non appris", - " ∅ nicht trainiert", - " ∅ no aprendido", - " ∅ non imparato", - " ∅ não aprendido", - " ∅ o‘rganilmaydi", - " ∅ үйренілмейді", - ], - [ - "Show position", - "Показать позицию", - "Afficher la position", - "Stellung anzeigen", - "Mostrar posición", - "Mostra posizione", - "Mostrar posição", - "Pozitsiyani ko‘rsatish", - "Позицияны көрсету", - ], - [ - "Show move statistics", - "Показать статистику хода", - "Afficher les statistiques du coup", - "Zugstatistik anzeigen", - "Mostrar estadísticas de la jugada", - "Mostra statistiche della mossa", - "Mostrar estatísticas do lance", - "Yurish statistikasini ko‘rsatish", - "Жүріс статистикасын көрсету", - ], - [ - "No attempts in the selected mode", - "Нет попыток в выбранном режиме", - "Aucune tentative dans le mode sélectionné", - "Keine Versuche im gewählten Modus", - "No hay intentos en el modo seleccionado", - "Nessun tentativo nella modalità selezionata", - "Não há tentativas no modo selecionado", - "Tanlangan rejimda urinishlar yo‘q", - "Таңдалған режимде әрекеттер жоқ", - ], - [ - "Filter", - "Фильтр", - "Filtre", - "Filter", - "Filtro", - "Filtro", - "Filtro", - "Filtr", - "Сүзгі", - ], - [ - "With mistakes", - "С ошибками", - "Avec erreurs", - "Mit Fehlern", - "Con errores", - "Con errori", - "Com erros", - "Xatolar bilan", - "Қателермен", - ], - [ - "Wrong", - "Неверных", - "Incorrects", - "Falsch", - "Incorrectas", - "Sbagliate", - "Incorretos", - "Noto‘g‘ri", - "Қате", - ], - [ - "Hints", - "Подсказки", - "Indices", - "Hinweise", - "Pistas", - "Suggerimenti", - "Dicas", - "Maslahatlar", - "Кеңестер", - ], - [ - "History", - "История", - "Historique", - "Verlauf", - "Historial", - "Cronologia", - "Histórico", - "Tarix", - "Тарих", - ], - [ - "No completed runs", - "Нет завершённых проходов", - "Aucun parcours terminé", - "Keine abgeschlossenen Durchgänge", - "No hay recorridos completados", - "Nessun percorso completato", - "Não há percursos concluídos", - "Yakunlangan o‘tishlar yo‘q", - "Аяқталған өтулер жоқ", - ], - [ - "The PGN file has no games", - "В PGN-файле нет партий", - "Le fichier PGN ne contient aucune partie", - "Die PGN-Datei enthält keine Partien", - "El archivo PGN no contiene partidas", - "Il file PGN non contiene partite", - "O arquivo PGN não contém partidas", - "PGN faylda partiyalar yo‘q", - "PGN файлда партиялар жоқ", - ], - [ - "The repertoire name must not be empty", - "Название репертуара не должно быть пустым", - "Le nom du répertoire ne doit pas être vide", - "Der Repertoirename darf nicht leer sein", - "El nombre del repertorio no debe estar vacío", - "Il nome del repertorio non può essere vuoto", - "O nome do repertório não pode estar vazio", - "Repertuar nomi bo‘sh bo‘lmasligi kerak", - "Репертуар аты бос болмауы керек", - ], - [ - "The repertoire name is longer than 120 characters", - "Название репертуара длиннее 120 символов", - "Le nom du répertoire dépasse 120 caractères", - "Der Repertoirename ist länger als 120 Zeichen", - "El nombre del repertorio supera los 120 caracteres", - "Il nome del repertorio supera i 120 caratteri", - "O nome do repertório excede 120 caracteres", - "Repertuar nomi 120 belgidan uzun", - "Репертуар аты 120 таңбадан ұзын", - ], - [ - "A repertoire with this name already exists", - "Репертуар с таким названием уже существует", - "Un répertoire portant ce nom existe déjà", - "Ein Repertoire mit diesem Namen existiert bereits", - "Ya existe un repertorio con este nombre", - "Esiste già un repertorio con questo nome", - "Já existe um repertório com este nome", - "Bu nomli repertuar allaqachon mavjud", - "Бұл аттағы репертуар бар", - ], - [ - "PGN exported: {path}", - "PGN экспортирован: {path}", - "PGN exporté : {path}", - "PGN exportiert: {path}", - "PGN exportado: {path}", - "PGN esportato: {path}", - "PGN exportado: {path}", - "PGN eksport qilindi: {path}", - "PGN экспортталды: {path}", - ], - [ - "Could not read statistics: {error}. The file was not replaced", - "Не удалось прочитать статистику: {error}. Файл не заменён", - "Impossible de lire les statistiques : {error}. Le fichier n’a pas été remplacé", - "Statistik konnte nicht gelesen werden: {error}. Die Datei wurde nicht ersetzt", - "No se pudieron leer las estadísticas: {error}. El archivo no fue reemplazado", - "Impossibile leggere le statistiche: {error}. Il file non è stato sostituito", - "Não foi possível ler as estatísticas: {error}. O arquivo não foi substituído", - "Statistikani o‘qib bo‘lmadi: {error}. Fayl almashtirilmadi", - "Статистиканы оқу мүмкін емес: {error}. Файл ауыстырылмады", - ], - [ - "Reading PGN · records: {n}", - "Чтение PGN · записей: {n}", - "Lecture du PGN · enregistrements : {n}", - "PGN wird gelesen · Einträge: {n}", - "Leyendo PGN · registros: {n}", - "Lettura PGN · record: {n}", - "Lendo PGN · registros: {n}", - "PGN o‘qilmoqda · yozuvlar: {n}", - "PGN оқылуда · жазбалар: {n}", - ], - [ - "Import: {path}", - "Импорт: {path}", - "Import : {path}", - "Import: {path}", - "Importar: {path}", - "Importa: {path}", - "Importar: {path}", - "Import: {path}", - "Импорт: {path}", - ], - [ - "Into one repertoire: {name}", - "В один репертуар: {name}", - "Dans un seul répertoire : {name}", - "In ein Repertoire: {name}", - "En un solo repertorio: {name}", - "In un solo repertorio: {name}", - "Para um único repertório: {name}", - "Bitta repertuarga: {name}", - "Бір репертуарға: {name}", - ], - [ - "PGN records: {games} · new moves: {added} · matching moves: {matched} · branches: {branches}", - "Записей PGN: {games} · новых ходов: {added} · совпадающих: {matched} · ветвей: {branches}", - "Enregistrements PGN : {games} · nouveaux coups : {added} · correspondants : {matched} · variantes : {branches}", - "PGN-Einträge: {games} · neue Züge: {added} · übereinstimmende Züge: {matched} · Varianten: {branches}", - "Registros PGN: {games} · jugadas nuevas: {added} · coincidentes: {matched} · variantes: {branches}", - "Record PGN: {games} · nuove mosse: {added} · corrispondenti: {matched} · varianti: {branches}", - "Registros PGN: {games} · novos lances: {added} · coincidentes: {matched} · variantes: {branches}", - "PGN yozuvlari: {games} · yangi yurishlar: {added} · mos: {matched} · variantlar: {branches}", - "PGN жазбалары: {games} · жаңа жүрістер: {added} · сәйкес: {matched} · нұсқалар: {branches}", - ], - [ - "Maximum depth: {depth} half-moves · targets at the current depth: {n}", - "Максимальная глубина: {depth} полуходов · целей при текущей глубине: {n}", - "Profondeur maximale : {depth} demi-coups · cibles à la profondeur actuelle : {n}", - "Maximale Tiefe: {depth} Halbzüge · Ziele bei aktueller Tiefe: {n}", - "Profundidad máxima: {depth} medias jugadas · objetivos a la profundidad actual: {n}", - "Profondità massima: {depth} mezze mosse · obiettivi alla profondità attuale: {n}", - "Profundidade máxima: {depth} meio-lances · objetivos na profundidade atual: {n}", - "Maksimal chuqurlik: {depth} yarim yurish · joriy chuqurlikdagi maqsadlar: {n}", - "Ең тереңдік: {depth} жарты жүріс · ағымдағы тереңдіктегі мақсаттар: {n}", - ], - [ - "Delete “{name}” and its new statistics?", - "Удалить «{name}» и всю его новую статистику?", - "Supprimer « {name} » et ses nouvelles statistiques ?", - "„{name}“ und die neue Statistik löschen?", - "¿Eliminar «{name}» y sus nuevas estadísticas?", - "Eliminare «{name}» e le sue nuove statistiche?", - "Excluir “{name}” e suas novas estatísticas?", - "“{name}” va uning yangi statistikasini o‘chirish kerakmi?", - "«{name}» және оның жаңа статистикасын жою керек пе?", - ], - [ - "Runs: {n}", - "Прохождений: {n}", - "Parcours : {n}", - "Durchgänge: {n}", - "Recorridos: {n}", - "Percorsi: {n}", - "Percursos: {n}", - "O‘tishlar: {n}", - "Өтулер: {n}", - ], - [ - "{line} — {n} half-moves", - "{line} — {n} полуходов", - "{line} — {n} demi-coups", - "{line} — {n} Halbzüge", - "{line} — {n} medias jugadas", - "{line} — {n} mezze mosse", - "{line} — {n} meio-lances", - "{line} — {n} yarim yurish", - "{line} — {n} жарты жүріс", - ], - [ - "← To game {title}", - "← К партии {title}", - "← Vers la partie {title}", - "← Zur Partie {title}", - "← A la partida {title}", - "← Alla partita {title}", - "← Para a partida {title}", - "← {title} partiyasiga", - "← {title} партиясына", - ], - [ - "Unfinished training: {progress}", - "Незавершённая тренировка: {progress}", - "Entraînement inachevé : {progress}", - "Nicht abgeschlossenes Training: {progress}", - "Entrenamiento sin terminar: {progress}", - "Allenamento non completato: {progress}", - "Treino não concluído: {progress}", - "Yakunlanmagan mashg‘ulot: {progress}", - "Аяқталмаған жаттығу: {progress}", - ], - [ - "In scope: {targets} · due: {due} · unseen: {unseen}", - "В области: {targets} · к повторению: {due} · новых: {unseen}", - "Dans la zone : {targets} · à réviser : {due} · nouveaux : {unseen}", - "Im Bereich: {targets} · fällig: {due} · neu: {unseen}", - "En el ámbito: {targets} · por repasar: {due} · nuevos: {unseen}", - "Nell’ambito: {targets} · da ripassare: {due} · nuovi: {unseen}", - "No âmbito: {targets} · por revisar: {due} · novos: {unseen}", - "Hududda: {targets} · takrorlash: {due} · yangi: {unseen}", - "Аймақта: {targets} · қайталау: {due} · жаңа: {unseen}", - ], - [ - "Start: {n} due", - "Начать: {n} к повторению", - "Commencer : {n} à réviser", - "Start: {n} fällig", - "Empezar: {n} por repasar", - "Inizia: {n} da ripassare", - "Começar: {n} por revisar", - "Boshlash: {n} takrorlash", - "Бастау: {n} қайталау", - ], - [ - "Start: {n} new", - "Начать: {n} новых", - "Commencer : {n} nouveaux", - "Start: {n} neue", - "Empezar: {n} nuevas", - "Inizia: {n} nuove", - "Começar: {n} novos", - "Boshlash: {n} yangi", - "Бастау: {n} жаңа", - ], - [ - " ⇄ {n} paths", - " ⇄ {n} путей", - " ⇄ {n} chemins", - " ⇄ {n} Pfade", - " ⇄ {n} rutas", - " ⇄ {n} percorsi", - " ⇄ {n} caminhos", - " ⇄ {n} yo‘llar", - " ⇄ {n} жолдар", - ], - [ - "Attempts: {attempts} · correct: {correct} · wrong: {wrong} · hints: {hints}", - "Попыток: {attempts} · верных: {correct} · неверных: {wrong} · подсказок: {hints}", - "Tentatives : {attempts} · correctes : {correct} · incorrectes : {wrong} · indices : {hints}", - "Versuche: {attempts} · richtig: {correct} · falsch: {wrong} · Hinweise: {hints}", - "Intentos: {attempts} · correctas: {correct} · incorrectas: {wrong} · pistas: {hints}", - "Tentativi: {attempts} · corrette: {correct} · sbagliate: {wrong} · suggerimenti: {hints}", - "Tentativas: {attempts} · corretos: {correct} · incorretos: {wrong} · dicas: {hints}", - "Urinishlar: {attempts} · to‘g‘ri: {correct} · noto‘g‘ri: {wrong} · maslahatlar: {hints}", - "Әрекеттер: {attempts} · дұрыс: {correct} · қате: {wrong} · кеңестер: {hints}", - ], - [ - "Clean streak: {streak} · last seen: {last} · next due: {due}", - "Чистая серия: {streak} · последний показ: {last} · следующий срок: {due}", - "Série sans erreur : {streak} · vu pour la dernière fois : {last} · prochaine révision : {due}", - "Fehlerfreie Serie: {streak} · zuletzt gesehen: {last} · nächster Termin: {due}", - "Racha sin errores: {streak} · última vez: {last} · próximo repaso: {due}", - "Serie senza errori: {streak} · ultima visualizzazione: {last} · prossimo ripasso: {due}", - "Sequência sem erros: {streak} · última visualização: {last} · próxima revisão: {due}", - "Xatosiz seriya: {streak} · oxirgi ko‘rish: {last} · keyingi takrorlash: {due}", - "Қатесіз серия: {streak} · соңғы көрсету: {last} · келесі қайталау: {due}", - ], - [ - "Enabled: {targets} · seen: {seen} · due: {due} · unseen: {unseen} · unscheduled: {unscheduled}", - "Включено: {targets} · показано: {seen} · к повторению: {due} · новых: {unseen} · вне расписания: {unscheduled}", - "Actifs : {targets} · vus : {seen} · à réviser : {due} · nouveaux : {unseen} · non planifiés : {unscheduled}", - "Aktiv: {targets} · gesehen: {seen} · fällig: {due} · neu: {unseen} · nicht eingeplant: {unscheduled}", - "Activas: {targets} · vistas: {seen} · por repasar: {due} · nuevas: {unseen} · sin programar: {unscheduled}", - "Attive: {targets} · viste: {seen} · da ripassare: {due} · nuove: {unseen} · non pianificate: {unscheduled}", - "Ativos: {targets} · vistos: {seen} · por revisar: {due} · novos: {unseen} · não agendados: {unscheduled}", - "Faol: {targets} · ko‘rilgan: {seen} · takrorlash: {due} · yangi: {unseen} · rejasiz: {unscheduled}", - "Белсенді: {targets} · көрсетілген: {seen} · қайталау: {due} · жаңа: {unseen} · жоспарсыз: {unscheduled}", - ], - [ - "{date} · half-moves: {plies} · mistakes: {mistakes} · hints: {hints}", - "{date} · полуходов: {plies} · ошибок: {mistakes} · подсказок: {hints}", - "{date} · demi-coups : {plies} · erreurs : {mistakes} · indices : {hints}", - "{date} · Halbzüge: {plies} · Fehler: {mistakes} · Hinweise: {hints}", - "{date} · medias jugadas: {plies} · errores: {mistakes} · pistas: {hints}", - "{date} · mezze mosse: {plies} · errori: {mistakes} · suggerimenti: {hints}", - "{date} · meio-lances: {plies} · erros: {mistakes} · dicas: {hints}", - "{date} · yarim yurishlar: {plies} · xatolar: {mistakes} · maslahatlar: {hints}", - "{date} · жарты жүрістер: {plies} · қателер: {mistakes} · кеңестер: {hints}", - ], - [ - "Could not read PGN record {n}", - "Не удалось прочитать запись PGN {n}", - "Impossible de lire l’enregistrement PGN {n}", - "PGN-Eintrag {n} konnte nicht gelesen werden", - "No se pudo leer el registro PGN {n}", - "Impossibile leggere il record PGN {n}", - "Não foi possível ler o registro PGN {n}", - "PGN {n} yozuvini o‘qib bo‘lmadi", - "PGN {n} жазбасын оқу мүмкін емес", - ], - [ - "PGN record {n} was rejected: {errors}", - "Запись PGN {n} отклонена: {errors}", - "L’enregistrement PGN {n} a été rejeté : {errors}", - "PGN-Eintrag {n} wurde abgelehnt: {errors}", - "El registro PGN {n} fue rechazado: {errors}", - "Il record PGN {n} è stato rifiutato: {errors}", - "O registro PGN {n} foi rejeitado: {errors}", - "PGN {n} yozuvi rad etildi: {errors}", - "PGN {n} жазбасы қабылданбады: {errors}", - ], - [ - "Record {n}: {message}", - "Запись {n}: {message}", - "Enregistrement {n} : {message}", - "Eintrag {n}: {message}", - "Registro {n}: {message}", - "Record {n}: {message}", - "Registro {n}: {message}", - "{n}-yozuv: {message}", - "{n}-жазба: {message}", - ], - [ - "PGN record {n}: {error}", - "Запись PGN {n}: {error}", - "Enregistrement PGN {n} : {error}", - "PGN-Eintrag {n}: {error}", - "Registro PGN {n}: {error}", - "Record PGN {n}: {error}", - "Registro PGN {n}: {error}", - "PGN {n}-yozuv: {error}", - "PGN {n}-жазба: {error}", - ], - [ - "× This move is outside the enabled variations", - "× Этот ход вне включённых вариантов", - "× Ce coup est en dehors des variantes actives", - "× Dieser Zug liegt außerhalb der aktiven Varianten", - "× Esta jugada está fuera de las variantes activas", - "× Questa mossa è fuori dalle varianti attive", - "× Este lance está fora das variantes ativas", - "× Bu yurish faol variantlardan tashqarida", - "× Бұл жүріс белсенді нұсқалардан тыс", - ], - [ - "× Another move is expected here", - "× Сейчас в репертуаре ожидается другой ход", - "× Un autre coup est attendu ici", - "× Hier ist ein anderer Zug aus dem Repertoire erwartet", - "× Aquí se espera otra jugada", - "× Qui è prevista un’altra mossa", - "× Outro lance é esperado aqui", - "× Bu yerda boshqa yurish kutilmoqda", - "× Мұнда басқа жүріс күтілуде", - ], - [ - "This move is in the repertoire, but another one is being reviewed now · Try again", - "Этот ход есть в репертуаре, но сейчас повторяется другой · Попробуйте ещё раз", - "Ce coup est dans le répertoire, mais un autre est en cours de révision · Réessayez", - "Dieser Zug ist im Repertoire, aber gerade wird ein anderer wiederholt · Noch einmal versuchen", - "Esta jugada está en el repertorio, pero ahora se repasa otra · Inténtalo de nuevo", - "Questa mossa è nel repertorio, ma ora se ne sta ripassando un’altra · Riprova", - "Este lance está no repertório, mas outro está sendo revisto agora · Tente novamente", - "Bu yurish repertuarda bor, lekin hozir boshqasi takrorlanmoqda · Qayta urining", - "Бұл жүріс репертуарда бар, бірақ қазір басқасы қайталануда · Қайта байқап көріңіз", - ], - [ - "Until the depth limit or the end of the branch", - "До глубины или конца ветки", - "Jusqu’à la profondeur limite ou la fin de la variante", - "Bis zur Tiefengrenze oder zum Ende der Variante", - "Hasta el límite de profundidad o el final de la variante", - "Fino al limite di profondità o alla fine della variante", - "Até ao limite de profundidade ou ao fim da variante", - "Chuqurlik chegarasigacha yoki variant oxirigacha", - "Тереңдік шегіне дейін немесе нұсқа аяғына дейін", - ], - [ - "New run", - "Новый проход", - "Nouveau parcours", - "Neuer Durchgang", - "Nuevo recorrido", - "Nuovo percorso", - "Novo percurso", - "Yangi o‘tish", - "Жаңа өту", - ], - [ - "Half-moves played: {n}", - "Сыграно полуходов: {n}", - "Demi-coups joués : {n}", - "Gespielte Halbzüge: {n}", - "Medias jugadas: {n}", - "Mezze mosse giocate: {n}", - "Meio-lances jogados: {n}", - "O‘ynalgan yarim yurishlar: {n}", - "Ойналған жарты жүрістер: {n}", - ], - [ - "Half-move {n}", - "Полуход {n}", - "Demi-coup {n}", - "Halbzug {n}", - "Media jugada {n}", - "Mezza mossa {n}", - "Meio-lance {n}", - "{n}-yarim yurish", - "{n}-жарты жүріс", - ], - [ - "Half-moves played: {n} · mistakes: {m}", - "Пройдено полуходов: {n} · ошибок: {m}", - "Demi-coups joués : {n} · erreurs : {m}", - "Gespielte Halbzüge: {n} · Fehler: {m}", - "Medias jugadas: {n} · errores: {m}", - "Mezze mosse giocate: {n} · errori: {m}", - "Meio-lances jogados: {n} · erros: {m}", - "O‘ynalgan yarim yurishlar: {n} · xatolar: {m}", - "Ойналған жарты жүрістер: {n} · қателер: {m}", - ], - [ - "Enabled half-moves: {targets} · completed runs: {runs}", - "Включено полуходов: {targets} · завершено проходов: {runs}", - "Demi-coups actifs : {targets} · parcours terminés : {runs}", - "Aktive Halbzüge: {targets} · abgeschlossene Durchgänge: {runs}", - "Medias jugadas activas: {targets} · recorridos completados: {runs}", - "Mezze mosse attive: {targets} · percorsi completati: {runs}", - "Meio-lances ativos: {targets} · percursos concluídos: {runs}", - "Faol yarim yurishlar: {targets} · yakunlangan o‘tishlar: {runs}", - "Белсенді жарты жүрістер: {targets} · аяқталған өтулер: {runs}", - ], - [ - "No due or unseen targets; choose a review queue", - "Нет целей к повторению или новых; выберите обзорную очередь", - "Aucune cible à réviser ou nouvelle ; choisissez une file de révision", - "Keine fälligen oder neuen Ziele; wählen Sie eine Wiederholungswarteschlange", - "No hay objetivos por repasar ni nuevos; elige una cola de repaso", - "Nessun obiettivo da ripassare o nuovo; scegli una coda di ripasso", - "Não há objetivos por revisar ou novos; escolha uma fila de revisão", - "Takrorlanadigan yoki yangi maqsad yo‘q; takrorlash navbatini tanlang", - "Қайталанатын немесе жаңа мақсат жоқ; қайталау кезегін таңдаңыз", - ], - [ - "Last played", - "Последний раз сыгран", - "Dernière fois joué", - "Zuletzt gespielt", - "Última vez jugado", - "Ultima mossa giocata", - "Última vez jogado", - "Oxirgi o‘ynalgan", - "Соңғы ойналған", - ], - [ - "Last played: {last}", - "Последний раз сыгран: {last}", - "Dernière fois joué : {last}", - "Zuletzt gespielt: {last}", - "Última vez jugado: {last}", - "Ultima mossa giocata: {last}", - "Última vez jogado: {last}", - "Oxirgi o‘ynalgan: {last}", - "Соңғы ойналған: {last}", - ], - [ - "Enabled half-moves: {targets} · played: {seen} · completed runs: {runs}", - "Включено полуходов: {targets} · сыграно: {seen} · завершено проходов: {runs}", - "Demi-coups actifs : {targets} · joués : {seen} · parcours terminés : {runs}", - "Aktive Halbzüge: {targets} · gespielt: {seen} · abgeschlossene Durchgänge: {runs}", - "Medias jugadas activas: {targets} · jugadas: {seen} · recorridos completados: {runs}", - "Mezze mosse attive: {targets} · giocate: {seen} · percorsi completati: {runs}", - "Meio-lances ativos: {targets} · jogados: {seen} · percursos concluídos: {runs}", - "Faol yarim yurishlar: {targets} · o‘ynalgan: {seen} · yakunlangan o‘tishlar: {runs}", - "Белсенді жарты жүрістер: {targets} · ойналған: {seen} · аяқталған өтулер: {runs}", - ], - [ - "Spaced schedule", - "По расписанию", - "Répétition espacée", - "Nach Zeitplan", - "Repetición espaciada", - "Ripetizione spaziata", - "Repetição espaçada", - "Oraliq jadval", - "Аралық кесте", - ], - [ - "Unscheduled", - "Вне расписания", - "Non planifié", - "Nicht eingeplant", - "Sin programar", - "Non pianificato", - "Não agendado", - "Rejasiz", - "Жоспарсыз", - ], - [ - "Scope", - "Область", - "Zone", - "Bereich", - "Ámbito", - "Ambito", - "Âmbito", - "Hudud", - "Аймақ", - ], - [ - "Reset scope", - "Сбросить область", - "Réinitialiser la zone", - "Bereich zurücksetzen", - "Restablecer ámbito", - "Reimposta ambito", - "Redefinir âmbito", - "Hududni tiklash", - "Аймақты қалпына келтіру", - ], - [ - "Use selected as scope", - "Сделать выбранное областью", - "Utiliser la sélection comme zone", - "Auswahl als Bereich verwenden", - "Usar selección como ámbito", - "Usa selezione come ambito", - "Usar seleção como âmbito", - "Tanlanganini hudud qilish", - "Таңдалғанды аймақ ету", - ], - [ - "End scope here", - "Завершить область здесь", - "Terminer la zone ici", - "Bereich hier beenden", - "Terminar ámbito aquí", - "Termina ambito qui", - "Terminar âmbito aqui", - "Hududni shu yerda tugatish", - "Аймақты осы жерде аяқтау", - ], - [ - "Replay automatic context", - "Показывать автоматический контекст", - "Rejouer le contexte automatique", - "Automatischen Kontext abspielen", - "Reproducir contexto automático", - "Riproduci contesto automatico", - "Reproduzir contexto automático", - "Avtomatik kontekstni ko‘rsatish", - "Автоматты контекстті көрсету", - ], - [ - "Paths completed: {completed} of {total}", - "Завершено путей: {completed} из {total}", - "Chemins terminés : {completed} sur {total}", - "Abgeschlossene Pfade: {completed} von {total}", - "Rutas completadas: {completed} de {total}", - "Percorsi completati: {completed} di {total}", - "Caminhos concluídos: {completed} de {total}", - "Yakunlangan yo‘llar: {completed} / {total}", - "Аяқталған жолдар: {completed} / {total}", - ], - [ - "Start review: {n}", - "Начать обзор: {n}", - "Commencer la révision : {n}", - "Wiederholung starten: {n}", - "Empezar repaso: {n}", - "Inizia ripasso: {n}", - "Começar revisão: {n}", - "Takrorlashni boshlash: {n}", - "Қайталауды бастау: {n}", - ], - [ - " [scope end]", - " [конец области]", - " [fin de zone]", - " [Bereichsende]", - " [fin del ámbito]", - " [fine ambito]", - " [fim do âmbito]", - " [hudud oxiri]", - " [аймақ аяғы]", - ], - [ - "Whole repertoire", - "Весь репертуар", - "Tout le répertoire", - "Gesamtes Repertoire", - "Todo el repertorio", - "Tutto il repertorio", - "Todo o repertório", - "Butun repertuar", - "Бүкіл репертуар", - ], - [ - "From {path}", - "От {path}", - "À partir de {path}", - "Ab {path}", - "Desde {path}", - "Da {path}", - "A partir de {path}", - "{path}dan", - "{path}тан", - ], - [ - " · end {path}", - " · конец {path}", - " · fin {path}", - " · Ende {path}", - " · fin {path}", - " · fine {path}", - " · fim {path}", - " · oxir {path}", - " · аяқ {path}", - ], - [ - "· 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", - "Досрочный обзор · сроки не меняются", - "Révision anticipée · calendrier inchangé", - "Vorzeitige Wiederholung · Zeitplan unverändert", - "Repaso anticipado · calendario sin cambios", - "Ripasso anticipato · calendario invariato", - "Revisão antecipada · calendário inalterado", - "Erta takrorlash · jadval o‘zgarmaydi", - "Ерте қайталау · кесте өзгермейді", - ], - [ - "Due now: {n}", - "К повторению сейчас: {n}", - "À réviser maintenant : {n}", - "Jetzt fällig: {n}", - "Por repasar ahora: {n}", - "Da ripassare ora: {n}", - "Por revisar agora: {n}", - "Hozir takrorlash: {n}", - "Қазір қайталау: {n}", - ], - [ - "Introduce new: {batch} of {remaining}", - "Добавить новые: {batch} из {remaining}", - "Introduire de nouveaux : {batch} sur {remaining}", - "Neue hinzufügen: {batch} von {remaining}", - "Introducir nuevas: {batch} de {remaining}", - "Introduci nuove: {batch} di {remaining}", - "Introduzir novos: {batch} de {remaining}", - "Yangilarini qo‘shish: {batch} / {remaining}", - "Жаңаларын қосу: {batch} / {remaining}", - ], - [ - "Review future moves early", - "Повторить будущие раньше", - "Réviser les coups futurs plus tôt", - "Künftige Züge früher wiederholen", - "Repasar jugadas futuras antes", - "Ripassa prima le mosse future", - "Revisar lances futuros mais cedo", - "Kelajakdagi yurishlarni erta takrorlash", - "Болашақ жүрістерді ерте қайталау", - ], - [ - "Review due moves", - "Повторить текущие", - "Réviser les coups à réviser", - "Fällige Züge wiederholen", - "Repasar jugadas pendientes", - "Ripassa mosse da ripassare", - "Revisar lances por revisar", - "Takrorlanadigan yurishlarni takrorlash", - "Қайталанатын жүрістерді қайталау", - ], - [ - "Paths", - "Пути", - "Chemins", - "Pfade", - "Rutas", - "Percorsi", - "Caminhos", - "Yo‘llar", - "Жолдар", - ], - [ - "Path", "Путь", "Chemin", "Pfad", "Ruta", "Percorso", "Caminho", "Yo‘l", "Жол", - ], - [ - "Completions", - "Завершения", - "Achèvements", - "Abschlüsse", - "Finalizaciones", - "Completamenti", - "Conclusões", - "Yakunlashlar", - "Аяқтаулар", - ], - [ - "Last completion", - "Последнее завершение", - "Dernier achèvement", - "Letzter Abschluss", - "Última finalización", - "Ultimo completamento", - "Última conclusão", - "Oxirgi yakunlash", - "Соңғы аяқтау", - ], - [ - "No paths", - "Нет путей", - "Aucun chemin", - "Keine Pfade", - "No hay rutas", - "Nessun percorso", - "Não há caminhos", - "Yo‘llar yo‘q", - "Жолдар жоқ", - ], - [ - "{n} new paths", - "Новых путей: {n}", - "{n} nouveaux chemins", - "Neue Pfade: {n}", - "{n} rutas nuevas", - "{n} nuovi percorsi", - "{n} novos caminhos", - "{n} yangi yo‘l", - "{n} жаңа жол", - ], - [ - "In order", - "По порядку", - "Dans l’ordre", - "Der Reihe nach", - "En orden", - "In ordine", - "Em ordem", - "Tartib bilan", - "Ретімен", - ], - [ - "With review", - "С повторениями", - "Avec révision", - "Mit Wiederholung", - "Con repaso", - "Con ripasso", - "Com revisão", - "Takrorlash bilan", - "Қайталаумен", - ], - [ - "No moves for this color in the PGN file", - "В PGN-файле нет ходов для этого цвета", - "Aucun coup pour cette couleur dans le fichier PGN", - "Keine Züge für diese Farbe in der PGN-Datei", - "No hay jugadas para este color en el archivo PGN", - "Nessuna mossa per questo colore nel file PGN", - "Não há lances para esta cor no arquivo PGN", - "PGN faylda bu rang uchun yurishlar yo‘q", - "PGN файлда бұл түс үшін жүрістер жоқ", - ], - [ - "Add PGN…", - "Добавить PGN…", - "Ajouter un PGN…", - "PGN hinzufügen…", - "Añadir PGN…", - "Aggiungi PGN…", - "Adicionar PGN…", - "PGN qo‘shish…", - "PGN қосу…", - ], - [ - "Create new PGN…", - "Создать новый PGN…", - "Créer un nouveau PGN…", - "Neue PGN erstellen…", - "Crear un PGN nuevo…", - "Crea un nuovo PGN…", - "Criar novo PGN…", - "Yangi PGN yaratish…", - "Жаңа PGN жасау…", - ], - [ - "Save as PGN and link…", - "Сохранить как PGN и привязать…", - "Enregistrer en PGN et lier…", - "Als PGN speichern und verknüpfen…", - "Guardar como PGN y vincular…", - "Salva come PGN e collega…", - "Guardar como PGN e vincular…", - "PGN saqlash va bog‘lash…", - "PGN сақтау және байланыстыру…", - ], - [ - "New PGN…", - "Новый PGN…", - "Nouveau PGN…", - "Neue PGN…", - "Nuevo PGN…", - "Nuovo PGN…", - "Novo PGN…", - "Yangi PGN…", - "Жаңа PGN…", - ], - [ - "Other PGN…", - "Другой PGN…", - "Autre PGN…", - "Andere PGN…", - "Otro PGN…", - "Altro PGN…", - "Outro PGN…", - "Boshqa PGN…", - "Басқа PGN…", - ], - [ - "Choose a PGN file", - "Выберите PGN-файл", - "Choisissez un fichier PGN", - "PGN-Datei auswählen", - "Elige un archivo PGN", - "Scegli un file PGN", - "Escolha um arquivo PGN", - "PGN faylni tanlang", - "PGN файлды таңдаңыз", - ], - [ - "Start training", - "Начать", - "Commencer l’entraînement", - "Training starten", - "Empezar entrenamiento", - "Inizia allenamento", - "Iniciar treino", - "Mashg‘ulotni boshlash", - "Жаттығуды бастау", - ], - [ - "The PGN file itself is not deleted", - "Сам PGN-файл не удаляется", - "Le fichier PGN lui-même n’est pas supprimé", - "Die PGN-Datei selbst wird nicht gelöscht", - "El archivo PGN no se elimina", - "Il file PGN non viene eliminato", - "O arquivo PGN em si não é excluído", - "PGN faylning o‘zi o‘chirilmaydi", - "PGN файлдың өзі өшірілмейді", - ], - [ - "No PGN files yet. Add an existing file or create a new one.", - "PGN-файлов пока нет. Добавьте существующий файл или создайте новый.", - "Aucun fichier PGN pour le moment. Ajoutez un fichier existant ou créez-en un nouveau.", - "Noch keine PGN-Dateien. Fügen Sie eine vorhandene Datei hinzu oder erstellen Sie eine neue.", - "Aún no hay archivos PGN. Añade uno existente o crea uno nuevo.", - "Ancora nessun file PGN. Aggiungi un file esistente o creane uno nuovo.", - "Ainda não há arquivos PGN. Adicione um existente ou crie um novo.", - "Hozircha PGN fayllar yo‘q. Mavjud faylni qo‘shing yoki yangisini yarating.", - "Әзірге PGN файлдар жоқ. Бар файлды қосыңыз немесе жаңасын жасаңыз.", - ], - [ - "Legacy records without PGN", - "Старые записи без PGN", - "Anciens enregistrements sans PGN", - "Alte Einträge ohne PGN", - "Registros antiguos sin PGN", - "Vecchi record senza PGN", - "Registros antigos sem PGN", - "PGN-siz eski yozuvlar", - "PGN-сіз ескі жазбалар", - ], - [ - "Choose a PGN file, then choose a color and start.", - "Выберите PGN-файл, затем цвет и начните тренировку.", - "Choisissez un fichier PGN, puis une couleur, et commencez.", - "Wählen Sie eine PGN-Datei, dann eine Farbe, und starten Sie.", - "Elige un archivo PGN, después un color y empieza.", - "Scegli un file PGN, poi un colore e inizia.", - "Escolha um arquivo PGN, depois uma cor e comece.", - "PGN faylni, so‘ng rangni tanlab boshlang.", - "PGN файлды, содан соң түсті таңдап бастаңыз.", - ], - [ - "The file could not be read; its cached copy will not be used", - "Файл не удалось прочитать; старый снимок не будет использован", - "Le fichier n’a pas pu être lu ; sa copie en cache ne sera pas utilisée", - "Die Datei konnte nicht gelesen werden; ihre zwischengespeicherte Kopie wird nicht verwendet", - "No se pudo leer el archivo; no se usará su copia en caché", - "Impossibile leggere il file; la copia nella cache non verrà usata", - "Não foi possível ler o arquivo; sua cópia em cache não será usada", - "Faylni o‘qib bo‘lmadi; keshdagi nusxasi ishlatilmaydi", - "Файлды оқу мүмкін емес; кэштегі нұсқасы қолданылмайды", - ], - [ - "Color", "Цвет", "Couleur", "Farbe", "Color", "Colore", "Cor", "Rang", "Түс", - ], - [ - "Both: you play every move; only moves from this PGN are accepted", - "Обе стороны: все ходы делаете вы; принимаются только ходы из этого PGN", - "Les deux : vous jouez chaque coup ; seuls les coups de ce PGN sont acceptés", - "Beide: Sie spielen jeden Zug; nur Züge aus dieser PGN werden akzeptiert", - "Ambos: juegas cada jugada; solo se aceptan jugadas de este PGN", - "Entrambi: giochi ogni mossa; sono accettate solo mosse di questo PGN", - "Ambos: você joga cada lance; apenas lances deste PGN são aceitos", - "Ikkala rang: har yurishni o‘zingiz qilasiz; faqat shu PGN dagi yurishlar qabul qilinadi", - "Екі түс: әр жүрісті өзіңіз жасайсыз; тек осы PGN дегі жүрістер қабылданады", - ], - [ - "White/Black: you play your color; the program answers from this PGN", - "Белые/чёрные: вы играете своим цветом, программа отвечает ходами из этого PGN", - "Blancs/Noirs : vous jouez votre couleur ; le programme répond avec ce PGN", - "Weiß/Schwarz: Sie spielen Ihre Farbe; das Programm antwortet aus dieser PGN", - "Blancas/Negras: juegas tu color; el programa responde con este PGN", - "Bianco/Nero: giochi il tuo colore; il programma risponde con questo PGN", - "Brancas/Pretas: você joga sua cor; o programa responde com este PGN", - "Oq/Qora: o‘z rangingiz bilan yurasiz; dastur shu PGN dan javob beradi", - "Ақ/Қара: өз түсіңізбен жүріссіз; бағдарлама осы PGN нан жауап береді", - ], - [ - "No training yet", - "Тренировок ещё не было", - "Aucun entraînement pour le moment", - "Noch kein Training", - "Aún sin entrenamiento", - "Ancora nessun allenamento", - "Ainda sem treino", - "Hozircha mashg‘ulot bo‘lmadi", - "Әзірге жаттығу болмады", - ], - [ - "Target PGN", - "Целевой PGN", - "PGN cible", - "Ziel-PGN", - "PGN de destino", - "PGN di destinazione", - "PGN de destino", - "Maqsad PGN", - "Мақсат PGN", - ], - [ - "The new file will be created only after Add", - "Новый файл будет создан только после нажатия «Добавить»", - "Le nouveau fichier sera créé seulement après « Ajouter »", - "Die neue Datei wird erst nach „Hinzufügen“ erstellt", - "El nuevo archivo se creará solo después de «Añadir»", - "Il nuovo file sarà creato solo dopo «Aggiungi»", - "O novo arquivo será criado somente após «Adicionar»", - "Yangi fayl faqat «Qo‘shish»dan so‘ng yaratiladi", - "Жаңа файл тек «Қосу»дан кейін жасалады", - ], - [ - "This exact PGN file will be changed. The source game and its database will not change.", - "Будет изменён именно этот PGN-файл. Исходная партия и её база не изменятся.", - "Ce fichier PGN précis sera modifié. La partie source et sa base ne changeront pas.", - "Genau diese PGN-Datei wird geändert. Die Ausgangspartie und ihre Datenbank bleiben unverändert.", - "Se modificará exactamente este archivo PGN. La partida original y su base no cambiarán.", - "Sarà modificato proprio questo file PGN. La partita di origine e il suo database non cambieranno.", - "Exatamente este arquivo PGN será alterado. A partida de origem e sua base não serão alteradas.", - "Aynan shu PGN fayl o‘zgaradi. Manba partiya va uning bazasi o‘zgarmaydi.", - "Дәл осы PGN файл өзгереді. Бастапқы партия және оның базасы өзгермейді.", - ], - [ - "Attempts: {attempts} · Mistakes: {mistakes} · Clean streak: {streak} · Last: {last}", - "Попытки: {attempts} · ошибки: {mistakes} · чистая серия: {streak} · последняя: {last}", - "Tentatives : {attempts} · erreurs : {mistakes} · série sans erreur : {streak} · dernière : {last}", - "Versuche: {attempts} · Fehler: {mistakes} · fehlerfreie Serie: {streak} · zuletzt: {last}", - "Intentos: {attempts} · errores: {mistakes} · racha sin errores: {streak} · última: {last}", - "Tentativi: {attempts} · errori: {mistakes} · serie senza errori: {streak} · ultima: {last}", - "Tentativas: {attempts} · erros: {mistakes} · sequência sem erros: {streak} · última: {last}", - "Urinishlar: {attempts} · xatolar: {mistakes} · xatosiz seriya: {streak} · so‘nggi: {last}", - "Әрекеттер: {attempts} · қателер: {mistakes} · қатесіз серия: {streak} · соңғысы: {last}", - ], - [ - "New moves: {added} · annotation additions: {annotations}", - "Новых ходов: {added} · добавлено аннотаций: {annotations}", - "Nouveaux coups : {added} · annotations ajoutées : {annotations}", - "Neue Züge: {added} · hinzugefügte Anmerkungen: {annotations}", - "Jugadas nuevas: {added} · anotaciones añadidas: {annotations}", - "Nuove mosse: {added} · annotazioni aggiunte: {annotations}", - "Novos lances: {added} · anotações adicionadas: {annotations}", - "Yangi yurishlar: {added} · qo‘shilgan izohlar: {annotations}", - "Жаңа жүрістер: {added} · қосылған түсініктемелер: {annotations}", - ], - [ - "Play every move from this PGN", - "Сыграйте каждый ход из этого PGN", - "Jouez chaque coup de ce PGN", - "Spielen Sie jeden Zug aus dieser PGN", - "Juega cada jugada de este PGN", - "Gioca ogni mossa di questo PGN", - "Jogue cada lance deste PGN", - "Shu PGN dagi har yurishni o‘ynang", - "Осы PGN дегі әр жүрісті орындаңыз", - ], - [ - "The program answers from this PGN", - "Программа отвечает ходами из этого PGN", - "Le programme répond avec ce PGN", - "Das Programm antwortet aus dieser PGN", - "El programa responde con este PGN", - "Il programma risponde con questo PGN", - "O programa responde com este PGN", - "Dastur shu PGN dan javob beradi", - "Бағдарлама осы PGN нан жауап береді", - ], - [ - "Back to files", - "К файлам", - "Retour aux fichiers", - "Zurück zu Dateien", - "Volver a archivos", - "Torna ai file", - "Voltar aos arquivos", - "Fayllarga qaytish", - "Файлдарға қайту", - ], - [ - "← Back to files", - "← К файлам", - "← Retour aux fichiers", - "← Zurück zu Dateien", - "← Volver a archivos", - "← Torna ai file", - "← Voltar aos arquivos", - "← Fayllarga qaytish", - "← Файлдарға қайту", - ], - [ - "The library changed; import the PGN again", - "Библиотека изменилась; импортируйте PGN заново", - "La bibliothèque a changé ; importez à nouveau le PGN", - "Die Bibliothek wurde geändert; importieren Sie die PGN erneut", - "La biblioteca ha cambiado; importe el PGN de nuevo", - "La raccolta è cambiata; importa nuovamente il PGN", - "A biblioteca mudou; importe o PGN novamente", - "Kutubxona o‘zgardi; PGN faylni qayta import qiling", - "Кітапхана өзгерді; PGN файлын қайта импорттаңыз", - ], - [ - "Enable the parent branch first", - "Сначала включите родительскую ветку", - "Activez d’abord la variante parente", - "Aktivieren Sie zuerst die übergeordnete Variante", - "Active primero la variante superior", - "Attiva prima la variante principale", - "Ative primeiro a variante superior", - "Avval yuqori variantni yoqing", - "Алдымен жоғарғы нұсқаны қосыңыз", - ], - [ - "No games", - "Нет партий", - "Aucune partie", - "Keine Partien", - "No hay partidas", - "Nessuna partita", - "Nenhuma partida", - "Partiyalar yo‘q", - "Партиялар жоқ", - ], - [ - "Delete repertoire and its statistics? Source PGN files will not change.", - "Удалить репертуар и его статистику? Исходные PGN-файлы не изменятся.", - "Supprimer le répertoire et ses statistiques ? Les fichiers PGN sources ne seront pas modifiés.", - "Repertoire und seine Statistik löschen? PGN-Quelldateien bleiben unverändert.", - "¿Eliminar el repertorio y sus estadísticas? Los archivos PGN originales no cambiarán.", - "Eliminare il repertorio e le sue statistiche? I file PGN originali non cambieranno.", - "Excluir o repertório e suas estatísticas? Os arquivos PGN originais não serão alterados.", - "Repertuar va uning statistikasini o‘chirasizmi? Asl PGN fayllar o‘zgarmaydi.", - "Репертуар мен оның статистикасын жою керек пе? Бастапқы PGN файлдары өзгермейді.", - ], - [ - "Save", - "Сохранить", - "Enregistrer", - "Speichern", - "Guardar", - "Salva", - "Salvar", - "Saqlash", - "Сақтау", - ], - [ - "Introduce new moves", - "Добавить новые ходы", - "Introduire de nouveaux coups", - "Neue Züge einführen", - "Introducir nuevas jugadas", - "Introduci nuove mosse", - "Introduzir novos lances", - "Yangi yurishlarni qo‘shish", - "Жаңа жүрістерді қосу", - ], - [ - "Move statistics", - "Статистика хода", - "Statistiques du coup", - "Zugstatistik", - "Estadísticas de la jugada", - "Statistiche della mossa", - "Estatísticas do lance", - "Yurish statistikasi", - "Жүріс статистикасы", - ], - [ - "Next review", - "Следующее повторение", - "Prochaine révision", - "Nächste Wiederholung", - "Próximo repaso", - "Prossimo ripasso", - "Próxima revisão", - "Keyingi takrorlash", - "Келесі қайталау", - ], - [ - "Last attempt", - "Последняя попытка", - "Dernier essai", - "Letzter Versuch", - "Último intento", - "Ultimo tentativo", - "Última tentativa", - "Oxirgi urinish", - "Соңғы әрекет", - ], - [ - "Branch statistics", - "Статистика веток", - "Statistiques des variantes", - "Variantenstatistik", - "Estadísticas de variantes", - "Statistiche delle varianti", - "Estatísticas das variantes", - "Variantlar statistikasi", - "Нұсқалар статистикасы", - ], - [ - "Play through variations", - "Пройти варианты", - "Play through variations", - "Varianten durchspielen", - "Play through variations", - "Play through variations", - "Play through variations", - "Play through variations", - "Play through variations", - ], - [ - "Review individual moves", - "Повторять отдельные позиции", - "Review individual moves", - "Einzelne Stellungen wiederholen", - "Review individual moves", - "Review individual moves", - "Review individual moves", - "Review individual moves", - "Review individual moves", - ], - [ - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - "Пройдите ветку от начала до конца. Любой включённый ход принимается; за соперника отвечает программа.", - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - "Spielen Sie eine Variante bis zum Ende. Jeder aktivierte Zug wird akzeptiert; das Programm spielt die Gegenseite.", - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - "Play a variation from start to finish. Any enabled move is accepted; the program plays the other side.", - ], - [ - "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.", - "Hier werden einzelne Stellungen wiederholt. Jeder Repertoirezug wird akzeptiert; nur Ihr gespielter Zug wird erfasst.", - "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.", - "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.", - "Move review presents individual positions. Any repertoire move is accepted; only the move you play is recorded.", - ], - // --- strict learning session --- - [ - "Spaced repetition (SRS)", - "Интервальные повторения (SRS)", - "Répétition espacée (SRS)", - "Verteilte Wiederholung (SRS)", - "Repetición espaciada (SRS)", - "Ripetizione spaziata (SRS)", - "Repetição espaçada (SRS)", - "Oraliq takrorlash (SRS)", - "Аралық қайталау (SRS)", - ], - [ - "Hint", - "Подсказка", - "Indice", - "Hinweis", - "Pista", - "Suggerimento", - "Dica", - "Maslahat", - "Кеңес", - ], - [ - "Next", - "Далее", - "Suivant", - "Weiter", - "Siguiente", - "Avanti", - "Avançar", - "Keyingisi", - "Келесі", - ], - [ - "Your turn: play the main repertoire move.", - "Ваш ход: сыграйте основной ход репертуара.", - "À vous de jouer : jouez le coup principal du répertoire.", - "Sie sind am Zug: Spielen Sie den Hauptzug des Repertoires.", - "Tu turno: juega la jugada principal del repertorio.", - "Tocca a te: gioca la mossa principale del repertorio.", - "Sua vez: jogue o lance principal do repertório.", - "Sizning yurishingiz: repertuardagi asosiy yurishni o‘ynang.", - "Сіздің жүрісіңіз: репертуардың негізгі жүрісін жасаңыз.", - ], - ["T", "T", "T", "T", "T", "T", "T", "T", "T"], - [ - "Context and move speed", - "Контекст и скорость ходов", - "Contexte et vitesse des coups", - "Kontext und Zuggeschwindigkeit", - "Contexto y velocidad de las jugadas", - "Contesto e velocità delle mosse", - "Contexto e velocidade dos lances", - "Kontekst va yurish tezligi", - "Контекст және жүріс жылдамдығы", - ], - [ - "Reinforce minimum correct", - "Минимум правильных для закрепления", - "Minimum de réponses correctes pour renforcer", - "Mindestzahl richtiger Antworten zur Festigung", - "Mínimo de respuestas correctas para reforzar", - "Minimo di risposte corrette per rinforzare", - "Mínimo de respostas corretas para reforçar", - "Mustahkamlash uchun minimal to‘g‘ri javoblar", - "Бекіту үшін дұрыс жауаптардың ең аз саны", - ], - [ - "Reinforce minimum days", - "Минимум дней для закрепления", - "Nombre minimal de jours pour renforcer", - "Mindesttage zur Festigung", - "Días mínimos para reforzar", - "Giorni minimi per rinforzare", - "Dias mínimos para reforçar", - "Mustahkamlash uchun minimal kunlar", - "Бекіту үшін ең аз күндер", - ], - [ - "Don't show start moves threshold", - "Порог пропуска начальных ходов", - "Seuil pour masquer les coups initiaux", - "Schwelle zum Überspringen der Anfangszüge", - "Umbral para omitir las jugadas iniciales", - "Soglia per saltare le mosse iniziali", - "Limite para ocultar os lances iniciais", - "Boshlang‘ich yurishlarni o‘tkazib yuborish chegarasi", - "Бастапқы жүрістерді өткізіп жіберу шегі", - ], - [ - "Use fixed piece movement speed", - "Фиксированная скорость движения фигур", - "Utiliser une vitesse de déplacement fixe des pièces", - "Feste Figurenbewegungsgeschwindigkeit verwenden", - "Usar velocidad fija de movimiento de las piezas", - "Usa velocità di movimento fissa dei pezzi", - "Usar velocidade fixa de movimento das peças", - "Figuralarning harakat tezligini belgilash", - "Фигуралардың қозғалыс жылдамдығын белгілеу", - ], - [ - "Move speed adjustment", - "Настройка скорости ходов", - "Ajustement de la vitesse des coups", - "Anpassung der Zuggeschwindigkeit", - "Ajuste de velocidad de las jugadas", - "Regolazione della velocità delle mosse", - "Ajuste da velocidade dos lances", - "Yurish tezligini sozlash", - "Жүріс жылдамдығын реттеу", - ], - [ - "Consider leadup moves when training branch", - "Проверять предшествующие ходы при изучении ветки", - "Tenir compte des coups précédents lors de l’apprentissage d’une variante", - "Vorangehende Züge beim Training einer Variante berücksichtigen", - "Considerar jugadas previas al entrenar una variante", - "Considera le mosse precedenti durante l’apprendimento di una variante", - "Considerar lances anteriores ao treinar uma variante", - "Variantni o‘rganda oldingi yurishlarni hisobga olish", - "Нұсқаны үйренгенде алдыңғы жүрістерді ескеру", - ], - [ - "plies", - "полуходов", - "demi-coups", - "Halbzüge", - "semimovimientos", - "semimosse", - "meios lances", - "yarim yurishlar", - "жарты жүрістер", - ], - [ - "Main answer", - "Основной ответ", - "Réponse principale", - "Hauptzug", - "Respuesta principal", - "Risposta principale", - "Resposta principal", - "Asosiy javob", - "Негізгі жауап", - ], - [ - "Make main answer", - "Сделать основным ответом", - "Définir comme réponse principale", - "Als Hauptzug festlegen", - "Establecer como respuesta principal", - "Imposta come risposta principale", - "Definir como resposta principal", - "Asosiy javob qilib belgilash", - "Негізгі жауап етіп белгілеу", - ], - [ - "Clear override", - "Убрать переопределение", - "Supprimer la surcharge", - "Überschreibung aufheben", - "Quitar anulación", - "Rimuovi sostituzione", - "Remover substituição", - "Almashtirishni bekor qilish", - "Қайта анықтауды жою", - ], - [ - "main", - "основной", - "principal", - "Hauptzug", - "principal", - "principale", - "principal", - "asosiy", - "негізгі", - ], - [ - "Learning analytics is kept for the current main answer", - "Аналитика обучения ведётся для текущего основного ответа", - "Les statistiques d’apprentissage sont conservées pour la réponse principale actuelle", - "Lernstatistik wird für den aktuellen Hauptzug geführt", - "Las estadísticas de aprendizaje se guardan para la respuesta principal actual", - "Le statistiche di apprendimento sono conservate per la risposta principale attuale", - "As estatísticas de aprendizagem são mantidas para a resposta principal atual", - "O‘rganish statistikasi joriy asosiy javob uchun saqlanadi", - "Үйрену статистикасы ағымдағы негізгі жауап үшін сақталады", - ], - // --- learning dashboard --- - [ - "Learning dashboard", - "Панель обучения", - "Tableau d’apprentissage", - "Lernübersicht", - "Panel de aprendizaje", - "Pannello di apprendimento", - "Painel de aprendizagem", - "O‘rganish paneli", - "Үйрену панелі", - ], - [ - "All repertoires (union)", - "Все репертуары (объединение)", - "Tous les répertoires (union)", - "Alle Repertoires (Vereinigung)", - "Todos los repertorios (unión)", - "Tutti i repertori (unione)", - "Todos os repertórios (união)", - "Barcha repertuarlar (birleshma)", - "Барлық репертуар (біріктіру)", - ], - [ - "Total moves", - "Всего ходов", - "Coups au total", - "Züge insgesamt", - "Jugadas totales", - "Mosse totali", - "Lances totais", - "Jami yurishlar", - "Барлық жүрістер", - ], - [ - "Save the current numbers for the selected scope and side. PGN and learning progress do not change.", - "Сохранить текущие показатели для выбранной области и стороны. PGN и прогресс обучения не изменятся.", - "Enregistrer les valeurs actuelles pour la portée et le camp sélectionnés. Le PGN et la progression de l’apprentissage ne changent pas.", - "Die aktuellen Werte für den ausgewählten Bereich und die ausgewählte Seite speichern. PGN und Lernfortschritt bleiben unverändert.", - "Guardar las cifras actuales para el ámbito y el lado seleccionados. El PGN y el progreso de aprendizaje no cambian.", - "Salva i valori attuali per l’ambito e il lato selezionati. PGN e progressi di apprendimento non cambiano.", - "Salvar os números atuais para o escopo e o lado selecionados. O PGN e o progresso de aprendizagem não mudam.", - "Tanlangan doira va tomon uchun joriy ko‘rsatkichlarni saqlash. PGN va o‘rganish jarayoni o‘zgarmaydi.", - "Таңдалған аумақ пен тараптың ағымдағы көрсеткіштерін сақтау. PGN және үйрену барысы өзгермейді.", - ], - [ - "Capture snapshot", - "Сохранить снимок", - "Capturer un instantané", - "Snapshot aufnehmen", - "Capturar instantánea", - "Cattura istantanea", - "Capturar instantâneo", - "O‘lchovni saqlash", - "Түсірімді сақтау", - ], - [ - "Summary", - "Сводка", - "Résumé", - "Übersicht", - "Resumen", - "Riepilogo", - "Resumo", - "Qisqacha", - "Қорытынды", - ], - [ - "T = Unseen + Learning + Learnt. Uncertain is already included in Learnt.", - "T = новые + изучаемые + изученные. Неподтверждённые уже входят в изученные.", - "T = nouveaux + en apprentissage + acquis. Les incertains sont déjà compris dans les acquis.", - "T = Neu + Lernen + Gelernt. Unsichere sind bereits in Gelernt enthalten.", - "T = nuevas + en aprendizaje + aprendidas. Las inciertas ya están incluidas en aprendidas.", - "T = nuove + in apprendimento + apprese. Le incerte sono già incluse nelle apprese.", - "T = novos + em aprendizagem + aprendidos. Os incertos já estão incluídos nos aprendidos.", - "T = yangi + o‘rganilayotgan + o‘rganilgan. Noaniqlar o‘rganilganga kiradi.", - "T = жаңа + үйренілуде + үйренілген. Расталмағандар үйренілгенге кіреді.", - ], - [ - "Uncertain is already included in Learnt and is never added to T.", - "Неподтверждённые уже входят в изученные и отдельно не прибавляются к T.", - "Les incertains sont déjà compris dans les acquis et ne sont jamais ajoutés à T.", - "Unsichere sind bereits in Gelernt enthalten und werden nie zu T addiert.", - "Las inciertas ya están incluidas en aprendidas y nunca se suman a T.", - "Le incerte sono già incluse nelle apprese e non vengono mai aggiunte a T.", - "Os incertos já estão incluídos nos aprendidos e nunca são somados a T.", - "Noaniqlar o‘rganilganga kiradi va T ga alohida qo‘shilmaydi.", - "Расталмағандар үйренілгенге кіреді және T санына бөлек қосылмайды.", - ], - [ - "Next due at", - "Следующее повторение", - "Prochaine révision", - "Nächste Wiederholung", - "Próximo repaso", - "Prossima ripetizione", - "Próxima revisão", - "Keyingi takrorlash", - "Келесі қайталау", - ], - [ - "No snapshots yet. Save statistics to History to record the current scope.", - "Снимков пока нет. Нажмите «Сохранить статистику в историю», чтобы записать текущую область.", - "Aucun instantané. Utilisez « Enregistrer les statistiques dans l’historique » pour enregistrer la portée actuelle.", - "Noch keine Snapshots. Mit „Statistiken im Verlauf speichern“ den aktuellen Bereich speichern.", - "Aún no hay instantáneas. Usa «Guardar estadísticas en el historial» para registrar el ámbito actual.", - "Nessuna istantanea. Usa «Salva statistiche nella cronologia» per registrare l’ambito attuale.", - "Ainda não há instantâneos. Use «Salvar estatísticas no histórico» para registrar o escopo atual.", - "Hali o‘lchovlar yo‘q. Joriy doirani yozish uchun «Statistikani tarixga saqlash» bosing.", - "Әзірге түсірім жоқ. Ағымдағы аумақты жазу үшін «Статистиканы тарихқа сақтау» басыңыз.", - ], - [ - "Today", - "Сегодня", - "Aujourd’hui", - "Heute", - "Hoy", - "Oggi", - "Hoje", - "Bugun", - "Бүгін", - ], - [ - "Branches", - "Ветки", - "Branches", - "Varianten", - "Ramas", - "Rami", - "Ramos", - "Tarmoqlar", - "Тармақтар", - ], - [ - "Branch", - "Ветка", - "Branche", - "Variante", - "Rama", - "Ramo", - "Ramo", - "Tarmoq", - "Тармақ", - ], - [ - "Total = Unseen + Learning + Learnt.", - "Всего = не начато + изучается + изучено.", - "Total = non vus + en cours + acquis.", - "Gesamt = ungesehen + laufend + gelernt.", - "Total = sin ver + aprendiendo + aprendidas.", - "Totale = non viste + in apprendimento + apprese.", - "Total = não vistos + em aprendizado + aprendidos.", - "Jami = ko‘rilmagan + o‘rganilmoqda + o‘rganilgan.", - "Барлығы = басталмаған + үйренілуде + үйренілген.", - ], - [ - "Last trained", - "Последняя тренировка", - "Dernier entraînement", - "Letztes Training", - "Último entrenamiento", - "Ultimo allenamento", - "Último treino", - "Oxirgi mashg‘ulot", - "Соңғы жаттығу", - ], - [ - "Selected: {n}", - "Выбрано: {n}", - "Sélection : {n}", - "Ausgewählt: {n}", - "Seleccionadas: {n}", - "Selezionate: {n}", - "Selecionadas: {n}", - "Tanlangan: {n}", - "Таңдалды: {n}", - ], - [ - "Selected: {n} ({k} hidden by the filter)", - "Выбрано: {n} ({k} скрыто фильтром)", - "Sélection : {n} ({k} masquées par le filtre)", - "Ausgewählt: {n} ({k} vom Filter verborgen)", - "Seleccionadas: {n} ({k} ocultas por el filtro)", - "Selezionate: {n} ({k} nascoste dal filtro)", - "Selecionadas: {n} ({k} ocultas pelo filtro)", - "Tanlangan: {n} ({k} tasi filtr bilan yashirilgan)", - "Таңдалды: {n} ({k} сүзгімен жасырылған)", - ], - [ - "Deselect", - "Снять", - "Désélectionner", - "Abwählen", - "Deseleccionar", - "Deseleziona", - "Desmarcar", - "Bekor qilish", - "Алып тастау", - ], - [ - "Clear the selection (Esc)", - "Снять выделение (Esc)", - "Annuler la sélection (Échap)", - "Auswahl aufheben (Esc)", - "Quitar la selección (Esc)", - "Annulla la selezione (Esc)", - "Limpar a seleção (Esc)", - "Tanlovni bekor qilish (Esc)", - "Таңдауды алып тастау (Esc)", - ], - [ - "Games hidden by the filter will be copied too. Esc clears the selection", - "Скрытые фильтром партии тоже будут скопированы. Снять выделение — Esc", - "Les parties masquées par le filtre seront aussi copiées. Échap annule la sélection", - "Vom Filter verborgene Partien werden mitkopiert. Esc hebt die Auswahl auf", - "Las partidas ocultas por el filtro también se copiarán. Esc quita la selección", - "Anche le partite nascoste dal filtro saranno copiate. Esc annulla la selezione", - "As partidas ocultas pelo filtro também serão copiadas. Esc limpa a seleção", - "Filtr yashirgan partiyalar ham nusxalanadi. Esc — tanlovni bekor qilish", - "Сүзгі жасырған партиялар да көшіріледі. Esc — таңдауды алып тастау", - ], - [ - "Games selected: {n}", - "Выбрано партий: {n}", - "Parties sélectionnées : {n}", - "Ausgewählte Partien: {n}", - "Partidas seleccionadas: {n}", - "Partite selezionate: {n}", - "Partidas selecionadas: {n}", - "Tanlangan partiyalar: {n}", - "Таңдалған партиялар: {n}", - ], - [ - "New database from selected…", - "Новая база из выбранных…", - "Nouvelle base à partir de la sélection…", - "Neue Datenbank aus Auswahl…", - "Nueva base con las seleccionadas…", - "Nuovo database dalle selezionate…", - "Nova base a partir das selecionadas…", - "Tanlanganlardan yangi baza…", - "Таңдалғандардан жаңа база…", - ], - [ - "Select all (Ctrl+A)", - "Выделить все (Ctrl+A)", - "Tout sélectionner (Ctrl+A)", - "Alle auswählen (Strg+A)", - "Seleccionar todo (Ctrl+A)", - "Seleziona tutto (Ctrl+A)", - "Selecionar tudo (Ctrl+A)", - "Hammasini tanlash (Ctrl+A)", - "Барлығын таңдау (Ctrl+A)", - ], - [ - "Clear selection (Esc)", - "Снять выделение (Esc)", - "Annuler la sélection (Échap)", - "Auswahl aufheben (Esc)", - "Quitar selección (Esc)", - "Annulla selezione (Esc)", - "Limpar seleção (Esc)", - "Tanlovni bekor qilish (Esc)", - "Таңдауды алып тастау (Esc)", - ], - [ - "Writing to «{name}» — wait until it finishes", - "Идёт запись в «{name}» — дождитесь окончания", - "Écriture dans « {name} » — attendez la fin", - "Schreibe in «{name}» — warten Sie, bis es fertig ist", - "Escribiendo en «{name}»: espere a que termine", - "Scrittura in «{name}» — attendi la fine", - "Gravando em «{name}» — aguarde o fim", - "«{name}» ga yozilmoqda — tugashini kuting", - "«{name}» ішіне жазылуда — аяқталуын күтіңіз", - ], - [ - "From the selection: {games} from «{src}»", - "Из выбранных: {games} из «{src}»", - "De la sélection : {games} de « {src} »", - "Aus der Auswahl: {games} aus «{src}»", - "De la selección: {games} de «{src}»", - "Dalla selezione: {games} da «{src}»", - "Da seleção: {games} de «{src}»", - "Tanlovdan: «{src}» dan {games}", - "Таңдаудан: «{src}» ішінен {games}", - ], - [ - "{k} of them are hidden by the filter now", - "из них {k} сейчас скрыты фильтром", - "dont {k} masquées par le filtre", - "davon {k} gerade vom Filter verborgen", - "{k} de ellas ocultas ahora por el filtro", - "di cui {k} ora nascoste dal filtro", - "{k} delas ocultas agora pelo filtro", - "ulardan {k} tasi hozir filtr bilan yashirilgan", - "олардың {k} қазір сүзгімен жасырылған", - ], - [ - "Many games: writing may take a few minutes; you can cancel it", - "Много партий: запись может занять несколько минут, её можно отменить", - "Beaucoup de parties : l’écriture peut prendre quelques minutes ; vous pouvez l’annuler", - "Viele Partien: das Schreiben kann einige Minuten dauern; Sie können es abbrechen", - "Muchas partidas: la escritura puede tardar unos minutos; se puede cancelar", - "Molte partite: la scrittura può richiedere alcuni minuti; puoi annullarla", - "Muitas partidas: a gravação pode levar alguns minutos; pode cancelá-la", - "Partiyalar ko‘p: yozish bir necha daqiqa olishi mumkin, uni bekor qilish mumkin", - "Партиялар көп: жазу бірнеше минутқа созылуы мүмкін, оны тоқтатуға болады", - ], - [ - "Create and copy", - "Создать и скопировать", - "Créer et copier", - "Erstellen und kopieren", - "Crear y copiar", - "Crea e copia", - "Criar e copiar", - "Yaratish va nusxalash", - "Жасау және көшіру", - ], - [ - "Writing to «{name}»: {i} of {n}", - "Запись в «{name}»: {i} из {n}", - "Écriture dans « {name} » : {i} sur {n}", - "Schreibe in «{name}»: {i} von {n}", - "Escribiendo en «{name}»: {i} de {n}", - "Scrittura in «{name}»: {i} di {n}", - "Gravando em «{name}»: {i} de {n}", - "«{name}» ga yozilmoqda: {n} dan {i}", - "«{name}» ішіне жазу: {n} ішінен {i}", - ], - [ - "Cancelling…", - "Отмена…", - "Annulation…", - "Wird abgebrochen…", - "Cancelando…", - "Annullamento…", - "Cancelando…", - "Bekor qilinmoqda…", - "Тоқтатылуда…", - ], - [ - "{name}: copied {n}, skipped {m}", - "{name}: скопировано {n}, пропущено {m}", - "{name} : {n} copiées, {m} ignorées", - "{name}: {n} kopiert, {m} übersprungen", - "{name}: copiadas {n}, omitidas {m}", - "{name}: copiate {n}, saltate {m}", - "{name}: copiadas {n}, ignoradas {m}", - "{name}: {n} ta nusxalandi, {m} ta o‘tkazildi", - "{name}: {n} көшірілді, {m} өткізілді", - ], - [ - "{name}: copied {n}, skipped {m} — duplicates {d}{dl}, unreadable {u}{ul}", - "{name}: скопировано {n}, пропущено {m} — дубли {d}{dl}, не прочитано {u}{ul}", - "{name} : {n} copiées, {m} ignorées — doublons {d}{dl}, illisibles {u}{ul}", - "{name}: {n} kopiert, {m} übersprungen — Duplikate {d}{dl}, unlesbar {u}{ul}", - "{name}: copiadas {n}, omitidas {m} — duplicadas {d}{dl}, ilegibles {u}{ul}", - "{name}: copiate {n}, saltate {m} — duplicati {d}{dl}, illeggibili {u}{ul}", - "{name}: copiadas {n}, ignoradas {m} — duplicadas {d}{dl}, ilegíveis {u}{ul}", - "{name}: {n} ta nusxalandi, {m} ta o‘tkazildi — takrorlar {d}{dl}, o‘qilmadi {u}{ul}", - "{name}: {n} көшірілді, {m} өткізілді — қайталанған {d}{dl}, оқылмады {u}{ul}", - ], - [ - "No. {list}", - "№ {list}", - "n° {list}", - "Nr. {list}", - "n.º {list}", - "n. {list}", - "n.º {list}", - "№ {list}", - "№ {list}", - ], - [ - "and {n} more", - "и ещё {n}", - "et {n} de plus", - "und {n} weitere", - "y {n} más", - "e altre {n}", - "e mais {n}", - "va yana {n} ta", - "және тағы {n}", - ], - [ - "Copying cancelled: «{name}» was not created", - "Копирование отменено: база «{name}» не создана", - "Copie annulée : « {name} » n’a pas été créée", - "Kopieren abgebrochen: «{name}» wurde nicht erstellt", - "Copia cancelada: «{name}» no se ha creado", - "Copia annullata: «{name}» non è stato creato", - "Cópia cancelada: «{name}» não foi criada", - "Nusxalash bekor qilindi: «{name}» yaratilmadi", - "Көшіру тоқтатылды: «{name}» жасалмады", - ], - [ - "Could not write «{name}»: {reason}. Nothing was written", - "Не удалось записать «{name}»: {reason}. Ничего не записано", - "Impossible d’écrire « {name} » : {reason}. Rien n’a été écrit", - "«{name}» konnte nicht geschrieben werden: {reason}. Nichts wurde geschrieben", - "No se pudo escribir «{name}»: {reason}. No se escribió nada", - "Impossibile scrivere «{name}»: {reason}. Non è stato scritto nulla", - "Não foi possível gravar «{name}»: {reason}. Nada foi gravado", - "«{name}» ni yozib bo‘lmadi: {reason}. Hech narsa yozilmadi", - "«{name}» жазылмады: {reason}. Ештеңе жазылған жоқ", - ], - [ - "«{src}» changed while copying. Nothing was written", - "База «{src}» изменилась во время копирования. Ничего не записано", - "« {src} » a changé pendant la copie. Rien n’a été écrit", - "«{src}» hat sich beim Kopieren geändert. Nichts wurde geschrieben", - "«{src}» cambió durante la copia. No se escribió nada", - "«{src}» è cambiato durante la copia. Non è stato scritto nulla", - "«{src}» mudou durante a cópia. Nada foi gravado", - "«{src}» nusxalash paytida o‘zgardi. Hech narsa yozilmadi", - "«{src}» көшіру кезінде өзгерді. Ештеңе жазылған жоқ", - ], - [ - "Games are deleted one at a time: clear the selection (Esc)", - "Удалять можно по одной партии: снимите выделение (Esc)", - "Les parties se suppriment une par une : annulez la sélection (Échap)", - "Partien werden einzeln gelöscht: heben Sie die Auswahl auf (Esc)", - "Las partidas se borran de una en una: quite la selección (Esc)", - "Le partite si eliminano una alla volta: annulla la selezione (Esc)", - "As partidas são apagadas uma de cada vez: limpe a seleção (Esc)", - "Partiyalar bittadan o‘chiriladi: tanlovni bekor qiling (Esc)", - "Партиялар бір-бірден жойылады: таңдауды алып тастаңыз (Esc)", - ], - [ - "a file with this name is already there", - "файл с таким именем уже есть", - "un fichier de ce nom existe déjà", - "eine Datei mit diesem Namen gibt es schon", - "ya existe un archivo con ese nombre", - "esiste già un file con questo nome", - "já existe um ficheiro com este nome", - "bu nomli fayl allaqachon bor", - "мұндай атаулы файл бар", - ], - [ - "the source changed", - "источник изменился", - "la source a changé", - "die Quelle hat sich geändert", - "el origen cambió", - "la sorgente è cambiata", - "a origem mudou", - "manba o‘zgardi", - "көз өзгерді", - ], - [ - "no space left on the disk", - "на диске нет места", - "plus d’espace sur le disque", - "kein Platz mehr auf dem Datenträger", - "no queda espacio en el disco", - "spazio su disco esaurito", - "sem espaço no disco", - "diskda joy qolmadi", - "дискіде орын жоқ", - ], - [ - "no permission to write", - "нет прав на запись", - "pas de droit d’écriture", - "keine Schreibrechte", - "sin permiso de escritura", - "nessun permesso di scrittura", - "sem permissão de escrita", - "yozishga ruxsat yo‘q", - "жазуға рұқсат жоқ", - ], - [ - "Another copy is being written: wait until it finishes", - "Идёт другая запись: дождитесь окончания", - "Une autre copie est en cours d’écriture : attendez la fin", - "Eine andere Kopie wird geschrieben: warten Sie, bis sie fertig ist", - "Se está escribiendo otra copia: espere a que termine", - "È in corso un’altra copia: attendi la fine", - "Outra cópia está a ser gravada: aguarde o fim", - "Boshqa nusxa yozilmoqda: tugashini kuting", - "Басқа көшірме жазылуда: аяқталуын күтіңіз", - ], - [ - "Selection cleared: the database changed", - "Выделение снято: база изменилась", - "Sélection annulée : la base a changé", - "Auswahl aufgehoben: die Datenbank hat sich geändert", - "Selección quitada: la base cambió", - "Selezione annullata: il database è cambiato", - "Seleção limpa: a base mudou", - "Tanlov bekor qilindi: baza o‘zgardi", - "Таңдау алынды: база өзгерді", - ], - [ - "The engine is busy searching opening errors in a preparation: wait or stop it", - "Движок занят: идёт поиск ошибок дебюта в подготовке — дождитесь или остановите его", - "Le moteur est occupé à chercher les erreurs d’ouverture d’une préparation : attendez ou arrêtez-le", - "Die Engine sucht gerade Eröffnungsfehler in einer Vorbereitung: warten oder anhalten", - "El motor está buscando errores de apertura en una preparación: espere o deténgalo", - "Il motore sta cercando errori d’apertura in una preparazione: attendi o fermalo", - "O motor está a procurar erros de abertura numa preparação: aguarde ou pare-o", - "Dvigatel tayyorgarlikda debyut xatolarini qidirmoqda — kuting yoki to‘xtating", - "Қозғалтқыш дайындықта дебют қателерін іздеуде — күтіңіз не тоқтатыңыз", - ], - [ - "all games", - "все партии базы", - "toutes les parties", - "alle Partien", - "todas las partidas", - "tutte le partite", - "todas as partidas", - "bazadagi barcha partiyalar", - "базаның барлық партиялары", - ], - [ - "matching the conditions", - "по условиям", - "selon les conditions", - "nach den Bedingungen", - "según las condiciones", - "secondo le condizioni", - "segundo as condições", - "shartlar bo‘yicha", - "шарттар бойынша", - ], - [ - "The search needs Stockfish 19: start «Analyse game» once to get it", - "Для поиска нужен Stockfish 19: один раз запустите «Анализ партии», чтобы его получить", - "La recherche a besoin de Stockfish 19 : lancez une fois « Analyser la partie » pour l’obtenir", - "Die Suche braucht Stockfish 19: einmal «Partie analysieren» starten, um ihn zu bekommen", - "La búsqueda necesita Stockfish 19: inicie una vez «Analizar partida» para obtenerlo", - "La ricerca richiede Stockfish 19: avvia una volta «Analizza partita» per ottenerlo", - "A pesquisa precisa do Stockfish 19: inicie uma vez «Analisar partida» para o obter", - "Qidiruv uchun Stockfish 19 kerak: uni olish uchun bir marta «Partiya tahlili»ni ishga tushiring", - "Іздеуге Stockfish 19 керек: оны алу үшін бір рет «Партия талдауын» іске қосыңыз", - ], - [ - "Search stopped: no game was reviewed", - "Поиск остановлен: ни одна партия не разобрана", - "Recherche arrêtée : aucune partie n’a été analysée", - "Suche angehalten: keine Partie wurde analysiert", - "Búsqueda detenida: no se analizó ninguna partida", - "Ricerca fermata: nessuna partita analizzata", - "Pesquisa parada: nenhuma partida foi analisada", - "Qidiruv to‘xtatildi: birorta ham partiya tahlil qilinmadi", - "Іздеу тоқтатылды: бірде-бір партия талданбады", - ], - [ - "The engine is busy reviewing {game}", - "Движок занят: идёт разбор партии {game}", - "Le moteur est occupé à analyser {game}", - "Die Engine analysiert gerade {game}", - "El motor está analizando {game}", - "Il motore sta analizzando {game}", - "O motor está a analisar {game}", - "Dvigatel {game} partiyasini tahlil qilmoqda", - "Қозғалтқыш {game} партиясын талдауда", - ], - [ - "Searching for great moves in «{db}»: {i} of {n}. Stop it in the library", - "Идёт поиск замечательных ходов в «{db}»: {i} из {n}. Остановить — в библиотеке", - "Recherche de très bons coups dans « {db} » : {i} sur {n}. Arrêtez-la dans la bibliothèque", - "Suche nach starken Zügen in «{db}»: {i} von {n}. Anhalten in der Bibliothek", - "Buscando jugadas notables en «{db}»: {i} de {n}. Deténgala en la biblioteca", - "Ricerca di mosse notevoli in «{db}»: {i} di {n}. Fermala nella libreria", - "A procurar lances notáveis em «{db}»: {i} de {n}. Pare-a na biblioteca", - "«{db}» da ajoyib yurishlar qidirilmoqda: {n} dan {i}. To‘xtatish — kutubxonada", - "«{db}» ішінде тамаша жүрістер ізделуде: {n} ішінен {i}. Тоқтату — кітапханада", - ], - [ - "The engine failed: {reason}. {i} of {n} reviewed", - "Движок остановился с ошибкой: {reason}. Разобрано {i} из {n}", - "Le moteur a échoué : {reason}. {i} sur {n} analysées", - "Die Engine ist ausgefallen: {reason}. {i} von {n} analysiert", - "El motor falló: {reason}. Analizadas {i} de {n}", - "Il motore si è fermato con un errore: {reason}. Analizzate {i} di {n}", - "O motor falhou: {reason}. Analisadas {i} de {n}", - "Dvigatel xato bilan to‘xtadi: {reason}. {n} dan {i} tasi tahlil qilindi", - "Қозғалтқыш қатемен тоқтады: {reason}. {n} ішінен {i} талданды", - ], - [ - "«{db}» changed; the search stopped. {i} of {n} reviewed", - "База «{db}» изменилась — поиск остановлен. Разобрано {i} из {n}", - "« {db} » a changé ; la recherche s’est arrêtée. {i} sur {n} analysées", - "«{db}» hat sich geändert; die Suche wurde angehalten. {i} von {n} analysiert", - "«{db}» cambió; la búsqueda se detuvo. Analizadas {i} de {n}", - "«{db}» è cambiato; la ricerca si è fermata. Analizzate {i} di {n}", - "«{db}» mudou; a pesquisa parou. Analisadas {i} de {n}", - "«{db}» bazasi o‘zgardi — qidiruv to‘xtatildi. {n} dan {i} tasi tahlil qilindi", - "«{db}» базасы өзгерді — іздеу тоқтатылды. {n} ішінен {i} талданды", - ], - [ - "Wait: the games are still being filtered", - "Подождите — партии ещё отбираются", - "Patientez : les parties sont encore en cours de filtrage", - "Bitte warten: die Partien werden noch gefiltert", - "Espere: las partidas todavía se están filtrando", - "Attendi: le partite sono ancora in fase di filtro", - "Aguarde: as partidas ainda estão a ser filtradas", - "Kuting — partiyalar hali tanlanmoqda", - "Күтіңіз — партиялар әлі іріктелуде", - ], - [ - "No games match these conditions", - "Нет партий по этим условиям", - "Aucune partie ne correspond à ces conditions", - "Keine Partien passen zu diesen Bedingungen", - "Ninguna partida cumple estas condiciones", - "Nessuna partita corrisponde a queste condizioni", - "Nenhuma partida corresponde a estas condições", - "Bu shartlar bo‘yicha partiya yo‘q", - "Бұл шарттар бойынша партия жоқ", - ], - [ - "Filter the games down to 100 or fewer", - "Отфильтруйте партии, чтобы их было не больше 100", - "Filtrez les parties pour en avoir 100 au plus", - "Filtern Sie auf höchstens 100 Partien", - "Filtre las partidas hasta 100 como máximo", - "Filtra le partite fino a non più di 100", - "Filtre as partidas até no máximo 100", - "Partiyalar 100 tadan ko‘p bo‘lmasin — filtrlang", - "Партиялар 100-ден аспайтындай сүзіңіз", - ], - [ - "!! Find moves", - "!! Найти ходы", - "!! Trouver des coups", - "!! Züge finden", - "!! Buscar jugadas", - "!! Trova mosse", - "!! Procurar lances", - "!! Yurishlarni topish", - "!! Жүрістерді табу", - ], - [ - "!! Find great moves", - "!! Найти замечательные ходы", - "!! Trouver de très bons coups", - "!! Starke Züge finden", - "!! Buscar jugadas notables", - "!! Trova mosse notevoli", - "!! Procurar lances notáveis", - "!! Ajoyib yurishlarni topish", - "!! Тамаша жүрістерді табу", - ], - [ - "Stopping…", - "Останавливаю…", - "Arrêt…", - "Wird angehalten…", - "Deteniendo…", - "Arresto…", - "A parar…", - "To‘xtatilmoqda…", - "Тоқтатылуда…", - ], - [ - "Stop the search; the reviewed games are kept", - "Остановить поиск; разобранные партии сохранятся", - "Arrêter la recherche ; les parties analysées sont conservées", - "Suche anhalten; analysierte Partien bleiben erhalten", - "Detener la búsqueda; las partidas analizadas se conservan", - "Ferma la ricerca; le partite analizzate restano", - "Parar a pesquisa; as partidas analisadas são guardadas", - "Qidiruvni to‘xtatish; tahlil qilingan partiyalar saqlanadi", - "Іздеуді тоқтату; талданған партиялар сақталады", - ], - [ - "Brilliant and great moves found by the engine: sort by them", - "Блестящие и замечательные ходы, найденные движком: сортировать по ним", - "Coups brillants et très bons trouvés par le moteur : trier par eux", - "Von der Engine gefundene brillante und starke Züge: danach sortieren", - "Jugadas brillantes y notables halladas por el motor: ordenar por ellas", - "Mosse brillanti e notevoli trovate dal motore: ordina per esse", - "Lances brilhantes e notáveis encontrados pelo motor: ordenar por eles", - "Dvigatel topgan ajoyib va zo‘r yurishlar: ular bo‘yicha saralash", - "Қозғалтқыш тапқан керемет және тамаша жүрістер: солар бойынша сұрыптау", - ], - [ - "Being reviewed…", - "Разбирается…", - "En cours d’analyse…", - "Wird analysiert…", - "Analizándose…", - "In analisi…", - "A ser analisada…", - "Tahlil qilinmoqda…", - "Талдануда…", - ], - [ - "Reviewed: no brilliant or great moves", - "Разобрана: блестящих и замечательных ходов нет", - "Analysée : aucun coup brillant ou très bon", - "Analysiert: keine brillanten oder starken Züge", - "Analizada: sin jugadas brillantes ni notables", - "Analizzata: nessuna mossa brillante o notevole", - "Analisada: sem lances brilhantes ou notáveis", - "Tahlil qilingan: ajoyib va zo‘r yurishlar yo‘q", - "Талданды: керемет және тамаша жүрістер жоқ", - ], - [ - "Reviewed with the previous engine settings", - "Разбор прежними настройками движка", - "Analysée avec les anciens réglages du moteur", - "Mit den früheren Engine-Einstellungen analysiert", - "Analizada con los ajustes anteriores del motor", - "Analizzata con le impostazioni precedenti del motore", - "Analisada com as definições anteriores do motor", - "Dvigatelning avvalgi sozlamalari bilan tahlil", - "Қозғалтқыштың бұрынғы баптауларымен талданған", - ], - [ - "Searching in «{db}»: {i} of {n}; stop it there", - "Идёт поиск в «{db}»: {i} из {n} — остановите его там", - "Recherche dans « {db} » : {i} sur {n} ; arrêtez-la là-bas", - "Suche in «{db}»: {i} von {n}; dort anhalten", - "Buscando en «{db}»: {i} de {n}; deténgala allí", - "Ricerca in «{db}»: {i} di {n}; fermala lì", - "A pesquisar em «{db}»: {i} de {n}; pare-a lá", - "«{db}» da qidiruv: {n} dan {i} — uni o‘sha yerda to‘xtating", - "«{db}» ішінде іздеу: {n} ішінен {i} — оны сонда тоқтатыңыз", - ], - [ - "Now: {n}", - "Сейчас: {n}", - "Actuellement : {n}", - "Jetzt: {n}", - "Ahora: {n}", - "Ora: {n}", - "Agora: {n}", - "Hozir: {n}", - "Қазір: {n}", - ], - [ - "Analysed {i} of {n} · ≈ {time} left", - "Проанализировано {i} из {n} · осталось ≈ {time}", - "Analysées {i} sur {n} · encore ≈ {time}", - "Analysiert {i} von {n} · noch ≈ {time}", - "Analizadas {i} de {n} · quedan ≈ {time}", - "Analizzate {i} di {n} · restano ≈ {time}", - "Analisadas {i} de {n} · faltam ≈ {time}", - "{n} dan {i} tasi tahlil qilindi · qoldi ≈ {time}", - "{n} ішінен {i} талданды · қалды ≈ {time}", - ], - [ - "{i} of {n}", - "{i} из {n}", - "{i} sur {n}", - "{i} von {n}", - "{i} de {n}", - "{i} di {n}", - "{i} de {n}", - "{n} dan {i}", - "{n} ішінен {i}", - ], - [ - "In «{db}»: {i} of {n}", - "В «{db}»: {i} из {n}", - "Dans « {db} » : {i} sur {n}", - "In «{db}»: {i} von {n}", - "En «{db}»: {i} de {n}", - "In «{db}»: {i} di {n}", - "Em «{db}»: {i} de {n}", - "«{db}» da: {n} dan {i}", - "«{db}» ішінде: {n} ішінен {i}", - ], - [ - "Review {games} with the engine and mark the !! and ! moves found (Shift+A)", - "Разобрать движком {games} и отметить найденные !! и ! (Shift+A)", - "Analyser {games} avec le moteur et marquer les !! et ! trouvés (Maj+A)", - "{games} mit der Engine analysieren und gefundene !! und ! markieren (Umschalt+A)", - "Analizar {games} con el motor y marcar los !! y ! hallados (Mayús+A)", - "Analizza {games} con il motore e segna i !! e ! trovati (Maiusc+A)", - "Analisar {games} com o motor e marcar os !! e ! encontrados (Shift+A)", - "{games}ni dvigatel bilan tahlil qilib, topilgan !! va ! ni belgilash (Shift+A)", - "{games} қозғалтқышпен талдап, табылған !! және ! белгілеу (Shift+A)", - ], - [ - "Open at {move}", - "Открыть на ходе {move}", - "Ouvrir au coup {move}", - "Bei {move} öffnen", - "Abrir en {move}", - "Apri alla mossa {move}", - "Abrir no lance {move}", - "{move} yurishida ochish", - "{move} жүрісінде ашу", - ], - [ - "Cannot be reviewed: {reason}", - "Не разбирается: {reason}", - "Analyse impossible : {reason}", - "Kann nicht analysiert werden: {reason}", - "No se puede analizar: {reason}", - "Non analizzabile: {reason}", - "Não pode ser analisada: {reason}", - "Tahlil qilinmaydi: {reason}", - "Талданбайды: {reason}", - ], - [ - "Brilliant moves: {n}: {moves}", - "Блестящих ходов: {n} — {moves}", - "Coups brillants : {n} — {moves}", - "Brillante Züge: {n} — {moves}", - "Jugadas brillantes: {n} — {moves}", - "Mosse brillanti: {n} — {moves}", - "Lances brilhantes: {n} — {moves}", - "Ajoyib yurishlar: {n} — {moves}", - "Керемет жүрістер: {n} — {moves}", - ], - [ - "Great moves: {n}: {moves}", - "Замечательных: {n} — {moves}", - "Très bons coups : {n} — {moves}", - "Starke Züge: {n} — {moves}", - "Jugadas notables: {n} — {moves}", - "Mosse notevoli: {n} — {moves}", - "Lances notáveis: {n} — {moves}", - "Zo‘r yurishlar: {n} — {moves}", - "Тамаша жүрістер: {n} — {moves}", - ], - [ - "the engine is no longer the Stockfish 19 that was checked", - "движок уже не тот Stockfish 19, что был проверен", - "le moteur n’est plus le Stockfish 19 vérifié", - "die Engine ist nicht mehr der geprüfte Stockfish 19", - "el motor ya no es el Stockfish 19 comprobado", - "il motore non è più lo Stockfish 19 verificato", - "o motor já não é o Stockfish 19 verificado", - "dvigatel endi tekshirilgan Stockfish 19 emas", - "қозғалтқыш енді тексерілген Stockfish 19 емес", - ], - [ - "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", "Chess960", - "Chess960", "Chess960", - ], - [ - "a null move in the main line", - "пустой ход в основной линии", - "un coup nul dans la ligne principale", - "ein Nullzug in der Hauptvariante", - "una jugada nula en la línea principal", - "una mossa nulla nella linea principale", - "um lance nulo na linha principal", - "asosiy liniyada bo‘sh yurish", - "негізгі линияда бос жүріс", - ], - [ - "the game cannot be read", - "партию не удалось прочитать", - "la partie est illisible", - "die Partie ist nicht lesbar", - "la partida no se puede leer", - "la partita non è leggibile", - "a partida não pode ser lida", - "partiyani o‘qib bo‘lmadi", - "партия оқылмады", - ], - [ - "Find great moves", - "Найти замечательные ходы", - "Trouver de très bons coups", - "Starke Züge finden", - "Buscar jugadas notables", - "Trova mosse notevoli", - "Procurar lances notáveis", - "Ajoyib yurishlarni topish", - "Тамаша жүрістерді табу", - ], - [ - "Counting the games already reviewed…", - "Считаю, сколько партий уже разобрано…", - "Décompte des parties déjà analysées…", - "Zähle bereits analysierte Partien…", - "Contando las partidas ya analizadas…", - "Conto le partite già analizzate…", - "A contar as partidas já analisadas…", - "Allaqachon tahlil qilingan partiyalar sanalmoqda…", - "Талданып қойған партиялар саналуда…", - ], - [ - "The engine will review {games}: about {time}.", - "Движок разберёт {games} — примерно {time}.", - "Le moteur analysera {games} : environ {time}.", - "Die Engine analysiert {games}: etwa {time}.", - "El motor analizará {games}: unos {time}.", - "Il motore analizzerà {games}: circa {time}.", - "O motor vai analisar {games}: cerca de {time}.", - "Dvigatel {games}ni tahlil qiladi — taxminan {time}.", - "Қозғалтқыш {games} талдайды — шамамен {time}.", - ], - [ - "{k} are already reviewed: their marks come from the saved review.", - "{k} уже разобраны: их отметки возьмутся из сохранённого разбора.", - "{k} sont déjà analysées : leurs marques viennent de l’analyse enregistrée.", - "{k} sind bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", - "{k} ya están analizadas: sus marcas salen del análisis guardado.", - "{k} sono già analizzate: i loro segni vengono dall’analisi salvata.", - "{k} já estão analisadas: as suas marcas vêm da análise guardada.", - "{k} tasi allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", - "{k} талданып қойған: белгілері сақталған талдаудан алынады.", - ], - [ - "The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept.", - "Компьютер будет загружен (до {p} процессов Stockfish 19). Работать с программой можно; остановить — в любой момент, разобранные партии сохранятся.", - "L’ordinateur sera occupé (jusqu’à {p} processus Stockfish 19). Vous pouvez continuer à travailler et arrêter à tout moment ; les parties analysées sont conservées.", - "Der Computer wird ausgelastet (bis zu {p} Stockfish-19-Prozesse). Sie können weiterarbeiten und jederzeit anhalten; analysierte Partien bleiben erhalten.", - "El ordenador estará ocupado (hasta {p} procesos de Stockfish 19). Puede seguir trabajando y detenerlo en cualquier momento; las partidas analizadas se conservan.", - "Il computer sarà occupato (fino a {p} processi Stockfish 19). Puoi continuare a lavorare e fermare in qualsiasi momento; le partite analizzate restano.", - "O computador ficará ocupado (até {p} processos Stockfish 19). Pode continuar a trabalhar e parar a qualquer momento; as partidas analisadas são guardadas.", - "Kompyuter band bo‘ladi ({p} tagacha Stockfish 19 jarayoni). Dastur bilan ishlash mumkin; istalgan payt to‘xtatish mumkin, tahlil qilinganlar saqlanadi.", - "Компьютер жүктеледі ({p} дейін Stockfish 19 процесі). Бағдарламамен жұмыс істеуге болады; кез келген уақытта тоқтатуға болады, талданғандар сақталады.", - ], - [ - "Start", - "Начать", - "Commencer", - "Starten", - "Empezar", - "Avvia", - "Começar", - "Boshlash", - "Бастау", - ], - [ - "Summary of the reviewed ({k})", - "Итог по разобранным ({k})", - "Bilan des analysées ({k})", - "Übersicht der analysierten ({k})", - "Resumen de las analizadas ({k})", - "Riepilogo delle analizzate ({k})", - "Resumo das analisadas ({k})", - "Tahlil qilinganlar yakuni ({k})", - "Талданғандар қорытындысы ({k})", - ], - [ - "Search stopped · reviewed: {i} of {n}", - "Поиск остановлен · разобрано: {i} из {n}", - "Recherche arrêtée · analysées : {i} sur {n}", - "Suche angehalten · analysiert: {i} von {n}", - "Búsqueda detenida · analizadas: {i} de {n}", - "Ricerca fermata · analizzate: {i} di {n}", - "Pesquisa parada · analisadas: {i} de {n}", - "Qidiruv to‘xtatildi · tahlil qilindi: {n} dan {i}", - "Іздеу тоқтатылды · талданды: {n} ішінен {i}", - ], - [ - "Summary · reviewed: {games}", - "Итог · разобрано: {games}", - "Bilan · analysées : {games}", - "Übersicht · analysiert: {games}", - "Resumen · analizadas: {games}", - "Riepilogo · analizzate: {games}", - "Resumo · analisadas: {games}", - "Yakun · tahlil qilindi: {games}", - "Қорытынды · талданды: {games}", - ], - [ - "Only the moves of «{name}» count: as White {w}, as Black {b}", - "Считаются только ходы игрока «{name}»: белыми {w}, чёрными {b}", - "Seuls les coups de « {name} » comptent : avec les Blancs {w}, avec les Noirs {b}", - "Nur die Züge von «{name}» zählen: mit Weiß {w}, mit Schwarz {b}", - "Solo cuentan las jugadas de «{name}»: con blancas {w}, con negras {b}", - "Contano solo le mosse di «{name}»: col Bianco {w}, col Nero {b}", - "Só contam os lances de «{name}»: de brancas {w}, de pretas {b}", - "Faqat «{name}» yurishlari hisoblanadi: oq bilan {w}, qora bilan {b}", - "Тек «{name}» жүрістері есептеледі: ақпен {w}, қарамен {b}", - ], - [ - "Not reviewed: {k} ({reason})", - "Не разобраны: {k} ({reason})", - "Non analysées : {k} ({reason})", - "Nicht analysiert: {k} ({reason})", - "No analizadas: {k} ({reason})", - "Non analizzate: {k} ({reason})", - "Não analisadas: {k} ({reason})", - "Tahlil qilinmagan: {k} ({reason})", - "Талданбаған: {k} ({reason})", - ], - [ - "{k} of them were reviewed with the previous engine settings", - "{k} из них разобраны прежними настройками движка", - "{k} d’entre elles ont été analysées avec les anciens réglages du moteur", - "{k} davon wurden mit den früheren Engine-Einstellungen analysiert", - "{k} de ellas se analizaron con los ajustes anteriores del motor", - "{k} di esse sono state analizzate con le impostazioni precedenti", - "{k} delas foram analisadas com as definições anteriores do motor", - "Ulardan {k} tasi dvigatelning avvalgi sozlamalari bilan tahlil qilingan", - "Олардың {k} қозғалтқыштың бұрынғы баптауларымен талданған", - ], - [ - "In {k} games the player was not found by name: their moves did not count", - "В {k} партиях игрок не найден по имени — их ходы не считались", - "Dans {k} parties le joueur n’a pas été trouvé par son nom : leurs coups ne comptent pas", - "In {k} Partien wurde der Spieler nicht am Namen erkannt: ihre Züge zählen nicht", - "En {k} partidas no se encontró al jugador por el nombre: sus jugadas no cuentan", - "In {k} partite il giocatore non è stato trovato per nome: le loro mosse non contano", - "Em {k} partidas o jogador não foi encontrado pelo nome: os seus lances não contam", - "{k} ta partiyada o‘yinchi nomi bo‘yicha topilmadi — ularning yurishlari hisoblanmadi", - "{k} партияда ойыншы аты бойынша табылмады — олардың жүрістері есептелмеді", - ], - [ - "{k} games are not reviewed: «Continue» reviews only them", - "{k} партий не разобраны — «Продолжить» разберёт только их", - "{k} parties ne sont pas analysées : « Continuer » n’analyse qu’elles", - "{k} Partien sind nicht analysiert: «Fortsetzen» analysiert nur sie", - "{k} partidas sin analizar: «Continuar» analiza solo esas", - "{k} partite non analizzate: «Continua» analizza solo quelle", - "{k} partidas não analisadas: «Continuar» analisa só essas", - "{k} ta partiya tahlil qilinmagan — «Davom etish» faqat ularni tahlil qiladi", - "{k} партия талданбаған — «Жалғастыру» тек соларды талдайды", - ], - [ - "Average accuracy", - "Средняя точность", - "Précision moyenne", - "Durchschnittliche Genauigkeit", - "Precisión media", - "Precisione media", - "Precisão média", - "O‘rtacha aniqlik", - "Орташа дәлдік", - ], - [ - "Average over {k}: from {min}% to {max}%", - "Среднее по {k}: от {min}% до {max}%", - "Moyenne sur {k} : de {min} % à {max} %", - "Durchschnitt über {k}: von {min} % bis {max} %", - "Media de {k}: del {min} % al {max} %", - "Media su {k}: dal {min}% al {max}%", - "Média de {k}: de {min}% a {max}%", - "{k} bo‘yicha o‘rtacha: {min}% dan {max}% gacha", - "{k} бойынша орташа: {min}%-дан {max}%-ға дейін", - ], - [ - "No brilliant moves. Games with ! — sort by the «!!» column", - "Блестящих ходов нет. Партии с ! — сортировка по колонке «!!»", - "Aucun coup brillant. Parties avec ! — tri par la colonne « !! »", - "Keine brillanten Züge. Partien mit ! — nach der Spalte «!!» sortieren", - "Sin jugadas brillantes. Partidas con ! — ordenar por la columna «!!»", - "Nessuna mossa brillante. Partite con ! — ordina per la colonna «!!»", - "Sem lances brilhantes. Partidas com ! — ordenar pela coluna «!!»", - "Ajoyib yurishlar yo‘q. ! li partiyalar — «!!» ustuni bo‘yicha saralash", - "Керемет жүрістер жоқ. ! бар партиялар — «!!» бағаны бойынша сұрыптау", - ], - [ - "Sort", - "Отсортировать", - "Trier", - "Sortieren", - "Ordenar", - "Ordina", - "Ordenar", - "Saralash", - "Сұрыптау", - ], - [ - "No brilliant or great moves", - "Блестящих и замечательных ходов нет", - "Aucun coup brillant ou très bon", - "Keine brillanten oder starken Züge", - "Sin jugadas brillantes ni notables", - "Nessuna mossa brillante o notevole", - "Sem lances brilhantes ou notáveis", - "Ajoyib va zo‘r yurishlar yo‘q", - "Керемет және тамаша жүрістер жоқ", - ], - [ - "Games with !! ({n})", - "Партии с !! ({n})", - "Parties avec !! ({n})", - "Partien mit !! ({n})", - "Partidas con !! ({n})", - "Partite con !! ({n})", - "Partidas com !! ({n})", - "!! li partiyalar ({n})", - "!! бар партиялар ({n})", - ], - [ - "Click: choose the row in the table; double click: open at this move", - "Щелчок — выбрать строку в таблице, двойной щелчок — открыть на этом ходе", - "Clic : choisir la ligne dans le tableau ; double clic : ouvrir à ce coup", - "Klick: Zeile in der Tabelle wählen; Doppelklick: bei diesem Zug öffnen", - "Clic: elegir la fila en la tabla; doble clic: abrir en esta jugada", - "Clic: scegli la riga nella tabella; doppio clic: apri a questa mossa", - "Clique: escolher a linha na tabela; duplo clique: abrir neste lance", - "Bosish — jadvalda qatorni tanlash, ikki marta bosish — shu yurishda ochish", - "Шерту — кестеде жолды таңдау, екі рет шерту — осы жүрісте ашу", - ], - [ - "Open game", - "Открыть партию", - "Ouvrir la partie", - "Partie öffnen", - "Abrir partida", - "Apri partita", - "Abrir partida", - "Partiyani ochish", - "Партияны ашу", - ], - [ - "Stockfish installed — the search for great moves started", - "Stockfish установлен — поиск замечательных ходов начат", - "Stockfish installé — la recherche de très bons coups a commencé", - "Stockfish installiert — die Suche nach starken Zügen läuft", - "Stockfish instalado: la búsqueda de jugadas notables ha empezado", - "Stockfish installato — la ricerca di mosse notevoli è iniziata", - "Stockfish instalado — a pesquisa de lances notáveis começou", - "Stockfish o‘rnatildi — ajoyib yurishlarni qidirish boshlandi", - "Stockfish орнатылды — тамаша жүрістерді іздеу басталды", - ], - [ - "The search for great moves will start by itself when the download finishes.", - "Поиск замечательных ходов начнётся сам, когда загрузка закончится.", - "La recherche de très bons coups commencera d’elle-même à la fin du téléchargement.", - "Die Suche nach starken Zügen beginnt von selbst, wenn der Download fertig ist.", - "La búsqueda de jugadas notables empezará sola cuando termine la descarga.", - "La ricerca di mosse notevoli partirà da sola al termine del download.", - "A pesquisa de lances notáveis começa sozinha quando a transferência terminar.", - "Yuklab olish tugagach, ajoyib yurishlarni qidirish o‘zi boshlanadi.", - "Жүктеу аяқталғанда тамаша жүрістерді іздеу өзі басталады.", - ], - [ - "A game against the engine waits until the search for great moves ends.", - "Игра с движком подождёт, пока идёт поиск замечательных ходов.", - "Une partie contre le moteur attend la fin de la recherche de très bons coups.", - "Eine Partie gegen die Engine wartet, bis die Suche nach starken Zügen endet.", - "Una partida contra el motor espera a que termine la búsqueda de jugadas notables.", - "Una partita contro il motore attende la fine della ricerca di mosse notevoli.", - "Uma partida contra o motor espera pelo fim da pesquisa de lances notáveis.", - "Ajoyib yurishlar qidiruvi tugaguncha dvigatel bilan o‘yin kutadi.", - "Тамаша жүрістерді іздеу аяқталғанша қозғалтқышпен ойын күтеді.", - ], - [ - "matching: {list}", - "по условиям: {list}", - "selon : {list}", - "nach: {list}", - "según: {list}", - "secondo: {list}", - "segundo: {list}", - "shartlar: {list}", - "шарттар: {list}", - ], - [ - "less than a minute", - "меньше минуты", - "moins d’une minute", - "weniger als eine Minute", - "menos de un minuto", - "meno di un minuto", - "menos de um minuto", - "bir daqiqadan kam", - "бір минуттан аз", - ], - [ - "about {n} min", - "примерно {n} мин", - "environ {n} min", - "etwa {n} Min.", - "unos {n} min", - "circa {n} min", - "cerca de {n} min", - "taxminan {n} daq", - "шамамен {n} мин", - ], - [ - "about {h} h {m} min", - "примерно {h} ч {m} мин", - "environ {h} h {m} min", - "etwa {h} Std. {m} Min.", - "unas {h} h {m} min", - "circa {h} h {m} min", - "cerca de {h} h {m} min", - "taxminan {h} soat {m} daq", - "шамамен {h} сағ {m} мин", - ], - [ - "the engine did not start", - "движок не запустился", - "le moteur n’a pas démarré", - "die Engine ist nicht gestartet", - "el motor no arrancó", - "il motore non è partito", - "o motor não arrancou", - "dvigatel ishga tushmadi", - "қозғалтқыш іске қосылмады", - ], - [ - "the engine stopped answering", - "движок перестал отвечать", - "le moteur ne répond plus", - "die Engine antwortet nicht mehr", - "el motor dejó de responder", - "il motore ha smesso di rispondere", - "o motor deixou de responder", - "dvigatel javob bermay qo‘ydi", - "қозғалтқыш жауап бермей қалды", - ], - [ - "The engine will review {games} — {time}.", - "Движок разберёт {games} — {time}.", - "Le moteur analysera {games} : {time}.", - "Die Engine analysiert {games}: {time}.", - "El motor analizará {games}: {time}.", - "Il motore analizzerà {games}: {time}.", - "O motor vai analisar {games}: {time}.", - "Dvigatel {games}ni tahlil qiladi — {time}.", - "Қозғалтқыш {games} талдайды — {time}.", - ], - [ - "{games} is already reviewed: its marks come from the saved review.", - "{games} уже разобрана: её отметки возьмутся из сохранённого разбора.", - "{games} est déjà analysée : ses marques viennent de l’analyse enregistrée.", - "{games} ist bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", - "{games} ya está analizada: sus marcas salen del análisis guardado.", - "{games} è già analizzata: i suoi segni vengono dall’analisi salvata.", - "{games} já está analisada: as suas marcas vêm da análise guardada.", - "{games} allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", - "{games} талданып қойған: белгілері сақталған талдаудан алынады.", - ], - [ - "{games} are already reviewed: their marks come from the saved review.", - "{games} уже разобраны: их отметки возьмутся из сохранённого разбора.", - "{games} sont déjà analysées : leurs marques viennent de l’analyse enregistrée.", - "{games} sind bereits analysiert: ihre Markierungen kommen aus der gespeicherten Analyse.", - "{games} ya están analizadas: sus marcas salen del análisis guardado.", - "{games} sono già analizzate: i loro segni vengono dall’analisi salvata.", - "{games} já estão analisadas: as suas marcas vêm da análise guardada.", - "{games} allaqachon tahlil qilingan: belgilari saqlangan tahlildan olinadi.", - "{games} талданып қойған: белгілері сақталған талдаудан алынады.", - ], - [ - "Search stopped · reviewed: {i} of {n} game", - "Поиск остановлен · разобрана: {i} из {n}", - "Recherche arrêtée · analysée : {i} sur {n}", - "Suche angehalten · analysiert: {i} von {n}", - "Búsqueda detenida · analizada: {i} de {n}", - "Ricerca fermata · analizzata: {i} di {n}", - "Pesquisa parada · analisada: {i} de {n}", - "Qidiruv to‘xtatildi · tahlil qilindi: {n} dan {i}", - "Іздеу тоқтатылды · талданды: {n} ішінен {i}", - ], - [ - "{k} cannot be reviewed ({reason})", - "{k} нельзя разобрать ({reason})", - "{k} ne peuvent pas être analysées ({reason})", - "{k} können nicht analysiert werden ({reason})", - "{k} no se pueden analizar ({reason})", - "{k} non si possono analizzare ({reason})", - "{k} não podem ser analisadas ({reason})", - "{k} tasini tahlil qilib bo‘lmaydi ({reason})", - "{k} талдауға болмайды ({reason})", - ], - [ - "Wait: counting how many selected games are hidden by the current filter", - "Подождите — считаю, сколько выделенных партий скрыто текущим фильтром", - "Patientez : comptage des parties sélectionnées masquées par le filtre actuel", - "Bitte warten: ausgewählte, vom aktuellen Filter verborgene Partien werden gezählt", - "Espere: contando las partidas seleccionadas ocultas por el filtro actual", - "Attendi: conteggio delle partite selezionate nascoste dal filtro attuale", - "Aguarde: contando as partidas selecionadas ocultas pelo filtro atual", - "Kuting — joriy filtr yashirgan tanlangan partiyalar soni hisoblanmoqda", - "Күтіңіз — ағымдағы сүзгі жасырған таңдалған партиялар саны есептелуде", - ], - [ - "Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)", - "Выбрано: {games}. Разобрать их движком и отметить !! и ! (Shift+A)", - "Sélection : {games}. Analysez-les avec le moteur et marquez les !! et ! (Maj+A)", - "Ausgewählt: {games}. Mit der Engine analysieren und !! und ! markieren (Umschalt+A)", - "Seleccionadas: {games}. Analízalas con el motor y marca !! y ! (Mayús+A)", - "Selezionate: {games}. Analizzale con il motore e segna !! e ! (Maiusc+A)", - "Selecionadas: {games}. Analise-as com o motor e marque !! e ! (Shift+A)", - "Tanlangan: {games}. Ularni dvigatel bilan tahlil qilib, !! va ! ni belgilang (Shift+A)", - "Таңдалды: {games}. Оларды қозғалтқышпен талдап, !! және ! белгілеңіз (Shift+A)", - ], - [ - "{k} hidden by the current filter; these games are included too.", - "Скрыто текущим фильтром: {k}; эти партии тоже входят.", - "{k} masquées par le filtre actuel ; ces parties sont incluses aussi.", - "{k} vom aktuellen Filter verborgen; diese Partien sind ebenfalls enthalten.", - "{k} ocultas por el filtro actual; estas partidas también se incluyen.", - "{k} nascoste dal filtro attuale; anche queste partite sono incluse.", - "{k} ocultas pelo filtro atual; estas partidas também estão incluídas.", - "Joriy filtr {k} tasini yashirdi; bu partiyalar ham kiradi.", - "Ағымдағы сүзгі {k} партияны жасырды; олар да кіреді.", - ], - [ - "The filter does not change this run's games.", - "Фильтр не меняет состав этого запуска.", - "Le filtre ne change pas les parties de ce lancement.", - "Der Filter ändert die Partien dieses Laufs nicht.", - "El filtro no cambia las partidas de este análisis.", - "Il filtro non cambia le partite di questa analisi.", - "O filtro não altera as partidas desta análise.", - "Filtr bu ishga tushirishdagi partiyalarni o‘zgartirmaydi.", - "Сүзгі бұл іске қосудғы партияларды өзгертпейді.", - ], - [ - "Selected: {games} — more than 100.", - "Выбрано: {games} — больше 100.", - "Sélection : {games} — plus de 100.", - "Ausgewählt: {games} — mehr als 100.", - "Seleccionadas: {games} — más de 100.", - "Selezionate: {games} — più di 100.", - "Selecionadas: {games} — mais de 100.", - "Tanlangan: {games} — 100 tadan ko‘p.", - "Таңдалды: {games} — 100-ден астам.", - ], - [ - "Keep no more than 100 selected; the filter is not used.", - "Оставьте не больше 100 выделенных; фильтр не используется.", - "Gardez au plus 100 parties sélectionnées ; le filtre n’est pas utilisé.", - "Behalten Sie höchstens 100 ausgewählte Partien; der Filter wird nicht verwendet.", - "Deje no más de 100 seleccionadas; el filtro no se usa.", - "Mantieni non più di 100 selezionate; il filtro non viene usato.", - "Mantenha no máximo 100 selecionadas; o filtro não é usado.", - "100 tadan oshiq tanlangan partiya qoldirmang; filtr ishlatilmaydi.", - "100-ден артық таңдалған партия қалдырмаңыз; сүзгі қолданылмайды.", - ], - [ - "Source: selected {games}; hidden by the filter at start: {k}.", - "Источник: выбранные {games}; скрыто фильтром при запуске: {k}.", - "Source : {games} sélectionnées ; masquées par le filtre au lancement : {k}.", - "Quelle: {games} ausgewählt; beim Start vom Filter verborgen: {k}.", - "Origen: {games} seleccionadas; ocultas por el filtro al iniciar: {k}.", - "Origine: {games} selezionate; nascoste dal filtro all'avvio: {k}.", - "Origem: {games} selecionadas; ocultas pelo filtro no início: {k}.", - "Manba: tanlangan {games}; boshlang‘ichda filtr yashirganni: {k}.", - "Көз: таңдалған {games}; басында сүзгі жасырғаны: {k}.", - ], - [ - "Source: selected {games}.", - "Источник: выбранные {games}.", - "Source : {games} sélectionnées.", - "Quelle: {games} ausgewählt.", - "Origen: {games} seleccionadas.", - "Origine: {games} selezionate.", - "Origem: {games} selecionadas.", - "Manba: tanlangan {games}.", - "Көз: таңдалған {games}.", - ], - [ - "Selection and filter changes do not change this pass.", - "Изменения выделения и фильтра не меняют этот проход.", - "Les changements de sélection et de filtre ne modifient pas ce passage.", - "Änderungen an Auswahl und Filter ändern diesen Durchlauf nicht.", - "Los cambios de selección y filtro no cambian este recorrido.", - "Le modifiche a selezione e filtro non cambiano questa analisi.", - "As alterações de seleção e filtro não mudam esta passagem.", - "Tanlov va filtr o‘zgarishlari bu o‘tishni o‘zgartirmaydi.", - "Таңдау мен сүзгі өзгерістері бұл өтуді өзгертпейді.", - ], - [ - "Selected: {games}", - "Выбрано: {games}", - "Sélection : {games}", - "Ausgewählt: {games}", - "Seleccionadas: {games}", - "Selezionate: {games}", - "Selecionadas: {games}", - "Tanlangan: {games}", - "Таңдалды: {games}", - ], - [ - "{k} hidden by the current filter", - "{k} скрыто текущим фильтром", - "{k} masquées par le filtre actuel", - "{k} vom aktuellen Filter verborgen", - "{k} ocultas por el filtro actual", - "{k} nascoste dal filtro attuale", - "{k} ocultas pelo filtro atual", - "Joriy filtr {k} tasini yashirdi", - "Ағымдағы сүзгі {k} партияны жасырды", - ], - [ - "Only the moves of «{name}» count.", - "Считаются только ходы игрока «{name}».", - "Seuls les coups de « {name} » comptent.", - "Nur die Züge von «{name}» zählen.", - "Solo cuentan las jugadas de «{name}».", - "Contano solo le mosse di «{name}».", - "Só contam os lances de «{name}».", - "Faqat «{name}» yurishlari hisoblanadi.", - "Тек «{name}» жүрістері есептеледі.", - ], - [ - "Only the moves of «{name}» as White count.", - "Считаются только ходы игрока «{name}» белыми.", - "Seuls les coups de « {name} » avec les Blancs comptent.", - "Nur die Züge von «{name}» mit Weiß zählen.", - "Solo cuentan las jugadas de «{name}» con blancas.", - "Contano solo le mosse di «{name}» col Bianco.", - "Só contam os lances de «{name}» de brancas.", - "Faqat «{name}» ning oq bilan yurishlari hisoblanadi.", - "Тек «{name}» ақпен жүрген жүрістері есептеледі.", - ], - [ - "Only the moves of «{name}» as Black count.", - "Считаются только ходы игрока «{name}» чёрными.", - "Seuls les coups de « {name} » avec les Noirs comptent.", - "Nur die Züge von «{name}» mit Schwarz zählen.", - "Solo cuentan las jugadas de «{name}» con negras.", - "Contano solo le mosse di «{name}» col Nero.", - "Só contam os lances de «{name}» de pretas.", - "Faqat «{name}» ning qora bilan yurishlari hisoblanadi.", - "Тек «{name}» қарамен жүрген жүрістері есептеледі.", - ], - [ - "The player condition limits the moves counted, but does not exclude selected games from review.", - "Условие игрока ограничивает считаемые ходы, но не исключает выбранные партии из разбора.", - "La condition du joueur limite les coups comptés, mais n’exclut pas les parties sélectionnées de l’analyse.", - "Die Spielerbedingung begrenzt die gezählten Züge, schließt ausgewählte Partien aber nicht aus der Analyse aus.", - "La condición del jugador limita las jugadas contadas, pero no excluye las partidas seleccionadas del análisis.", - "La condizione del giocatore limita le mosse contate, ma non esclude le partite selezionate dall'analisi.", - "A condição do jogador limita os lances contados, mas não exclui as partidas selecionadas da análise.", - "O‘yinchi sharti hisoblanadigan yurishlarni cheklaydi, ammo tanlangan partiyalarni tahlildan chiqarmaydi.", - "Ойыншы шарты есептелетін жүрістерді шектейді, бірақ таңдалған партияларды талдаудан шығармайды.", - ], - [ - "Hidden by the filter at start: {k}", - "Скрыто фильтром при запуске: {k}", - "Masquées par le filtre au lancement : {k}", - "Beim Start vom Filter verborgen: {k}", - "Ocultas por el filtro al iniciar: {k}", - "Nascoste dal filtro all'avvio: {k}", - "Ocultas pelo filtro no início: {k}", - "Boshlang‘ichda filtr yashirganni: {k}", - "Басында сүзгі жасырғаны: {k}", - ], ]; #[cfg(test)] @@ -21001,17 +13799,9 @@ mod tests { include_str!("translate_ui.rs"), include_str!("chatgpt.rs"), include_str!("san.rs"), - include_str!("prep_ui.rs"), - include_str!("opening_layout.rs"), - include_str!("opening_lines.rs"), - include_str!("opening_session.rs"), - include_str!("repertoire_ui.rs"), - include_str!("batch_copy.rs"), - include_str!("brilliant.rs"), - include_str!("brilliant_ui.rs"), ]; let mut chars = std::collections::BTreeSet::new(); - for row in ROWS.iter() { + for row in ROWS { for text in row.iter() { chars.extend(text.chars()); } @@ -21080,13 +13870,6 @@ mod tests { include_str!("translate_ui.rs"), include_str!("chatgpt.rs"), include_str!("san.rs"), - include_str!("prep_ui.rs"), - include_str!("opening_layout.rs"), - include_str!("opening_lines.rs"), - include_str!("opening_session.rs"), - include_str!("repertoire_ui.rs"), - include_str!("brilliant.rs"), - include_str!("brilliant_ui.rs"), ]; let mut missing = Vec::new(); let mut found = 0; @@ -21132,7 +13915,7 @@ mod tests { #[test] fn rows_are_unique_and_complete() { let mut seen = std::collections::HashSet::new(); - for row in ROWS.iter() { + for row in ROWS { assert!(seen.insert(row[0]), "duplicate key {}", row[0]); assert!( row.iter().all(|s| !s.is_empty()), diff --git a/apps/desktop/src/large_db.rs b/apps/desktop/src/large_db.rs index 8719113..c0a2dfc 100644 --- a/apps/desktop/src/large_db.rs +++ b/apps/desktop/src/large_db.rs @@ -22,7 +22,6 @@ use shakmaty::uci::UciMove; use crate::board_search::{self, Background, BoardEvent, SearchBoard}; use crate::i18n::{tr, trf}; use crate::library::LibraryAction; -use crate::prep_ui::PrepEntry; use crate::settings::Settings; use crate::viewed::{self, Viewed}; @@ -193,8 +192,6 @@ pub struct Header { pub format_hint: String, /// A database downloaded from Lichess and Chess.com: its "⟳ New games". pub online: Option, - /// A file the browser holds only for this visit: "Keep a copy in the browser". - pub keep_copy: bool, } pub struct OnlineButton { @@ -278,30 +275,6 @@ struct Suggestions { highlighted: Option, } -/// The search for great moves under way, as the conditions line shows it. -#[derive(Clone, Debug, PartialEq)] -pub struct PassStatus { - /// In this database (else in `name`). - pub here: bool, - pub name: String, - pub selected: Option, - pub done: usize, - pub total: usize, - /// The record being analysed. - pub current: Option, - pub left_secs: f64, - pub stopping: bool, -} - -/// A copy of chosen records being written, as the conditions line shows it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct BatchStatus { - pub name: String, - pub done: usize, - pub total: usize, - pub cancelling: bool, -} - /// State of one large database in the library (kept for the session). pub struct LargeView { form: Form, @@ -331,53 +304,8 @@ pub struct LargeView { suggestions: Option, /// The pointer is on the open suggestion list. pointer_on_list: bool, - /// Record index of the row under the keyboard cursor: Enter, F2 and «Board» take it. + /// Record index of the selected row. pub selected: Option, - /// The records chosen (task 42): one or many, kept across filters and sorting. - marked: crate::batch_copy::Selection, - /// Where a Shift range starts. - anchor: Option, - /// Changes of `marked` and of `view`, and the chosen records the list hides then. - marked_gen: u64, - view_gen: u64, - hidden: Option<(u64, u64, usize)>, - /// The copy of chosen records being written (set by the library each frame). - pub batch: Option, - /// «Cancel» of that copy was clicked. - pub cancel_batch: bool, - /// Why the last copy wrote nothing: said in red where its progress was, until `×`. - pub batch_error: Option, - /// The chosen records as the file had them before it was read again (a hash of - /// each one's bytes), to know they are still the same games; `None` for a choice too - /// large to check (it is let go when the file changes). - marked_before: Option>, - /// Said once (a toast), taken by the library. - pub notice: Option, - /// The marks of the records found by the search for great moves (task 27), set by - /// the library; what the table shows of them, checked against each record's main - /// line, by record, for the index's generation. - pub marks: Option>>, - shown_marks: std::cell::RefCell<(u64, HashMap>)>, - /// The table sorted by the «!!» column. - marks_sort: bool, - /// The database the marks are checked against (set by `table`). - marks_db: Option>, - /// The texts of the conditions of the list (for the search's question). - last_conditions: Vec, - /// Whose moves the «!!» column counts: the filter's player's (found in the background - /// for that filter), else both sides'. - marks_sides: (Option, crate::brilliant::Sides), - sides_job: Option<(Filter, Receiver)>, - /// The search under way (here or in another database), set by the library. - pub pass: Option, - /// Why the search cannot start now (the engine is busy), set by the app. - pub engine_busy: Option, - /// Why the last search stopped with an error, in red where its progress was. - pub pass_error: Option, - /// «Stop» of the search was clicked. - pub stop_pass: bool, - /// «!! Find great moves» was clicked (taken by `table`, which has the path). - find_clicked: bool, scroll_to_selected: bool, scroll_to_top: bool, focus_player: bool, @@ -407,11 +335,6 @@ pub struct LargeView { drawer_top: f32, /// The quick search has the keyboard (arrows and Enter go to the table). search_focused: bool, - /// «Prepare against…» was asked (the panel's button, a row's menu): the library - /// takes it (docs/design/opponent-prep.md §2.1). - pub prepare: Option, - /// The web page of the game whose context menu is open (its record, the link). - menu_link: Option<(usize, Option)>, } impl LargeView { @@ -455,21 +378,6 @@ impl LargeView { } let drawer = pane_env.as_deref() == Some("drawer"); // `CP_SORT=date`: newest games first (screenshots). - // `CP_SELECT=3,7,15`: these records (their numbers in the table) chosen, the - // cursor on the last (screenshots of task 42). - let mut marked = crate::batch_copy::Selection::default(); - let mut cursor = None; - if let Ok(list) = std::env::var("CP_SELECT") { - for n in list - .split(',') - .filter_map(|n| n.trim().parse::().ok()) - { - if n > 0 { - marked.insert(n - 1); - cursor = Some(n - 1); - } - } - } let sort = if std::env::var("CP_SORT").as_deref() == Ok("date") { (SortKey::Date, false) } else { @@ -494,29 +402,7 @@ impl LargeView { suggest_job: None, suggestions: None, pointer_on_list: false, - selected: cursor, - marked, - anchor: cursor, - marked_gen: 0, - view_gen: 0, - hidden: None, - batch: None, - cancel_batch: false, - batch_error: None, - marked_before: None, - notice: None, - marks: None, - shown_marks: std::cell::RefCell::new((u64::MAX, HashMap::new())), - marks_sort: false, - marks_db: None, - last_conditions: Vec::new(), - marks_sides: (None, Default::default()), - sides_job: None, - pass: None, - engine_busy: None, - pass_error: None, - stop_pass: false, - find_clicked: false, + selected: None, scroll_to_selected: false, scroll_to_top: false, focus_player: false, @@ -533,8 +419,6 @@ impl LargeView { drawer_open: drawer, drawer_asked: false, drawer_top: 0.0, - prepare: None, - menu_link: None, } } @@ -560,409 +444,14 @@ impl LargeView { self.cache.clear(); self.blocked = None; self.books = db.books(); - self.shown_marks.borrow_mut().1.clear(); - // Several chosen: kept only if each is still the same record (a game added at - // the end keeps them; one deleted or put back moves the numbers). Otherwise let - // go, and said: the choice never moves to other games unnoticed. - if self.marked.len() >= 2 { - let same = std::mem::take(&mut self.marked_before).is_some_and(|before| { - before.len() == self.marked.len() - && before - .iter() - .all(|&(r, h)| (r as usize) < db.len() && record_hash(db, r as usize) == h) - }); - if !same { - self.clear_marks(); - self.notice = Some(tr("Selection cleared: the database changed").to_owned()); - } - } else if self.marked.last().is_some_and(|r| r >= db.len()) { - self.mark(|m| m.clear()); - } - self.selected = self.selected.filter(|&c| c < db.len()); } - /// Before the file is read again: what the chosen records are now (up to - /// `CHECKED_CHOICE` of them). - pub fn before_reread(&mut self, db: &Database) { - self.marked_before = - (self.marked.len() >= 2 && self.marked.len() <= CHECKED_CHOICE).then(|| { - self.marked - .records() - .into_iter() - .map(|r| (r, record_hash(db, r as usize))) - .collect() - }); - } - - /// Selects a record and scrolls to it (returning from a game): a choice of several - /// records stays. + /// Selects a record and scrolls to it (returning from a game). pub fn reveal(&mut self, index: usize) { self.selected = Some(index); - if self.marked.len() <= 1 { - self.mark(|m| m.only(index)); - } self.scroll_to_selected = true; } - /// Changes the chosen records. - fn mark(&mut self, change: impl FnOnce(&mut crate::batch_copy::Selection)) { - change(&mut self.marked); - self.marked_gen += 1; - } - - /// No record chosen any more. - pub fn clear_marks(&mut self) { - self.mark(|m| m.clear()); - self.anchor = None; - } - - /// The chosen records hidden by the list's filter, counted once per change. - fn hidden_marked(&mut self) -> usize { - let key = (self.marked_gen, self.view_gen); - match self.hidden { - Some((m, v, n)) if (m, v) == key => n, - _ => { - let n = self.marked.len() - self.marked.count_in(&self.view); - self.hidden = Some((key.0, key.1, n)); - n - } - } - } - - /// The choice comes down to the cursor's row (Esc, «Clear», a row deleted). - fn mark_cursor_only(&mut self) { - let cursor = self.selected; - self.mark(|m| match cursor { - Some(i) => m.only(i), - None => m.clear(), - }); - self.anchor = cursor; - } - - /// The records of the view from position `a` to position `b` (either order). - fn range(&self, a: usize, b: usize) -> &[u32] { - let (lo, hi) = (a.min(b), a.max(b)); - &self.view[lo..=hi.min(self.view.len().saturating_sub(1))] - } - - fn position_of(&self, record: usize) -> Option { - self.view.iter().position(|&i| i as usize == record) - } - - /// The cursor cannot stay on a record hidden by a new filter. Its mark can: marked - /// records are a separate selection, including a single hidden record. - fn clear_hidden_cursor(&mut self) { - if self - .selected - .is_some_and(|sel| !self.view.contains(&(sel as u32))) - { - self.selected = None; - } - } - - /// A click on the row of `index` with `mods` (§42.5). - fn click(&mut self, index: usize, mods: egui::Modifiers) { - // An anchor hidden by the filter: the cursor, when it is seen, starts the range. - let anchor = self - .anchor - .filter(|a| self.position_of(*a).is_some()) - .or(self.selected.filter(|c| self.position_of(*c).is_some())); - let at = self.position_of(index); - match ( - mods.command, - mods.shift, - anchor.and_then(|a| self.position_of(a)), - at, - ) { - (add, true, Some(a), Some(b)) => { - let range = self.range(a, b).to_vec(); - self.mark(|m| { - if !add { - m.clear(); - } - m.extend(&range); - }); - } - (true, false, _, _) => { - self.mark(|m| m.toggle(index)); - self.anchor = Some(index); - } - _ => { - self.mark(|m| m.only(index)); - self.anchor = Some(index); - } - } - self.selected = Some(index); - } - - /// The filter's player's sides of each record, for the «!!» column: found again in - /// the background when the filter changes; both sides without a player. - fn update_marks_sides(&mut self, db: &Arc, ctx: &egui::Context) { - let filter = self.form.filter(); - if let Some((f, rx)) = &self.sides_job - && let Ok(sides) = rx.try_recv() - { - self.marks_sides = (Some(f.clone()), sides); - self.sides_job = None; - self.shown_marks.borrow_mut().1.clear(); - if self.marks_sort { - self.sort_by_marks(); - } - } - let wanted = self.marks_sides.0.as_ref() == Some(&filter) - || self.sides_job.as_ref().is_some_and(|(f, _)| *f == filter); - if wanted { - return; - } - if !filter.player.is_set() { - self.marks_sides = (Some(filter), Default::default()); - self.sides_job = None; - self.shown_marks.borrow_mut().1.clear(); - return; - } - let (tx, rx) = channel(); - let (db, f, ctx) = (db.clone(), filter.clone(), ctx.clone()); - let spawned = std::thread::Builder::new() - .name("marks-sides".into()) - .spawn(move || { - let sides = crate::brilliant::player_sides( - &db, - &f, - &std::sync::atomic::AtomicBool::new(false), - ); - let _ = tx.send(sides); - ctx.request_repaint(); - }); - if spawned.is_ok() { - self.sides_job = Some((filter, rx)); - } - } - - /// The database the marks are checked against. - pub fn set_marks_db(&mut self, db: &Arc) { - if !self.marks_db.as_ref().is_some_and(|d| Arc::ptr_eq(d, db)) { - self.marks_db = Some(db.clone()); - } - } - - /// The table sorted by its «!!» column (the summary's «Sort»). - pub fn sort_marks_on(&mut self) { - self.marks_sort = true; - self.sort_by_marks(); - } - - /// The list by its marks (!! first), each group in the order of its numbers. - fn sort_by_marks(&mut self) { - let Some(index) = self.marks.clone() else { - return; - }; - let Ok(index) = index.lock() else { - return; - }; - let sides = &self.marks_sides.1; - // Only the entries of the games the database has there now (a deleted game's - // marks are not its successor's). - let current: std::collections::HashSet = match &self.marks_db { - Some(db) => index - .records() - .filter(|&r| crate::brilliant::current_entry(&index, db, r).is_some()) - .collect(), - None => std::collections::HashSet::new(), - }; - self.view - .sort_by_key(|&r| (index.rank(r, sides, &|r| current.contains(&r)), r)); - self.view_gen += 1; - } - - /// The marks of record `index` to show: those of the index if the record still has - /// the main line they were found in (checked once per record and index change). - fn shown_mark( - marks: &Option>>, - shown: &std::cell::RefCell<(u64, HashMap>)>, - sides: &crate::brilliant::Sides, - db: &Database, - record: u32, - ) -> Option { - let index = marks.as_ref()?.lock().ok()?; - let mut shown = shown.borrow_mut(); - if index.generation != shown.0 { - shown.1.clear(); - shown.0 = index.generation; - } - let entry = index.get(record)?.clone(); - drop(index); - shown - .1 - .entry(record) - .or_insert_with(|| { - let game = db.load_game(record as usize)?.game; - let line = game_review::GameAnalysis::new(&game, None).cache_key(); - (entry.line == line).then_some(entry) - }) - .clone() - .map(|e| { - let (w, b) = sides.of(record); - e.for_sides(w, b) - }) - } - - /// «!! Find great moves» (the button, Shift+A): a choice of records takes priority - /// over the filtered list. Both are owned snapshots: later changes in the table do - /// not change the request already sent to the library. - fn ask_search(&mut self, path: &Path, db: &Database, actions: &mut Vec) { - let selected = self.selected_games(); - let (records, about) = if selected.is_none() { - let about = if self.last_conditions.is_empty() { - tr("all games").to_owned() - } else { - trf( - "matching: {list}", - &[("list", &self.last_conditions.join(" · "))], - ) - }; - (self.view.clone(), about) - } else { - let mut records = self.marked.records(); - let (sort, ascending) = if self.blocked.is_some() { - self.sort - } else { - self.effective_sort() - }; - db.sort_records(&mut records, sort, ascending); - (records, String::new()) - }; - actions.push(LibraryAction::FindGreatMoves { - path: path.to_path_buf(), - records, - filter: self.form.filter(), - about, - selected, - }); - } - - /// «!! Find great moves»: the button, or Shift+A outside a field (a disabled button - /// says why, also over an empty list). - fn handle_find( - &mut self, - ui: &mut Ui, - path: &Path, - db: &Database, - actions: &mut Vec, - ) { - if !crate::platform::CAPS.great_moves { - return; - } - let typing = ui.ctx().egui_wants_keyboard_input(); - let shift_a = !typing - && !crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) - && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::A)); - if std::mem::take(&mut self.find_clicked) || shift_a { - match (self.pass.is_some(), self.search_blocked()) { - (false, None) => self.ask_search(path, db, actions), - (false, Some(why)) => actions.push(LibraryAction::Notice(why)), - (true, _) => {} - } - } - } - - /// How many games a search asked for now would take: the whole choice when there - /// is one, otherwise the filtered list. - fn search_len(&self) -> usize { - if self.marked.is_empty() { - self.view.len() - } else { - self.marked.len() - } - } - - /// The manual source and its hidden count, captured from the finished current view. - fn selected_games(&mut self) -> Option { - if self.marked.is_empty() { - return None; - } - let games = self.marked.len(); - let hidden = self.hidden_marked(); - Some(crate::brilliant::SelectedGames { games, hidden }) - } - - /// Why the search cannot start on the choice or the list shown, if it cannot. - fn search_blocked(&self) -> Option { - if let Some(why) = &self.engine_busy { - return Some(why.clone()); - } - if let Some(p) = self.pass.as_ref().filter(|p| !p.here) { - return Some(trf( - "Searching in «{db}»: {i} of {n}; stop it there", - &[("db", &p.name), ("i", &p.done), ("n", &p.total)], - )); - } - // Overflow is known without k and takes priority over a filter still running. - if self.marked.len() > crate::brilliant::LIMIT { - return Some(selected_limit_hint(self.marked.len())); - } - // A valid choice also waits: its hidden count is not known before this view. - if self.job.is_some() || self.shown.is_none() { - return Some( - tr(if self.marked.is_empty() { - "Wait: the games are still being filtered" - } else { - "Wait: counting how many selected games are hidden by the current filter" - }) - .to_owned(), - ); - } - match crate::brilliant::can_start(self.search_len()) { - Ok(()) => None, - Err(crate::brilliant::Blocked::NoGames) => { - Some(tr("No games match these conditions").to_owned()) - } - Err(crate::brilliant::Blocked::TooMany) if !self.marked.is_empty() => { - Some(selected_limit_hint(self.marked.len())) - } - Err(crate::brilliant::Blocked::TooMany) => Some(format!( - "{}\n{}", - tr("Filter the games down to 100 or fewer"), - trf("Now: {n}", &[("n", &grouped(self.view.len()))]) - )), - } - } - - /// Every row of the list chosen (Ctrl+A): the list's records only. - fn select_all(&mut self) { - let view = std::mem::take(&mut self.view); - self.mark(|m| m.extend(&view)); - self.view = view; - if self.selected.is_none() { - self.selected = self.view.first().map(|&i| i as usize); - } - } - - /// «New database from selected…»: the library opens the dialog (none while another - /// copy is written). - fn ask_copy(&mut self, path: &Path, actions: &mut Vec) { - if self.batch.is_some() || !crate::platform::CAPS.batch_copy { - return; - } - let (records, sort, ascending) = self.copy_request(); - actions.push(LibraryAction::CopySelection { - path: path.to_path_buf(), - records, - sort, - ascending, - hidden: self.hidden_marked(), - }); - } - - /// The chosen records for a copy, in the table's order once sorted by the copy. - fn copy_request(&self) -> (Vec, SortKey, bool) { - let (sort, ascending) = if self.blocked.is_some() { - self.sort - } else { - self.effective_sort() - }; - (self.marked.records(), sort, ascending) - } - pub fn pane(&self) -> Pane { self.pane } @@ -1026,9 +515,6 @@ impl LargeView { } else if self.drawer().is_some() { self.drawer_open = false; true - } else if self.marked.len() >= 2 { - self.mark_cursor_only(); - true } else if self.board_alone() { self.pane = Pane::Hidden; true @@ -1127,19 +613,17 @@ impl LargeView { ); } self.view = answer.view; - self.view_gen += 1; - if self.marks_sort { - self.sort_by_marks(); - } self.outcome = answer.outcome; self.in_order = answer.in_order; self.blocked = answer.blocked; self.shown = Some(job.request); - // A cursor that left the list is cleared, so Enter cannot open a game - // the user does not see. The marked record itself stays, also when it - // is the only one: the search and copy include hidden chosen records. - if new_filter { - self.clear_hidden_cursor(); + // A selected game that left the list is no longer selected, so Enter + // cannot open a game the user does not see. + if let Some(sel) = self.selected + && new_filter + && !self.view.contains(&(sel as u32)) + { + self.selected = None; } if new_filter { // The user looks at the result of the new filter from its top. @@ -1332,6 +816,7 @@ impl LargeView { if let Some((b, work)) = &self.booster { let p = (b.progress() as f32 / (*work).max(1) as f32).min(1.0); ui.horizontal(|ui| { + ui.add(egui::Spinner::new().size(14.0)); ui.label( RichText::new(trf( "Speeding up search in this database (once)… {p} %", @@ -1479,10 +964,6 @@ impl LargeView { filters_shown, ), ] { - // The search by position is not in every version. - if pane == Pane::Board && !crate::platform::CAPS.reference { - continue; - } let hint = if on { tr("Hide the panel") } else { hint }; if ui.selectable_label(on, label).on_hover_text(hint).clicked() { match (pane, on) { @@ -1664,25 +1145,12 @@ impl LargeView { /// many games reached the position in the board's move order. fn chips(&mut self, ui: &mut Ui, settings: &Settings) { let conditions = self.conditions(settings); - self.last_conditions = conditions.iter().map(|c| c.text.clone()).collect(); let mut clear = None; let mut goto = None; let mut toggle_order = false; - let chosen = self.marked.len(); - let hidden = if chosen >= 2 { self.hidden_marked() } else { 0 }; - let batch = self.batch.clone(); - let batch_error = self.batch_error.clone(); - let mut close_error = false; - let mut clear_marked = false; - let mut cancel_batch = false; ui.horizontal(|ui| { ui.set_min_height(22.0); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Right to left (docs/design/task-27-brilliant-search-2026-11-27.md §4.1): - // the slot of the far right, the move order, the choice or its copy, the - // conditions. The far right slot keeps one width whatever it shows, so what - // stands left of it does not move when it changes. - self.right_slot(ui); if let Some((same, all)) = self.in_order && self.board.is_set() && (same < all || self.only_order) @@ -1710,79 +1178,6 @@ impl LargeView { ); } } - // The choice, or the copy being written, in the same place (§42.3). - if batch.is_some() || batch_error.is_some() || chosen >= 2 { - ui.add_space(SLOT_GAP); - } - if let (None, Some(e)) = (&batch, &batch_error) { - if crate::widgets::small_close_button(ui).clicked() { - close_error = true; - } - let width = (ui.available_width() - 140.0).max(80.0); - ui.scope(|ui| { - ui.set_max_width(width); - ui.add( - egui::Label::new(RichText::new(e).color(ui.visuals().error_fg_color)) - .truncate(), - ) - .on_hover_text(e); - }); - } else if let Some(b) = &batch { - if b.cancelling { - ui.spinner(); - ui.label(RichText::new(tr("Cancelling…")).weak()); - } else { - if ui.link(tr("Cancel")).clicked() { - cancel_batch = true; - } - let fraction = b.done as f32 / b.total.max(1) as f32; - ui.add(egui::ProgressBar::new(fraction).desired_width(80.0).desired_height(8.0)); - ui.label( - RichText::new(trf( - "Writing to «{name}»: {i} of {n}", - &[("name", &b.name), ("i", &grouped(b.done)), ("n", &grouped(b.total))], - )) - .weak(), - ); - } - } else if chosen >= 2 { - if ui - .link(tr("Deselect")) - .on_hover_text(tr("Clear the selection (Esc)")) - .clicked() - { - clear_marked = true; - } - let full = if hidden > 0 { - trf( - "Selected: {n} ({k} hidden by the filter)", - &[("n", &grouped(chosen)), ("k", &grouped(hidden))], - ) - } else { - trf("Selected: {n}", &[("n", &grouped(chosen))]) - }; - // Short in a narrow line: the conditions keep their 140 px. - let short = ui.available_width() - < 140.0 + ui.fonts_mut(|f| { - f.layout_no_wrap( - full.clone(), - egui::TextStyle::Body.resolve(ui.style()), - Color32::WHITE, - ) - .size() - .x - }) + 16.0; - let text = if short { format!("{} ·", grouped(chosen)) } else { format!("{full} ·") }; - let label = ui.label(text); - if hidden > 0 { - label.on_hover_text(format!( - "{full}\n{}", - tr("Games hidden by the filter will be copied too. Esc clears the selection") - )); - } else if short { - label.on_hover_text(full); - } - } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { if conditions.is_empty() { ui.label(RichText::new(tr("No conditions: all games are shown")).weak()); @@ -1817,15 +1212,6 @@ impl LargeView { if toggle_order { self.only_order = !self.only_order; } - if clear_marked { - self.mark_cursor_only(); - } - if close_error { - self.batch_error = None; - } - if cancel_batch { - self.cancel_batch = true; - } if let Some(c) = clear { self.clear(c); } @@ -1836,200 +1222,6 @@ impl LargeView { } } - /// The far right slot of the conditions line: «!! Find great moves», or the search - /// under way with «Stop», or why it stopped (task 27 §4.1–4.2). Its width is that of - /// its longest form for the line's width, whatever it shows: what stands left of it - /// never moves. - fn right_slot(&mut self, ui: &mut Ui) { - if !crate::platform::CAPS.great_moves { - return; - } - let line = ui.available_width(); - let form = if line >= 1100.0 { - 2 - } else if line >= 800.0 { - 1 - } else { - 0 - }; - let body = egui::TextStyle::Body.resolve(ui.style()); - let width = |text: &str| { - ui.fonts_mut(|f| { - f.layout_no_wrap(text.to_owned(), body.clone(), Color32::WHITE) - .size() - .x - }) - }; - let progress_text = |i: usize, n: usize, left: &str| match form { - 2 => format!( - "!! {}", - trf( - "Analysed {i} of {n} · ≈ {time} left", - &[("i", &i), ("n", &n), ("time", &left)] - ) - ), - 1 => format!( - "!! {} · ≈ {left}", - trf("{i} of {n}", &[("i", &i), ("n", &n)]) - ), - _ => format!("!! {}", trf("{i} of {n}", &[("i", &i), ("n", &n)])), - }; - let bar = if form == 2 { 90.0 } else { 60.0 }; - let pad = 2.0 * ui.spacing().button_padding.x; - let gap = ui.spacing().item_spacing.x; - let button_text = if form == 0 { - tr("!! Find moves") - } else { - tr("!! Find great moves") - }; - let longest = width(&progress_text( - 100, - 100, - &crate::review::format_duration(59.0 * 60.0), - )) + gap - + bar - + gap - + width(tr("Stop")) - + pad; - let slot = longest.max(width(button_text) + pad); - let pass = self.pass.clone(); - let selected = if self.job.is_none() && self.shown.is_some() { - self.selected_games() - } else { - None - }; - let blocked = self.search_blocked(); - let error = self.pass_error.clone(); - let mut find = false; - let mut stop = false; - let mut close_error = false; - ui.allocate_ui_with_layout( - vec2(slot, 22.0), - egui::Layout::right_to_left(egui::Align::Center), - |ui| { - ui.set_min_width(slot); - match (&pass, &error) { - (Some(p), _) => { - if p.stopping { - ui.spinner(); - ui.label(RichText::new(tr("Stopping…")).weak()); - } else { - if ui - .small_button(tr("Stop")) - .on_hover_text(tr("Stop the search; the reviewed games are kept")) - .clicked() - { - stop = true; - } - ui.add( - egui::ProgressBar::new(p.done as f32 / p.total.max(1) as f32) - .desired_width(bar) - .desired_height(8.0), - ); - let left = crate::review::format_duration(p.left_secs); - let text = if p.here { - progress_text(p.done, p.total, &left) - } else { - format!( - "!! {}", - trf( - "In «{db}»: {i} of {n}", - &[("db", &p.name), ("i", &p.done), ("n", &p.total)] - ) - ) - }; - let mut hint = String::new(); - if let Some(selected) = p.selected { - if selected.hidden > 0 { - hint.push_str(&trf( - "Source: selected {games}; hidden by the filter at start: {k}.", - &[ - ("games", &crate::i18n::games(selected.games)), - ("k", &grouped(selected.hidden)), - ], - )); - } else { - hint.push_str(&trf( - "Source: selected {games}.", - &[("games", &crate::i18n::games(selected.games))], - )); - } - hint.push('\n'); - hint.push_str(tr( - "Selection and filter changes do not change this pass.", - )); - hint.push('\n'); - } - hint.push_str(&trf( - "Analysed {i} of {n} · ≈ {time} left", - &[("i", &p.done), ("n", &p.total), ("time", &left)], - )); - ui.add(egui::Label::new(RichText::new(text).weak()).truncate()) - .on_hover_text(hint); - } - } - (None, Some(e)) => { - if crate::widgets::small_close_button(ui).clicked() { - close_error = true; - } - ui.add( - egui::Label::new(RichText::new(e).color(ui.visuals().error_fg_color)) - .truncate(), - ) - .on_hover_text(e); - } - (None, None) => { - let teal = crate::notation::assessment_text_color( - chess_core::Nag(3), - ui.visuals().dark_mode, - ) - .unwrap_or(Color32::WHITE); - let mut job = egui::text::LayoutJob::default(); - let rest = button_text.strip_prefix("!! ").unwrap_or(button_text); - let bold = egui::FontId::new(13.0, egui::FontFamily::Name("bold".into())); - let bold = if ui.fonts_mut(|f| f.families().contains(&bold.family)) { - bold - } else { - body.clone() - }; - job.append("!! ", 0.0, egui::TextFormat::simple(bold, teal)); - // The button's own text colour (it lightens under the pointer). - job.append( - rest, - 0.0, - egui::TextFormat::simple(body.clone(), Color32::PLACEHOLDER), - ); - let enabled = blocked.is_none(); - let r = ui.add_enabled(enabled, egui::Button::new(job).small()); - let r = match &blocked { - Some(why) => r.on_disabled_hover_text(why), - None => r.on_hover_text(match selected { - Some(selected) => selected_search_hint(selected), - None => trf( - "Review {games} with the engine and mark the !! and ! moves found (Shift+A)", - &[("games", &crate::i18n::games(self.search_len()))], - ), - }), - }; - if r.clicked() { - find = true; - } - } - } - }, - ); - ui.add_space(SLOT_GAP); - if find { - self.find_clicked = true; - } - if stop { - self.stop_pass = true; - } - if close_error { - self.pass_error = None; - } - } - /// The filter panel (an `egui::Panel` on the right of the library). pub fn panel(&mut self, ui: &mut Ui, db: &Arc) { self.update(db, ui.ctx()); @@ -2105,39 +1297,9 @@ impl LargeView { .response .on_disabled_hover_text(tr("Enter a player first")); }); - // Preparing against the player: with the name picked from the list, else the - // dialog offers the names that match the text (opponent-prep.md §2.1). - if player_set { - let label = match self.form.player.exact { - Some(_) => trf( - "♟ Prepare against {name}…", - &[("name", &self.form.player.text)], - ), - None => tr("♟ Prepare against an opponent…").to_owned(), - }; - if ui - .add(egui::Button::new(label).truncate()) - .on_hover_text(tr( - "The player's openings by colour, with names, and the opening errors the engine finds (Ctrl+Shift+P)", - )) - .clicked() - { - self.prepare = self.prep_entry(); - } - } self.name_field(ui, db, NameField::Opponent, tr("Opponent")); } - /// «Prepare against…» for the player of the filter: the name picked from the list - /// (or the text typed) and the colour of the filter. - pub fn prep_entry(&self) -> Option { - self.form.player.is_set().then(|| PrepEntry { - query: self.form.player.text.trim().to_owned(), - exact: self.form.player.exact, - side: self.form.side, - }) - } - fn event_group(&mut self, ui: &mut Ui, db: &Arc) { let count = usize::from(self.form.event.is_set()) + usize::from(!self.form.annotator.trim().is_empty()); @@ -2498,7 +1660,7 @@ impl LargeView { .weak(), ); ui.add_space(6.0); - ui.label(RichText::new(trf("File: {path}", &[("path", &crate::platform::files::shown(path))])).weak()); + ui.label(RichText::new(trf("File: {path}", &[("path", &path.display())])).weak()); }); return open_notes; } @@ -2632,22 +1794,16 @@ impl LargeView { ui.label(text); } if let Some(p) = progress { + ui.add(egui::Spinner::new().size(14.0)); ui.label(RichText::new(format!("{:.0} %", p * 100.0)).weak()); } if notes > 0 && crate::widgets::notes_button(ui, notes).clicked() { open_notes = true; } - if header.keep_copy - && ui - .add(egui::Button::new(tr("📋 Keep a copy in the browser")).small()) - .on_hover_text(tr("The copy opens right away, without choosing the file. It is stored in this browser on this device and is lost if you clear the site's data. The file on disk is not changed.")) - .clicked() - { - actions.push(LibraryAction::KeepCopy(path.to_path_buf())); - } // A database from Lichess and Chess.com: its new games. if let Some(online) = &header.online { if online.busy { + ui.add(egui::Spinner::new().size(14.0)); ui.label(RichText::new(tr("updating…")).weak()); } else if ui .add_enabled(online.enabled, egui::Button::new(tr("⟳ New games")).small()) @@ -2655,7 +1811,6 @@ impl LargeView { .on_disabled_hover_text(&online.hint) .clicked() { - #[cfg(not(web))] actions.push(LibraryAction::UpdateOnline(path.to_path_buf())); } } @@ -2722,9 +1877,7 @@ impl LargeView { self.focus_search = true; } } - if crate::platform::CAPS.reference - && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) - { + if ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::B)) { self.pane = Pane::Board; } // Ctrl+Shift+Backspace: all conditions, the quick search and the position included. @@ -2814,55 +1967,10 @@ impl LargeView { } } }); - // Shift+A on an empty list still says why nothing can be searched. - self.handle_find(ui, path, db, actions); return open_notes; } - self.handle_find(ui, path, db, actions); - self.update_marks_sides(db, ui.ctx()); - // `CP_MARKS_DEMO=1`: made-up marks for the first rows (screenshots of the column). - if std::env::var_os("CP_MARKS_DEMO").is_some() - && self.shown.is_some() - && self.job.is_none() - && let Some(marks) = self.marks.clone() - { - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| demo_marks(db, &self.view, &marks)); - } - // `CP_BRILLIANT_RUN=1`: the search asked for once the list is there. - if std::env::var_os("CP_BRILLIANT_RUN").is_some() - && self.shown.is_some() - && self.job.is_none() - && self.search_blocked().is_none() - { - static ONCE: std::sync::Once = std::sync::Once::new(); - let mut first = false; - ONCE.call_once(|| first = true); - if first { - self.ask_search(path, db, actions); - } - } - // Records the database does not have (`CP_SELECT` on a short one) are not chosen. - if self.marked.last().is_some_and(|r| r >= db.len()) { - let len = db.len(); - self.mark(|m| m.retain_below(len)); - self.selected = self.selected.filter(|&c| c < len); - } self.keyboard(ui, path, actions); - // `CP_BATCH=new:`: the chosen records copied into a new database once the - // list is there (screenshots, checks). - if std::env::var("CP_BATCH").is_ok_and(|b| b.starts_with("new:")) - && !self.marked.is_empty() - && !self.view.is_empty() - { - static ONCE: std::sync::Once = std::sync::Once::new(); - let mut first = false; - ONCE.call_once(|| first = true); - if first { - self.ask_copy(path, actions); - } - } let scroll_row = if std::mem::take(&mut self.scroll_to_selected) { self.selected @@ -2902,8 +2010,6 @@ impl LargeView { (tr("Black"), Some(SortKey::Black), name), ("Elo", Some(SortKey::BlackElo), Column::exact(ELO_COL)), (tr("Res."), Some(SortKey::Result), Column::exact(RESULT_COL)), - // The marks of the search for great moves: in every layout (task 27 §4.3). - ("!!", None, Column::exact(MARKS_COL)), ]); if show_moves { columns.push((tr("Length"), Some(SortKey::Moves), Column::exact(56.0))); @@ -2945,9 +2051,6 @@ impl LargeView { year_only, use_position, ); - let frame_color = ui.visuals().selection.stroke.color; - let table_clip = ui.clip_rect().intersect(ui.max_rect()); - let spacing = ui.spacing().item_spacing; let mut table = TableBuilder::new(ui) .id_salt(("game table", layout)) .striped(true) @@ -2965,22 +2068,8 @@ impl LargeView { let mut opened = None; let mut toggle_viewed = None; let mut hovered = None; - let marks_sorted = self.marks_sort; - let mut marks_click = false; - let pass_current = self - .pass - .as_ref() - .filter(|p| p.here) - .and_then(|p| p.current); - let (marks_ref, shown_ref, sides_ref) = - (&self.marks, &self.shown_marks, &self.marks_sides.1); let view = &self.view; let selected = self.selected; - let marked = &self.marked; - let many = marked.len() >= 2; - let batch_running = self.batch.as_ref().map(|b| b.name.clone()); - let mut batch_menu = None; - let mut secondary = None; // A position not applied (no memory) does not sort: the arrow shows the view's own order. let sort = if self.blocked.is_some() { self.sort @@ -3005,16 +2094,16 @@ impl LargeView { .header(26.0, |mut header| { for (label, key, _) in &columns { header.col(|ui| { - if *label == "!!" { - let r = crate::widgets::sort_header(ui, label, marks_sorted.then_some(true)) - .on_hover_text(tr("Brilliant and great moves found by the engine: sort by them")); - if r.clicked() { - marks_click = true; + let arrow = match key { + Some(k) if sort.0 == *k => { + if sort.1 { " ⏶" } else { " ⏷" } } - return; - } - let active = key.filter(|k| sort.0 == *k && !marks_sorted).map(|_| sort.1); - let r = crate::widgets::sort_header(ui, label, active); + _ => "", + }; + let r = ui.add( + egui::Button::new(RichText::new(format!("{label}{arrow}")).strong()) + .frame(false), + ); if let Some(k) = key && r.clicked() { @@ -3030,10 +2119,7 @@ impl LargeView { }; let index = index as usize; let r = db.row(index); - let is_marked = marked.contains(index); - row.set_selected(is_marked); - // Where the row's cells are: the cursor's frame follows the row's fill. - let mut cells = egui::Rect::NOTHING; + row.set_selected(selected == Some(index)); let key = viewed::key(db.identity(index)); let seen = viewed.contains(key); let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() }; @@ -3046,7 +2132,6 @@ impl LargeView { }; for (label, key_, _) in &columns { row.col(|ui| { - cells = cells.union(ui.max_rect()); let cell = match (*label, *key_) { (l, None) if l == tr("Move") => { let Some(m) = found else { return }; @@ -3082,10 +2167,6 @@ impl LargeView { (_, Some(SortKey::Black)) => RichText::new(r.black.as_str()), (_, Some(SortKey::BlackElo)) => RichText::new(elo(r.black_elo)), (_, Some(SortKey::Result)) => RichText::new(result), - ("!!", None) => { - marks_cell(ui, Self::shown_mark(marks_ref, shown_ref, sides_ref, db, index as u32), pass_current == Some(index as u32), is_marked); - return; - } (_, Some(SortKey::Moves)) => RichText::new(match r.moves { 0 => String::new(), 255 => "255+".into(), @@ -3129,82 +2210,12 @@ impl LargeView { .filter(|t| !t.trim().is_empty() && *t != "?" && !t.contains("://")) .collect(); let resp = row.response(); - // The cursor among several chosen rows, or on a row not chosen: a frame - // (a shape, not a colour; §42.4). - if selected == Some(index) && (many || !is_marked) { - ui_painter_frame(&resp, cells.expand2(spacing / 2.0), frame_color, table_clip); - } let resp = if about.is_empty() { resp } else { resp.on_hover_text(about.join(" · ")) }; - if resp.secondary_clicked() { - secondary = Some(index); - } - // Several chosen and this one among them: the menu of the choice. - if many && is_marked { - resp.context_menu(|ui| { - if let Some(item) = batch_items(ui, marked.len(), batch_running.as_deref()) { - batch_menu = Some(item); - ui.close(); - } - }); - } else { resp.context_menu(|ui| { if ui.button(tr("Open")).clicked() { opened = Some(index); ui.close(); } - // The first !! (else !) the search found: the game at it. - if let Some(f) = Self::shown_mark(marks_ref, shown_ref, sides_ref, db, index as u32) - .and_then(|e| { - let first = e.found.iter().find(|f| f.brilliant).or(e.found.first()); - first.cloned() - }) - && ui - .button(trf("Open at {move}", &[("move", &f.label())])) - .clicked() - { - let at = db.load_game(index).and_then(|p| { - let node = *p.game.mainline().get(f.ply as usize)?; - Some(p.game.node(node)?.position().clone()) - }); - actions.push(LibraryAction::OpenGameReport { - path: path.to_path_buf(), - index, - at, - }); - ui.close(); - } - // The game's page, when its tags have one (read once per menu). - if self.menu_link.as_ref().is_none_or(|(i, _)| *i != index) { - let link = db.load_game(index).and_then(|p| { - crate::game_link::of(|t| p.game.tag(t).map(str::to_owned)) - }); - self.menu_link = Some((index, link)); - } - if let Some((_, Some(link))) = &self.menu_link - && ui.button(link.label()).clicked() - { - ui.ctx().open_url(egui::OpenUrl::new_tab(link.at(0, false))); - ui.close(); - } - // One item per player of the game (the same name once). - let mut players: Vec<&str> = vec![r.white.as_str(), r.black.as_str()]; - players.dedup(); - for name in players { - if name.trim().is_empty() || name == "?" { - continue; - } - if ui - .button(trf("♟ Prepare against {name}…", &[("name", &name)])) - .clicked() - { - self.prepare = Some(PrepEntry { - query: name.to_owned(), - exact: None, - side: Side::Any, - }); - ui.close(); - } - } if ui.button(tr("Game data… (F2)")).clicked() { actions.push(LibraryAction::EditGameData { path: path.to_path_buf(), index }); ui.close(); @@ -3213,10 +2224,6 @@ impl LargeView { actions.push(LibraryAction::AddGameToDatabase { path: path.to_path_buf(), index }); ui.close(); } - if ui.button(tr("Select all (Ctrl+A)")).clicked() { - batch_menu = Some(BatchItem::SelectAll); - ui.close(); - } let label = if seen { tr("Mark as not viewed") } else { @@ -3234,7 +2241,6 @@ impl LargeView { } } }); - } if resp.hovered() { hovered = Some(index); } @@ -3255,17 +2261,7 @@ impl LargeView { if let Some((k, v)) = toggle_viewed { viewed.set(k, v); } - if marks_click { - self.marks_sort = !self.marks_sort; - if self.marks_sort { - self.sort_by_marks(); - } else { - // The list comes again in the sort of its columns. - self.shown = None; - } - } if let Some(k) = sort_click { - self.marks_sort = false; let current = self.effective_sort(); self.sort = if current.0 == k { (k, !current.1) @@ -3276,20 +2272,7 @@ impl LargeView { self.typed_at = f64::NEG_INFINITY; } if let Some(i) = clicked { - let mods = ui.input(|i| i.modifiers); - self.click(i, mods); - } - // A right click on a row not chosen chooses it alone. - if let Some(i) = secondary - && !(self.marked.len() >= 2 && self.marked.contains(i)) - { - self.click(i, egui::Modifiers::NONE); - } - match batch_menu { - Some(BatchItem::NewBase) => self.ask_copy(path, actions), - Some(BatchItem::SelectAll) => self.select_all(), - Some(BatchItem::Clear) => self.mark_cursor_only(), - None => {} + self.selected = Some(i); } if let Some(index) = opened { self.selected = Some(index); @@ -3302,10 +2285,7 @@ impl LargeView { open_notes } - /// Up/Down move the cursor, Page Up/Down by a page, Home/End to the ends, Enter - /// opens. Without a modifier the choice follows the cursor, Shift chooses the range - /// from the anchor, Ctrl moves the cursor alone; Ctrl+Space toggles its row, Ctrl+A - /// chooses the whole list (§42.6). + /// Up/Down move the selection, Page Up/Down by a page, Enter opens. fn keyboard(&mut self, ui: &mut Ui, path: &Path, actions: &mut Vec) { // In a filter field the arrows still move through the table (unless the // suggestions are open), but Enter belongs to the field. @@ -3313,49 +2293,17 @@ impl LargeView { if typing && self.suggestions.is_some() { return; } - // A question or a menu over the table takes the keys (Enter there is its button, - // not «open the game»). - if crate::app::overlay_open_besides(ui.ctx(), &[egui::Id::new("filters_drawer")]) { - return; - } - let (up, down, page_up, page_down, enter, mods) = ui.input(|i| { + let (up, down, page_up, page_down, enter) = ui.input(|i| { ( i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::PageUp), i.key_pressed(egui::Key::PageDown), i.key_pressed(egui::Key::Enter), - i.modifiers, ) }); - let (home, end) = if typing { - (false, false) - } else { - ui.input(|i| { - ( - i.key_pressed(egui::Key::Home), - i.key_pressed(egui::Key::End), - ) - }) - }; - if !typing { - let (all, toggle) = ui.input_mut(|i| { - ( - i.consume_key(egui::Modifiers::COMMAND, egui::Key::A), - i.consume_key(egui::Modifiers::COMMAND, egui::Key::Space), - ) - }); - if all { - self.select_all(); - } - if toggle && let Some(c) = self.selected { - self.mark(|m| m.toggle(c)); - self.anchor = Some(c); - } - } - // The cursor's record: F2 opens it with its data, Ctrl+Shift+S adds a copy of it - // to another database (several chosen: a new database of them), Delete removes - // it (a question first; never while several are chosen). + // The selected record: F2 opens it with its data, Ctrl+Shift+S adds a copy of it + // to another database, Delete removes it (a question first). if !typing && let Some(index) = self.selected { let (data, add, delete) = ui.input_mut(|i| { ( @@ -3367,7 +2315,6 @@ impl LargeView { i.consume_key(egui::Modifiers::NONE, egui::Key::Delete), ) }); - let many = self.marked.len() >= 2; let p = path.to_path_buf(); if data { actions.push(LibraryAction::EditGameData { @@ -3375,57 +2322,32 @@ impl LargeView { index, }); } - if add && many { - self.ask_copy(path, actions); - } else if add { + if add { actions.push(LibraryAction::AddGameToDatabase { path: p.clone(), index, }); } - if delete && many { - actions.push(LibraryAction::Notice( - tr("Games are deleted one at a time: clear the selection (Esc)").to_owned(), - )); - } else if delete { - // Also for a database that takes no games: the app says why. + // Also for a database that takes no games: the app says why. + if delete { actions.push(LibraryAction::DeleteGame { path: p, index }); } } // Enter belongs to a filter field, but in the quick search it opens the game. let enter = enter && (!typing || self.search_focused); let step = if page_up || page_down { 20 } else { 1 }; - if up || down || page_up || page_down || home || end { - let pos = self.selected.and_then(|r| self.position_of(r)); + if up || down || page_up || page_down { + let pos = self + .selected + .and_then(|r| self.view.iter().position(|&i| i as usize == r)); let last = self.view.len().saturating_sub(1); let next = match (pos, down || page_down) { - _ if home => 0, - _ if end => last, (None, _) => 0, (Some(p), true) => (p + step).min(last), (Some(p), false) => p.saturating_sub(step), }; if let Some(&i) = self.view.get(next) { - let i = i as usize; - if mods.shift { - let from = self - .anchor - .and_then(|a| self.position_of(a)) - .or(pos) - .unwrap_or(next); - if self.anchor.and_then(|a| self.position_of(a)).is_none() { - self.anchor = self.view.get(from).map(|&r| r as usize); - } - let range = self.range(from, next).to_vec(); - self.mark(|m| { - m.clear(); - m.extend(&range); - }); - } else if !mods.command { - self.mark(|m| m.only(i)); - self.anchor = Some(i); - } - self.selected = Some(i); + self.selected = Some(i as usize); self.scroll_to_selected = true; } } @@ -3444,234 +2366,6 @@ impl LargeView { } } -/// Up to this many chosen records are checked when their file is read again; a larger -/// choice is let go if the file changed. -const CHECKED_CHOICE: usize = 100_000; - -/// A hash of the bytes of record `index`. -fn record_hash(db: &Database, index: usize) -> u64 { - let mut h = std::collections::hash_map::DefaultHasher::new(); - db.identity(index).hash(&mut h); - h.finish() -} - -/// Space between the slots of the conditions line (`item_spacing.x` + 4). -const SLOT_GAP: f32 = 4.0; -/// The «!!» column. -const MARKS_COL: f32 = 28.0; - -/// An item of the menus about the chosen records. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum BatchItem { - NewBase, - SelectAll, - Clear, -} - -/// The menu of several chosen rows (§42.7): how many, the copy, select all, clear. The -/// copy waits while another one is written. -fn batch_items(ui: &mut Ui, n: usize, writing: Option<&str>) -> Option { - let mut out = None; - ui.label(RichText::new(trf("Games selected: {n}", &[("n", &grouped(n))])).weak()); - ui.separator(); - let copy = ui.add_enabled( - writing.is_none() && crate::platform::CAPS.batch_copy, - egui::Button::new(tr("New database from selected…")), - ); - let copy = match writing { - Some(name) => copy.on_disabled_hover_text(trf( - "Writing to «{name}» — wait until it finishes", - &[("name", &name)], - )), - None => copy, - }; - if copy.clicked() { - out = Some(BatchItem::NewBase); - } - ui.separator(); - if ui.button(tr("Select all (Ctrl+A)")).clicked() { - out = Some(BatchItem::SelectAll); - } - if ui.button(tr("Clear selection (Esc)")).clicked() { - out = Some(BatchItem::Clear); - } - out -} - -/// Made-up marks for the first rows of `view` (`CP_MARKS_DEMO`): !!, !, none, not -/// analysable, in turn; not saved. -fn demo_marks(db: &Database, view: &[u32], marks: &std::sync::Mutex) { - use crate::brilliant::{Counts, Entry, Found, SideMarks, Skip}; - let Ok(mut index) = marks.lock() else { - return; - }; - for (n, &r) in view.iter().take(8).enumerate() { - let Some(game) = db.load_game(r as usize).map(|p| p.game) else { - continue; - }; - let line = game_review::GameAnalysis::new(&game, None).cache_key(); - let side = |brilliant, great| SideMarks { - counts: Counts { - brilliant, - great, - ..Counts::default() - }, - acpl: Some(30), - accuracy: Some(85.0), - }; - let found = |brilliant| Found { - ply: 20, - white: true, - number: 11, - san: "Rxf7".into(), - brilliant, - }; - let entry = match n % 4 { - 0 => Entry { - line, - white: side(1, 0), - black: side(0, 0), - found: vec![found(true)], - stale: false, - skip: None, - }, - 1 => Entry { - line, - white: side(0, 2), - black: side(0, 0), - found: vec![found(false)], - stale: true, - skip: None, - }, - 2 => Entry { - line, - white: side(0, 0), - black: side(0, 0), - found: Vec::new(), - stale: false, - skip: None, - }, - _ => Entry { - line, - white: SideMarks::default(), - black: SideMarks::default(), - found: Vec::new(), - stale: false, - skip: Some(Skip::NullMove), - }, - }; - index.set(r, entry); - } -} - -/// The «!!» cell of a record (task 27 §4.3): !!, !, «·» analysed without them, «—» not -/// analysable, a spinner while analysed, nothing when not analysed. Signs, not colours -/// alone; on a chosen row in the text colour of the selection. -fn marks_cell(ui: &mut Ui, entry: Option, running: bool, chosen: bool) { - ui.with_layout( - egui::Layout::centered_and_justified(egui::Direction::LeftToRight), - |ui| { - if running { - ui.add(egui::Spinner::new().size(12.0)) - .on_hover_text(tr("Being reviewed…")); - return; - } - let Some(e) = entry else { - return; - }; - let dark = ui.visuals().dark_mode; - let tint = |nag: u8| { - if chosen { - ui.visuals().selection.stroke.color - } else { - crate::notation::assessment_text_color(chess_core::Nag(nag), dark) - .unwrap_or(ui.visuals().text_color()) - } - }; - let moves = |brilliant: bool| { - let list: Vec = e - .found - .iter() - .filter(|f| f.brilliant == brilliant) - .map(|f| f.label()) - .collect(); - let shown = list.iter().take(3).cloned().collect::>().join(", "); - if list.len() > 3 { - format!( - "{shown} {}", - trf("and {n} more", &[("n", &(list.len() - 3))]) - ) - } else { - shown - } - }; - let c = e.of_sides(true, true); - let (text, color, mut hint) = if let Some(skip) = e.skip { - ( - "—", - ui.visuals().weak_text_color(), - trf( - "Cannot be reviewed: {reason}", - &[("reason", &skip.reason())], - ), - ) - } else if c.brilliant > 0 || c.great > 0 { - let mut hint = Vec::new(); - if c.brilliant > 0 { - hint.push(trf( - "Brilliant moves: {n}: {moves}", - &[("n", &c.brilliant), ("moves", &moves(true))], - )); - } - if c.great > 0 { - hint.push(trf( - "Great moves: {n}: {moves}", - &[("n", &c.great), ("moves", &moves(false))], - )); - } - if c.brilliant > 0 { - ("!!", tint(3), hint.join("\n")) - } else { - ("!", tint(1), hint.join("\n")) - } - } else { - ( - "•", - ui.visuals().weak_text_color(), - tr("Reviewed: no brilliant or great moves").to_owned(), - ) - }; - if e.stale { - hint.push('\n'); - hint.push_str(tr("Reviewed with the previous engine settings")); - } - let color = if chosen { - ui.visuals().selection.stroke.color - } else { - color - }; - // Ubuntu-B, as the other signs of moves. - let bold = egui::FontId::new(13.0, egui::FontFamily::Name("bold".into())); - let font = if ui.fonts_mut(|f| f.families().contains(&bold.family)) { - bold - } else { - egui::FontId::proportional(13.0) - }; - ui.add(egui::Label::new(RichText::new(text).font(font).color(color)).selectable(false)) - .on_hover_text(hint); - }, - ); -} - -/// The keyboard cursor's frame: 1 px inside the row. -fn ui_painter_frame(row: &egui::Response, rect: egui::Rect, color: Color32, clip: egui::Rect) { - let stroke = Stroke::new(1.0, color); - row.ctx - .layer_painter(row.layer_id) - .with_clip_rect(clip) - .rect_stroke(rect.intersect(clip), 0.0, stroke, egui::StrokeKind::Inside); -} - /// A condition of the list, shown as a chip. struct Condition { text: String, @@ -3733,7 +2427,6 @@ 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, @@ -3869,36 +2562,6 @@ fn check_mark(ui: &mut Ui) { .line_segment([c + vec2(-1.0, 3.5), c + vec2(5.0, -4.0)], stroke); } -/// The active button's explanation of a manual source, including its hidden records. -fn selected_search_hint(selected: crate::brilliant::SelectedGames) -> String { - let mut hint = trf( - "Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)", - &[("games", &crate::i18n::games(selected.games))], - ); - hint.push('\n'); - if selected.hidden > 0 { - hint.push_str(&trf( - "{k} hidden by the current filter; these games are included too.", - &[("k", &grouped(selected.hidden))], - )); - } else { - hint.push_str(tr("The filter does not change this run's games.")); - } - hint -} - -/// More than 100 selected records: never fall back to a small enough filtered list. -fn selected_limit_hint(games: usize) -> String { - format!( - "{}\n{}", - trf( - "Selected: {games} — more than 100.", - &[("games", &crate::i18n::games(games))] - ), - tr("Keep no more than 100 selected; the filter is not used.") - ) -} - /// "11 741 260": thousands separated by a narrow space. pub fn grouped(n: usize) -> String { let digits = n.to_string(); @@ -3941,359 +2604,6 @@ fn new_game_hint(name: &str) -> String { mod tests { use super::*; - fn ctrl() -> egui::Modifiers { - egui::Modifiers::COMMAND - } - - fn shift() -> egui::Modifiers { - egui::Modifiers::SHIFT - } - - /// A view showing records 0..20 in the order 19, 18, … 0 (a sort). - fn table() -> LargeView { - let mut v = LargeView::new(); - v.view = (0..20).rev().collect(); - v - } - - /// A table whose filter has finished, so its search button can be evaluated. - fn ready_table() -> LargeView { - let mut v = table(); - let shown = v.request(); - v.shown = Some(shown); - v - } - - /// The owned request that the search button sends to the existing analysis path. - fn find_request( - v: &mut LargeView, - db: &Database, - ) -> (Vec, Option) { - let mut actions = Vec::new(); - v.ask_search(Path::new("/games.pgn"), db, &mut actions); - match actions.pop() { - Some(LibraryAction::FindGreatMoves { - records, selected, .. - }) => (records, selected), - _ => panic!("one great-moves request"), - } - } - - #[test] - fn clicks_choose_one_toggle_and_ranges_in_the_tables_order() { - let mut v = table(); - v.click(3, egui::Modifiers::NONE); - assert_eq!((v.marked.records(), v.selected), (vec![3], Some(3))); - v.click(7, ctrl()); - v.click(15, ctrl()); - assert_eq!(v.marked.records(), vec![3, 7, 15]); - v.click(7, ctrl()); - assert_eq!(v.marked.records(), vec![3, 15]); - // Shift: the range from the anchor (7, the last Ctrl click) in the table's order - // replaces the choice; Ctrl+Shift adds it. - v.click(10, shift()); - assert_eq!(v.marked.records(), vec![7, 8, 9, 10]); - v.click(1, ctrl()); - v.click(3, ctrl() | shift()); - assert_eq!(v.marked.records(), vec![1, 2, 3, 7, 8, 9, 10]); - v.click(5, egui::Modifiers::NONE); - assert_eq!(v.marked.records(), vec![5]); - } - - #[test] - fn an_anchor_hidden_by_the_filter_gives_way_to_the_cursor() { - let mut v = table(); - v.click(30, egui::Modifiers::NONE); - v.click(4, ctrl()); - v.anchor = Some(30); - v.click(6, shift()); - assert_eq!(v.marked.records(), vec![4, 5, 6]); - } - - #[test] - fn select_all_takes_the_list_and_escape_comes_back_to_the_cursor() { - let mut v = table(); - v.marked.insert(40); - v.click(40, ctrl()); - v.click(2, ctrl()); - v.select_all(); - assert_eq!(v.marked.len(), 20); - assert_eq!(v.hidden_marked(), 0); - v.marked.insert(40); - v.marked_gen += 1; - assert_eq!(v.hidden_marked(), 1); - assert!(v.escape()); - assert_eq!(v.marked.records(), vec![2]); - // One chosen: Escape is the next one's (here nobody's). - assert!(!v.escape()); - } - - #[test] - fn returning_from_a_game_keeps_a_choice_of_several() { - let mut v = table(); - v.click(1, egui::Modifiers::NONE); - v.reveal(9); - assert_eq!(v.marked.records(), vec![9]); - v.click(3, ctrl()); - v.reveal(3); - assert_eq!(v.marked.records(), vec![3, 9]); - } - - fn database(name: &str, games: &[&str]) -> Database { - let path = - std::env::temp_dir().join(format!("cp-reread-{}-{name}.pgn", std::process::id())); - let text: String = games - .iter() - .map(|w| format!("[White \"{w}\"]\n[Black \"x\"]\n[Result \"*\"]\n\n1. e4 *\n\n")) - .collect(); - std::fs::write(&path, text).unwrap(); - let db = chess_import::open( - &path, - &mut |_| {}, - &std::sync::atomic::AtomicBool::new(false), - ) - .unwrap() - .db; - let _ = std::fs::remove_file(&path); - db - } - - #[test] - fn a_choice_never_moves_to_other_games_when_the_file_is_read_again() { - let before = database("before", &["a", "b", "c", "d"]); - // A game added at the end: the chosen ones are the same records. - let mut v = table(); - v.click(1, egui::Modifiers::NONE); - v.click(2, ctrl()); - v.before_reread(&before); - v.reread(&database("added", &["a", "b", "c", "d", "e"])); - assert_eq!(v.marked.records(), vec![1, 2]); - assert!(v.notice.is_none()); - // A game put back at the start (undo of a delete): the numbers moved; let go, - // and said. - v.before_reread(&before); - v.reread(&database("undo", &["z", "a", "b", "c", "d"])); - assert!(v.marked.is_empty()); - assert!(v.notice.is_some()); - } - - #[test] - fn the_copy_asks_for_the_chosen_records_and_the_tables_sort() { - let mut v = table(); - v.sort = (SortKey::White, false); - v.click(5, egui::Modifiers::NONE); - v.click(2, ctrl()); - let mut actions = Vec::new(); - v.ask_copy(Path::new("/x.pgn"), &mut actions); - match actions.as_slice() { - [ - LibraryAction::CopySelection { - records, - sort, - ascending, - hidden, - .. - }, - ] => { - assert_eq!(records, &vec![2, 5]); - assert_eq!((*sort, *ascending, *hidden), (SortKey::White, false, 0)); - } - _ => panic!("one copy"), - } - // None while another copy is written. - v.batch = Some(BatchStatus { - name: "x".into(), - done: 0, - total: 1, - cancelling: false, - }); - actions.clear(); - v.ask_copy(Path::new("/x.pgn"), &mut actions); - assert!(actions.is_empty()); - } - - #[test] - fn the_search_limit_follows_the_choice_independently_of_the_filter() { - let mut v = ready_table(); - v.view = (0..101).collect(); - assert!( - v.search_blocked() - .is_some_and(|s| s.contains(tr("Filter the games down to 100 or fewer"))) - ); - - // One and one hundred selected games may start even when the filter has 101. - v.marked.only(0); - assert_eq!(v.search_len(), 1); - assert_eq!(v.search_blocked(), None); - v.marked.clear(); - for r in 0..100 { - v.marked.insert(r); - } - assert_eq!(v.search_len(), 100); - assert_eq!(v.search_blocked(), None); - v.marked.insert(100); - assert!(v.search_blocked().is_some_and(|s| s.contains(tr( - "Keep no more than 100 selected; the filter is not used." - )))); - - // The inverse: a small filtered list does not enable 101 selected games, and - // clearing that choice brings back the old filter behaviour. - v.clear_marks(); - v.view = vec![0]; - assert_eq!(v.search_blocked(), None); - for r in 0..101 { - v.marked.insert(r); - } - assert!(v.search_blocked().is_some_and(|s| s.contains(tr( - "Keep no more than 100 selected; the filter is not used." - )))); - v.clear_marks(); - assert_eq!(v.search_blocked(), None); - - // A selected game hidden by an empty filtered result is still a valid source. - v.view.clear(); - assert!( - v.search_blocked() - .is_some_and(|s| s.contains(tr("No games match these conditions"))) - ); - v.marked.only(0); - assert_eq!(v.search_blocked(), None); - v.marked.clear(); - for r in 0..100 { - v.marked.insert(r); - } - assert_eq!(v.search_len(), 100); - assert_eq!(v.search_blocked(), None); - - // Until the current view is ready, k is unknown for either source. Overflow is - // already known and takes priority over that wait. - v.shown = None; - v.marked.insert(100); - assert!(v.search_blocked().is_some_and(|s| s.contains(tr( - "Keep no more than 100 selected; the filter is not used." - )))); - v.marked.remove(100); - assert!(v.search_blocked().is_some_and(|s| s.contains(tr( - "Wait: counting how many selected games are hidden by the current filter" - )))); - v.clear_marks(); - assert!( - v.search_blocked() - .is_some_and(|s| s.contains(tr("Wait: the games are still being filtered"))) - ); - } - - #[test] - fn the_search_request_snapshots_exactly_the_selected_ids_including_hidden_ones() { - let db = database("search-source", &["a", "b", "c", "d"]); - let mut v = ready_table(); - v.view = vec![0, 2]; - - // No choice: the previous source, the filtered table, is unchanged. - let (filtered, selected) = find_request(&mut v, &db); - assert_eq!(filtered, vec![0, 2]); - assert_eq!(selected, None); - - // Inserting the same ID twice cannot duplicate it. Records 1 and 3 are hidden - // by the current table, but belong to the request just like visible record 0. - for r in [0, 1, 3, 1] { - v.marked.insert(r); - } - let (snapshot, selected) = find_request(&mut v, &db); - assert_eq!(snapshot, vec![0, 1, 3]); - assert_eq!( - selected, - Some(crate::brilliant::SelectedGames { - games: 3, - hidden: 2, - }) - ); - - // Later selection, filter and sort changes do not mutate the sent Vec. A new - // request after clearing the selection uses the new filtered table again. - v.sort = (SortKey::Date, false); - v.marked.only(2); - v.view = vec![2]; - assert_eq!(snapshot, vec![0, 1, 3]); - assert_eq!( - selected, - Some(crate::brilliant::SelectedGames { - games: 3, - hidden: 2, - }) - ); - v.clear_marks(); - let (next, _) = find_request(&mut v, &db); - assert_eq!(next, vec![2]); - } - - #[test] - fn a_single_hidden_mark_survives_the_cursor_reset() { - let mut v = ready_table(); - v.marked.only(0); - v.selected = Some(0); - v.view.clear(); - v.clear_hidden_cursor(); - assert_eq!(v.selected, None); - assert_eq!(v.marked.records(), vec![0]); - assert_eq!(v.search_blocked(), None); - } - - #[test] - fn escape_keeps_one_selected_game_as_the_search_source() { - let db = database("search-escape", &["a", "b", "c"]); - let mut v = ready_table(); - v.view = vec![0, 1, 2]; - v.click(0, egui::Modifiers::NONE); - v.click(1, ctrl()); - v.click(2, ctrl()); - assert!(v.escape()); - assert_eq!(v.marked.len(), 1); - let (one, _) = find_request(&mut v, &db); - assert_eq!(one, vec![2]); - - // The existing Ctrl+Space gesture can clear that last mark; only then does the - // command return to the filtered table. - v.marked.toggle(2); - assert!(v.marked.is_empty()); - let (filtered, _) = find_request(&mut v, &db); - assert_eq!(filtered, vec![0, 1, 2]); - } - - #[test] - fn selection_hints_explain_hidden_games_and_the_independent_limit() { - let selected = crate::brilliant::SelectedGames { - games: 3, - hidden: 2, - }; - assert_eq!( - selected_search_hint(selected), - format!( - "{}\n{}", - trf( - "Selected: {games}. Review them with the engine and mark !! and ! (Shift+A)", - &[("games", &crate::i18n::games(3))] - ), - trf( - "{k} hidden by the current filter; these games are included too.", - &[("k", &grouped(2))] - ) - ) - ); - assert!( - selected_search_hint(crate::brilliant::SelectedGames { - games: 1, - hidden: 0, - }) - .contains(tr("The filter does not change this run's games.")) - ); - let limit = selected_limit_hint(101); - assert!(limit.contains(&crate::i18n::games(101))); - assert!(limit.contains(tr( - "Keep no more than 100 selected; the filter is not used." - ))); - } - #[test] fn numbers_group_and_shorten() { assert_eq!(grouped(11_741_260), "11\u{202f}741\u{202f}260"); diff --git a/apps/desktop/src/lib.rs b/apps/desktop/src/lib.rs deleted file mode 100644 index 47362d9..0000000 --- a/apps/desktop/src/lib.rs +++ /dev/null @@ -1,203 +0,0 @@ -//! ChessPenguin's window: the library, the game, analysis, play, preparation. -//! -//! One interface for two platforms. The desktop program (`src/main.rs`) starts it in a -//! native window ([`run_native`]); the web version (`apps/web`) in a page's canvas -//! ([`start_web`]). What differs between them — files, background work, storage, -//! dialogs, the clipboard — is behind [`platform`]. Features a platform does not have -//! are not built for it (`cfg(web)`: WebAssembly in a browser, set by `build.rs`), or, -//! where the interface only needs to know, hidden by [`platform::CAPS`]. The web build -//! compiles parts of the interface it never shows: what is unused there is the desktop -//! build's to find (the platform layer, [`platform`], is checked in both). -// (A browser's `std::fs::File` has no destructor: dropping one there is no closing.) -#![cfg_attr(web, allow(unused, clippy::drop_non_drop))] - -mod adjourned; -mod analysis; -mod app; -mod assets; -mod batch_copy; -mod board; -mod board_search; -mod brilliant; -mod brilliant_ui; -mod chatgpt; -mod db_counts; -mod engine_download; -mod engine_offer; -mod engines; -mod examples; -mod file_state; -mod game_link; -mod game_view; -#[cfg(not(web))] -mod graphics; -mod i18n; -mod large_db; -mod library; -mod maia_download; -#[cfg(web)] -mod my_games; -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; -mod player_games; -mod prep_saved; -mod prep_ui; -mod reference; -#[cfg(not(web))] -mod repertoire_ui; -mod review; -mod review_engine; -mod rodent4_download; -mod rodent_download; -mod san; -mod settings; -mod settings_ui; -mod sound; -mod translate; -mod translate_ui; -#[cfg(not(web))] -mod update; -#[cfg(not(web))] -mod update_ui; -mod viewed; -mod widgets; - -/// Learning an opening: shared with the Android app. -use trainer as train; - -/// The web version in the page's `canvas`: the program's data is read from the -/// browser's storage first, then the interface starts. `lang`: the language the page -/// was opened in (`?lang=` of the site's link), over the one chosen before. -#[cfg(web)] -pub async fn start_web( - canvas: web_sys::HtmlCanvasElement, - lang: Option, -) -> Result<(), wasm_bindgen::JsValue> { - platform::web::vfs::load().await; - platform::web::remembered::restore().await; - platform::web::engine::probe().await; - platform::web::storage::refresh(|| {}); - let mut settings = settings::Settings::load(); - if let Some(chosen) = lang.as_deref().and_then(i18n::Lang::from_locale) - && chosen != settings.language - { - settings.language = chosen; - let _ = settings.save(); - } - i18n::set_lang(settings.language); - eframe::WebRunner::new() - .start( - canvas, - eframe::WebOptions::default(), - Box::new(|cc| { - assets::install(&cc.egui_ctx); - Ok(Box::new(app::App::new(&cc.egui_ctx))) - }), - ) - .await -} - -/// The page's reader (`import-worker.js`, a worker with an instance of its own): takes -/// the files of a database one by one ([`reader_give`]), reads it and answers with its -/// text and index, or only how many games it holds (`count`; `platform::web::import`). -#[cfg(web)] -pub fn reader_give(name: String, bytes: Vec) { - platform::web::import::give(name, bytes); -} - -#[cfg(web)] -pub fn reader_read(count: bool) -> wasm_bindgen::JsValue { - platform::web::import::answer(count) -} - -/// The desktop program: `chesspenguin [--bench [report.txt]]`. -#[cfg(not(web))] -pub fn run_native() -> eframe::Result { - // `chesspenguin --bench [report.txt]`: timings instead of the window - // (`docs/dev/import.md`, "Замер на другой машине"). - let args: Vec = std::env::args_os().skip(1).collect(); - if args.first().is_some_and(|a| a == "--bench") { - let Some(db) = args.get(1) else { - eprintln!("usage: chesspenguin --bench [report.txt]"); - std::process::exit(2); - }; - let cache = settings::Settings::cache_dir().map(|d| d.join("boosters")); - let result = match args.get(2) { - Some(file) => std::fs::File::create(file) - .and_then(|mut f| chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut f)), - None => chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut std::io::stdout()), - }; - if let Err(e) = result { - eprintln!("bench: {e}"); - std::process::exit(1); - } - return Ok(()); - } - crate::i18n::set_lang(settings::Settings::load().language); - // The runs of the opening trainer (`CP_TRAINING_FILE` elsewhere: development). - if let Some(file) = std::env::var_os("CP_TRAINING_FILE") - .map(std::path::PathBuf::from) - .or_else(|| { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.data_local_dir().join("training.json")) - }) - { - train::set_file(file); - } - graphics::install_panic_hook(); - graphics::init_library_log(); - let mode = graphics::choose(); - let mut viewport = egui::ViewportBuilder::default() - .with_app_id("io.github.vrubelroman.chessPenguin") - .with_title("ChessPenguin") - .with_inner_size([1400.0, 900.0]) - .with_min_inner_size([640.0, 480.0]) - // X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id. - .with_icon( - eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png")) - .unwrap_or_default(), - ); - if let Some((width, height)) = std::env::var("CP_SCREENSHOT_SIZE").ok().and_then(|size| { - let (width, height) = size.split_once('x')?; - Some((width.parse::().ok()?, height.parse::().ok()?)) - }) { - viewport = viewport - .with_inner_size([width, height]) - .with_min_inner_size([width, height]) - .with_max_inner_size([width, height]) - .with_resizable(false) - .with_fullscreen(false) - .with_maximized(false); - } - let options = eframe::NativeOptions { - viewport, - wgpu_options: graphics::options(mode), - ..Default::default() - }; - let result = eframe::run_native( - "ChessPenguin", - options, - Box::new(|cc| { - assets::install(&cc.egui_ctx); - Ok(Box::new(app::App::new(&cc.egui_ctx))) - }), - ); - if let Err(e) = &result { - if graphics::retry(&e.to_string()) { - return Ok(()); - } - graphics::fatal(&e.to_string()); - } - result -} diff --git a/apps/desktop/src/library.rs b/apps/desktop/src/library.rs index 85c51d3..ff7db1f 100644 --- a/apps/desktop/src/library.rs +++ b/apps/desktop/src/library.rs @@ -48,26 +48,12 @@ pub enum LibraryAction { PastePgn, AddDatabases, /// The window for downloading games from Lichess and Chess.com. - #[cfg(not(web))] OnlineGames, /// Fetch the new games of an online database. - #[cfg(not(web))] UpdateOnline(PathBuf), /// The window offering a newer version. - #[cfg(not(web))] OpenUpdate, RemoveDatabase(PathBuf), - /// A file the browser held for the last visit only: choose it again, the new one - /// taking its place on the shelf. - ChooseAgain(PathBuf), - /// Let the page read the remembered file again (the browser asks the user). - #[cfg(web)] - AllowReading(PathBuf), - /// Choose the folder of the ChessBase database whose `.cbh` alone is there. - #[cfg(web)] - ChooseFolderAgain(PathBuf), - /// Keep a copy of a file in the browser (it opens then without choosing it). - KeepCopy(PathBuf), OpenSettings, /// A new, empty PGN database (own-databases.md §2). NewDatabase, @@ -83,48 +69,10 @@ pub enum LibraryAction { path: PathBuf, index: usize, }, - /// «New database from selected…»: the chosen records (by number) of `path`, the - /// table's order, how many of them the filter hides (task 42). - CopySelection { - path: PathBuf, - records: Vec, - sort: chess_import::chessbase::base::SortKey, - ascending: bool, - hidden: usize, - }, - /// A short message (a toast). - Notice(String), - /// Open a game at the position `at` with its report shown (a move the search for - /// great moves found). - OpenGameReport { - path: PathBuf, - index: usize, - at: Option, - }, - /// «!! Find great moves» over the list `records` of `path` (in the table's order), - /// found by `filter` (task 27). - FindGreatMoves { - path: PathBuf, - records: Vec, - filter: chess_import::chessbase::base::Filter, - /// The conditions in words, for a filtered question and summary. - about: String, - /// The manual source and its hidden count, fixed with `records`. - selected: Option, - }, EditGameData { path: PathBuf, index: usize, }, - /// «🗐 Preparations»: the saved preparations against opponents. - Preparations, - #[cfg(not(web))] - OpeningTraining, - /// «Prepare against…» for a player of this database (opponent-prep.md §2). - PrepareAgainst { - path: PathBuf, - entry: crate::prep_ui::PrepEntry, - }, } /// How a database was imported, and what is worth knowing about it. @@ -150,25 +98,21 @@ fn button_w(ui: &Ui, text: &str) -> f32 { + ui.spacing().item_spacing.x } -// Toolbar contents change as background probes finish and the window narrows. -// Keep action IDs independent of the preceding widgets: egui buttons resolve -// their visual state from the previous frame's response before being allocated. -fn shelf_button(ui: &mut Ui, id: &str, label: impl Into) -> egui::Response { - ui.push_id(id, |ui| ui.button(label)).inner -} - /// A PGN file whose beginning is in a legacy (single-byte) encoding: it takes games only /// through a UTF-8 copy. For a file not read yet (its card's menu). fn legacy_pgn(path: &Path) -> bool { + use std::io::Read; let pgn = path .extension() .is_some_and(|e| e.to_string_lossy().eq_ignore_ascii_case("pgn")); if !pgn || crate::online::is_online(path) || crate::examples::is_example(path) { return false; } - let Ok(head) = crate::platform::fs::read_head(path, 64 << 10) else { + let mut head = Vec::with_capacity(64 << 10); + let read = std::fs::File::open(path).and_then(|f| f.take(64 << 10).read_to_end(&mut head)); + if read.is_err() { return false; - }; + } let guess = chess_core::detect_encoding(&head); guess.encoding != chess_core::TextEncoding::Utf8 && !guess.ascii_only } @@ -187,33 +131,9 @@ fn shelf_buttons_w(ui: &Ui, update: Option<&str>, icons: bool) -> f32 { tr("♞ Play"), ] }; - let play = crate::platform::CAPS.play; - let prep = crate::platform::CAPS.prep; - let training = crate::platform::CAPS.training; - let groups = 1.0 + f32::from(u8::from(play)) + f32::from(u8::from(prep || training)); - texts[..if play { 4 } else { 3 }] - .iter() - .map(|t| button_w(ui, t)) - .sum::() - + if prep { - button_w( - ui, - if icons { - "🗐" - } else { - tr("🗐 Preparations") - }, - ) - } else { - 0.0 - } - + if training { - button_w(ui, tr("Opening training (α version)")) - } else { - 0.0 - } + texts.iter().map(|t| button_w(ui, t)).sum::() + update.map_or(0.0, |v| button_w(ui, v)) - + groups * GROUP_GAP + + 2.0 * GROUP_GAP } /// A shelf button's tooltip: with icons only, its name first. @@ -282,8 +202,7 @@ pub struct Library { /// Database whose import notes are shown. notes_open: Option, pub selected_db: Option, - /// Network probe availability for updating an existing online database. - /// The main toolbar is always available according to platform capabilities. + /// Lichess or Chess.com answered at start (the online games are offered). pub online: bool, /// Online databases being downloaded or updated. pub online_busy: Vec, @@ -295,39 +214,6 @@ pub struct Library { pub aside: Option, /// The games of the databases not opened, for their cards. counts: crate::db_counts::Counts, - /// Chosen records being copied into a new database (one copy at a time). - batch: Option, - /// The marks of great moves of each database (task 27), read once per session. - marks: HashMap>>, - /// The search for great moves under way (one engine job in the program). - pub pass: Option, -} - -/// A copy of chosen records into a new database, written in the background. -struct BatchJob { - source: PathBuf, - target: PathBuf, - total: usize, - work: crate::board_search::Background< - Result, - >, - cancelling: bool, -} - -/// How a copy of chosen records ended. -pub enum BatchEnd { - Done { - target: PathBuf, - report: crate::batch_copy::CopyReport, - }, - Cancelled { - target: PathBuf, - }, - Failed { - source: PathBuf, - target: PathBuf, - error: crate::batch_copy::CopyError, - }, } impl Library { @@ -348,203 +234,9 @@ impl Library { update: None, aside: None, counts: crate::db_counts::Counts::new(ctx), - batch: None, - marks: HashMap::new(), - pass: None, } } - /// The marks of great moves of the database at `path`. - pub fn marks(&mut self, path: &Path) -> Arc> { - self.marks - .entry(path.to_path_buf()) - .or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(path)))) - .clone() - } - - /// The search under way, as each database's conditions line shows it; «Stop» of - /// any of them stops it. Called every frame. - pub fn show_pass(&mut self, estimate: impl Fn(&[u32]) -> f64) { - let status = self.pass.as_ref().map(|job| { - ( - job.source.clone(), - crate::own_db::base_name(&job.source), - job.selected, - job.done(), - job.records.len(), - job.current(), - job.left_secs(&estimate), - job.stopping, - ) - }); - let mut stop = false; - for (path, view) in self.large.iter_mut() { - view.pass = status.as_ref().map( - |(source, name, selected, done, total, current, left, stopping)| { - large_db::PassStatus { - here: source == path, - name: name.clone(), - selected: *selected, - done: *done, - total: *total, - current: *current, - left_secs: *left, - stopping: *stopping, - } - }, - ); - stop |= std::mem::take(&mut view.stop_pass); - } - if stop && let Some(job) = self.pass.as_mut() { - job.stop(); - } - } - - /// Why the search may not start now (the engine is busy elsewhere), for every - /// database's button. - pub fn set_engine_busy(&mut self, why: Option) { - for view in self.large.values_mut() { - view.engine_busy = why.clone(); - } - } - - /// Why the last search in `path` stopped with an error, where its progress was. - pub fn set_pass_error(&mut self, path: &Path, text: Option) { - if let Some(view) = self.large.get_mut(path) { - view.pass_error = text; - } - } - - /// Starts copying `records` of `source` into the new file `target` (none while - /// another copy is written). `false`: the source is not read or the thread did not - /// start. - pub fn start_batch( - &mut self, - ctx: &egui::Context, - source: &Path, - records: Vec, - sort: chess_import::chessbase::base::SortKey, - ascending: bool, - target: PathBuf, - ) -> bool { - if self.batch.is_some() { - return false; - } - let Some(db) = self.database(source) else { - return false; - }; - let total = records.len(); - let req = crate::batch_copy::CopyRequest { - records, - sort, - ascending, - target: target.clone(), - slow: std::env::var_os("CP_BATCH_SLOW").is_some(), - }; - let now = ctx.input(|i| i.time); - let Some(work) = crate::board_search::Background::spawn(ctx, now, move |p, c| { - crate::batch_copy::copy_into_new(&db, &req, p, c) - }) else { - return false; - }; - if let Some(view) = self.large.get_mut(source) { - view.batch_error = None; - } - self.batch = Some(BatchJob { - source: source.to_path_buf(), - target, - total, - work, - cancelling: false, - }); - true - } - - /// Why the copy from `path` wrote nothing, said where its progress was. - pub fn set_batch_error(&mut self, path: &Path, text: String) { - if let Some(view) = self.large.get_mut(path) { - view.batch_error = Some(text); - } - } - - /// The chosen records of `path` let go (their numbers no longer mean the same games). - pub fn clear_selection(&mut self, path: &Path) { - if let Some(view) = self.large.get_mut(path) { - view.clear_marks(); - } - } - - /// Asks the copy being written to stop. - pub fn cancel_batch(&mut self) { - if let Some(job) = &mut self.batch { - job.work.cancel(); - job.cancelling = true; - } - } - - /// Stops the copy being written and waits a little for it to clean up (closing the - /// program): its temporary file goes, no new database appears. - pub fn stop_batch(&mut self) { - if let Some(job) = self.batch.take() { - job.work.cancel(); - job.work.wait(std::time::Duration::from_secs(3)); - } - } - - /// The end of the copy being written, once it came (called every frame, whatever is - /// on the screen); while it runs the source's conditions line shows it. - pub fn poll_batch(&mut self, ctx: &egui::Context) -> Option { - let job = self.batch.as_ref()?; - // `CP_BATCH_CANCEL_AFTER=`: «Cancel» pressed that long after the start (checks, - // screenshots of the cancelling). - let cancel_after = std::env::var("CP_BATCH_CANCEL_AFTER") - .ok() - .and_then(|ms| ms.parse::().ok()); - if let Some(ms) = cancel_after - && !job.cancelling - && ctx.input(|i| i.time) - job.work.started >= ms / 1000.0 - { - self.cancel_batch(); - } - let job = self.batch.as_ref()?; - let Some(result) = job.work.poll() else { - let status = large_db::BatchStatus { - name: crate::own_db::base_name(&job.target), - done: job.work.progress(), - total: job.total, - cancelling: job.cancelling, - }; - let source = job.source.clone(); - let mut cancel = false; - if let Some(view) = self.large.get_mut(&source) { - cancel = std::mem::take(&mut view.cancel_batch); - view.batch = Some(status); - } - if cancel { - self.cancel_batch(); - } - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - return None; - }; - let job = self.batch.take()?; - if let Some(view) = self.large.get_mut(&job.source) { - view.batch = None; - view.cancel_batch = false; - } - Some(match result { - None => BatchEnd::Cancelled { target: job.target }, - Some(Ok(report)) => BatchEnd::Done { - target: job.target, - report, - }, - Some(Err(error)) => BatchEnd::Failed { - source: job.source, - target: job.target, - error, - }, - }) - } - /// Starts loading `path` in the background (no-op if already loaded/loading). pub fn load(&mut self, path: &Path, ctx: &egui::Context) { if matches!( @@ -560,20 +252,27 @@ impl Library { })); let cancel = Arc::new(AtomicBool::new(false)); let (tx, rx) = channel(); - let (p, ctx, wake) = (progress.clone(), ctx.clone(), ctx.clone()); - let spawned = crate::platform::open_database( - path, - move |sp| { - if let Ok(mut g) = p.lock() { - *g = sp; - } - wake.request_repaint(); - }, + let (p, c, path_owned, ctx) = ( + progress.clone(), cancel.clone(), - move |res| { + path.to_path_buf(), + ctx.clone(), + ); + let spawned = std::thread::Builder::new() + .name("db-open".into()) + .spawn(move || { + let res = chess_import::open( + &path_owned, + &mut |sp| { + if let Ok(mut g) = p.lock() { + *g = sp; + } + ctx.request_repaint(); + }, + &c, + ); // The filters' index of a PGN is built here, not on the screen's thread - // (a large download takes a second, §9.7; in a browser, which reads - // smaller files, it is the page's thread). + // (a large download takes a second, §9.7). if let Ok(opened) = &res && let Database::Pgn(pgn) = &opened.db { @@ -581,8 +280,7 @@ impl Library { } let _ = tx.send(res); ctx.request_repaint(); - }, - ); + }); let slot = match spawned { Ok(_) => Slot::Loading { progress, @@ -601,21 +299,6 @@ impl Library { } } - /// Chooses the row of `index` alone (any choice of several let go) and scrolls to it. - pub fn choose_only(&mut self, path: &Path, index: usize) { - if let Some(view) = self.large.get_mut(path) { - view.clear_marks(); - view.reveal(index); - } - } - - /// Sorts the table of `path` by its «!!» column. - pub fn sort_by_marks(&mut self, path: &Path) { - if let Some(view) = self.large.get_mut(path) { - view.sort_marks_on(); - } - } - /// Selects (and scrolls to) a game row, e.g. when returning from a game. pub fn reveal(&mut self, path: &Path, index: usize) { if let Some(view) = self.large.get_mut(path) { @@ -628,10 +311,7 @@ impl Library { let selected = self.selected_db.as_deref() == Some(path); // The conditions, the position, the sort and the selection stay (§9.7): the view // finds its list anew once the file is read. - let mut view = self.large.remove(path); - if let (Some(v), Some(db)) = (view.as_mut(), self.database(path)) { - v.before_reread(&db); - } + let view = self.large.remove(path); self.forget(path); if let Some(v) = view { self.large.insert(path.to_path_buf(), v); @@ -653,10 +333,6 @@ impl Library { if crate::examples::is_example(path) { return Some(Block::Example); } - // In a browser the user's files are only read. - if cfg!(web) && crate::platform::fs::meta(path).is_ok_and(|m| m.readonly) { - return Some(Block::ReadOnly); - } if !self.files.exists(path) { return Some(Block::Missing); } @@ -954,35 +630,10 @@ impl Library { { ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); } - for view in self.large.values_mut() { - if let Some(text) = view.notice.take() { - actions.push(LibraryAction::Notice(text)); - } - } - if let Some(path) = self.selected_db.clone() - && let Some(view) = self.large.get_mut(&path) - && let Some(entry) = view.prepare.take() - && crate::platform::CAPS.prep - { - actions.push(LibraryAction::PrepareAgainst { path, entry }); - } self.notes_window(ui.ctx()); actions } - /// Ctrl+Shift+P: the chosen database (when it is read) and the player of its - /// filter, if one is set. - pub fn prep_entry(&self) -> Option<(PathBuf, Option)> { - let path = self.selected_db.clone()?; - if !matches!(self.slots.get(&path), Some(Slot::Ready(_))) { - return None; - } - Some(( - path.clone(), - self.large.get(&path).and_then(|v| v.prep_entry()), - )) - } - fn notes_window(&mut self, ctx: &egui::Context) { let Some(path) = self.notes_open.clone() else { return; @@ -1061,12 +712,9 @@ impl Library { self.select_db(&p, ui.ctx()); } self.groups(ui, true, icons, actions); - ui.scope_builder( - egui::UiBuilder::new() - .id_salt("shelf_app_actions") - .layout(egui::Layout::right_to_left(egui::Align::Center)), - |ui| self.app_buttons(ui, icons, actions), - ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + self.app_buttons(ui, icons, actions); + }); }); // The game put aside: a strip under the line. if let Some(card) = &self.aside { @@ -1079,10 +727,14 @@ impl Library { /// "⚙ Settings" and the newer version (right to left): the program's corner, the /// same as on the game screen. Icons only, with the names in the tooltips. fn app_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { - if crate::widgets::settings_button(ui, icons).clicked() { + let label = |full: &'static str, icon: &'static str| if icons { icon } else { full }; + if ui + .button(label(tr("⚙ Settings"), "⚙")) + .on_hover_text(shelf_hint(icons, tr("⚙ Settings"), "Ctrl+,")) + .clicked() + { actions.push(LibraryAction::OpenSettings); } - #[cfg(not(web))] if let Some(v) = &self.update && crate::widgets::update_button(ui, v).clicked() { @@ -1096,43 +748,15 @@ impl Library { self.shelf_actions(ui, folded, actions); ui.separator(); self.game_buttons(ui, icons, actions); - if crate::platform::CAPS.play { - ui.separator(); - self.play_button(ui, icons, actions); - } - if crate::platform::CAPS.prep { - ui.separator(); - let label = if icons { - "🗐" - } else { - tr("🗐 Preparations") - }; - if shelf_button(ui, "preparations", label) - .on_hover_text(shelf_hint( - icons, - tr("🗐 Preparations"), - tr("Preparations against opponents: the saved ones and a new one"), - )) - .clicked() - { - actions.push(LibraryAction::Preparations); - } - } - #[cfg(not(web))] - if crate::platform::CAPS.training { - if !crate::platform::CAPS.prep { - ui.separator(); - } - if shelf_button(ui, "opening_training", tr("Opening training (α version)")).clicked() { - actions.push(LibraryAction::OpeningTraining); - } - } + ui.separator(); + self.play_button(ui, icons, actions); } /// "♞ Play": a game against Maia, a group of its own. fn play_button(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { let label = if icons { "♞" } else { tr("♞ Play") }; - if shelf_button(ui, "play", label) + if ui + .button(label) .on_hover_text(shelf_hint( icons, tr("♞ Play"), @@ -1148,7 +772,8 @@ impl Library { fn game_buttons(&self, ui: &mut Ui, icons: bool, actions: &mut Vec) { let label = |full: &'static str, icon: &'static str| if icons { icon } else { full }; let hint = |full: &str, hint: &str| shelf_hint(icons, full, hint); - if shelf_button(ui, "new_game", label(tr("♟ New game"), "♟")) + if ui + .button(label(tr("♟ New game"), "♟")) .on_hover_text(hint( tr("♟ New game"), tr("Empty board in the starting position (Ctrl+N)"), @@ -1157,7 +782,8 @@ impl Library { { actions.push(LibraryAction::NewGame); } - if shelf_button(ui, "paste_pgn", label(tr("📋 Paste PGN"), "📋")) + if ui + .button(label(tr("📋 Paste PGN"), "📋")) .on_hover_text(hint( tr("📋 Paste PGN"), tr("Open a game from the clipboard"), @@ -1203,12 +829,9 @@ impl Library { ui.add_space(16.0 - ui.spacing().item_spacing.x); } self.groups(ui, folded, icons, actions); - ui.scope_builder( - egui::UiBuilder::new() - .id_salt("shelf_app_actions") - .layout(egui::Layout::right_to_left(egui::Align::Center)), - |ui| self.app_buttons(ui, icons, actions), - ); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + self.app_buttons(ui, icons, actions); + }); }); let card = self.aside.take(); let card_w = card.as_ref().map_or(0.0, |c| c.width(ui)); @@ -1247,9 +870,12 @@ impl Library { /// The width of `shelf_actions`. fn shelf_actions_w(&self, ui: &Ui, folded: bool) -> f32 { - if folded { + let online = self.online_running.map_or(0.0, |n| { + 14.0 + ui.spacing().item_spacing.x + button_w(ui, &crate::large_db::grouped(n)) + }); + let buttons = if folded { button_w(ui, "+ ▾") - + if crate::platform::CAPS.online_games { + + if self.online { button_w(ui, "🌐") } else { 0.0 @@ -1257,17 +883,17 @@ impl Library { } else { button_w(ui, tr("+ Add database")) + button_w(ui, tr("✚ New database")) - + if crate::platform::CAPS.online_games { + + if self.online { button_w(ui, &format!("🌐 {}", tr("Online games"))) } else { 0.0 } - } + }; + buttons + if self.online { online } else { 0.0 } } /// «+ Add database · ✚ New database · 🌐 Online games», or folded: «+ ▾» (a menu of - /// the first two) and «🌐». Download progress belongs in the tooltip/dialog so - /// background work never moves the toolbar's other actions. + /// the first two) and «🌐»; a download under way shows its count beside the globe. fn shelf_actions(&self, ui: &mut Ui, folded: bool, actions: &mut Vec) { let add_hint = tr("Open PGN, ChessBase (.cbh, .cbv) or an archive (.zip, .7z) (Ctrl+O)"); let new_hint = tr("An empty PGN file for your own games (Ctrl+Shift+N)"); @@ -1275,43 +901,41 @@ impl Library { "Download any player's games by nickname into a database: yours, a pupil's, an opponent's", ); if folded { - ui.push_id("database_menu", |ui| { - ui.menu_button("+ ▾", |ui| { - if ui - .button(tr("Add database…")) - .on_hover_text(add_hint) - .clicked() - { - actions.push(LibraryAction::AddDatabases); - ui.close(); - } - if crate::platform::CAPS.own_databases - && ui - .button(tr("New database…")) - .on_hover_text(new_hint) - .clicked() - { - actions.push(LibraryAction::NewDatabase); - ui.close(); - } - }) + ui.menu_button("+ ▾", |ui| { + if ui + .button(tr("Add database…")) + .on_hover_text(add_hint) + .clicked() + { + actions.push(LibraryAction::AddDatabases); + ui.close(); + } + if ui + .button(tr("New database…")) + .on_hover_text(new_hint) + .clicked() + { + actions.push(LibraryAction::NewDatabase); + ui.close(); + } }); } else { - if shelf_button(ui, "add_database", tr("+ Add database")) + if ui + .button(tr("+ Add database")) .on_hover_text(add_hint) .clicked() { actions.push(LibraryAction::AddDatabases); } - if crate::platform::CAPS.own_databases - && shelf_button(ui, "new_database", tr("✚ New database")) - .on_hover_text(new_hint) - .clicked() + if ui + .button(tr("✚ New database")) + .on_hover_text(new_hint) + .clicked() { actions.push(LibraryAction::NewDatabase); } } - if crate::platform::CAPS.online_games { + if self.online { let label = if folded { "🌐".to_owned() } else { @@ -1321,27 +945,20 @@ impl Library { Some(n) => trf("downloading… {n}", &[("n", &crate::i18n::games(n))]), None => online_hint.to_owned(), }; - if shelf_button(ui, "online_games", label) - .on_hover_text(hint) - .clicked() - { - #[cfg(not(web))] + if ui.button(label).on_hover_text(hint).clicked() { actions.push(LibraryAction::OnlineGames); } + if let Some(n) = self.online_running { + ui.add(egui::Spinner::new().size(14.0)); + ui.label(RichText::new(crate::large_db::grouped(n)).weak()); + } } } /// The empty shelf's invitation: the three actions as large cards, centred. fn action_cards(&self, ui: &mut Ui, actions: &mut Vec) { let (add_w, new_w, online_w) = side_card_widths(ui); - let total = add_w - + new_w - + if crate::platform::CAPS.online_games { - online_w + 8.0 - } else { - 0.0 - } - + 8.0; + let total = add_w + new_w + if self.online { online_w + 8.0 } else { 0.0 } + 8.0; let card = |ui: &mut Ui, w: f32, title: &str, below: Option<&str>| { let (rect, resp) = ui.allocate_exact_size(vec2(w, 64.0), Sense::click()); let visuals = ui.style().interact(&resp); @@ -1386,14 +1003,13 @@ impl Library { { actions.push(LibraryAction::AddDatabases); } - if crate::platform::CAPS.own_databases - && card(ui, new_w, tr("✚ New database"), None) - .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) - .clicked() + if card(ui, new_w, tr("✚ New database"), None) + .on_hover_text(tr("An empty PGN file for your own games (Ctrl+Shift+N)")) + .clicked() { actions.push(LibraryAction::NewDatabase); } - if crate::platform::CAPS.online_games + if self.online && card( ui, online_w, @@ -1403,7 +1019,6 @@ impl Library { .on_hover_text(tr("Download any player's games by nickname into a database: yours, a pupil's, an opponent's")) .clicked() { - #[cfg(not(web))] actions.push(LibraryAction::OnlineGames); } }); @@ -1440,17 +1055,6 @@ impl Library { }); trf("loading… {n}", &[("n", &p.games)]) } - Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(path) => { - tr("📁 Choose the database's folder").into() - } - Some(Slot::Failed(_)) | None if crate::platform::files::waiting_to_read(path) => { - tr("🔒 Allow reading").into() - } - Some(Slot::Failed(_)) | None - if crate::platform::files::session_only(path) && !self.files.exists(path) => - { - tr("↻ Choose the file again").into() - } Some(Slot::Failed(_)) => tr("error").into(), None if !self.files.exists(path) => tr("file not found").into(), // Not opened: its games once counted, nothing till then. @@ -1514,9 +1118,9 @@ impl Library { &[("name", name)], ) }; - resp.on_hover_text(format!("{whose}\n{}", crate::platform::files::shown(path))) + resp.on_hover_text(format!("{whose}\n{}", path.display())) } - None => resp.on_hover_text(crate::platform::files::shown(path)), + None => resp.on_hover_text(path.display().to_string()), }; if resp.clicked() { self.select_db(path, ui.ctx()); @@ -1612,10 +1216,7 @@ impl Library { ui.add_space(40.0); ui.label(trf( "Reading {path} — games found: {n}", - &[ - ("path", &crate::platform::files::shown(&path)), - ("n", &p.games), - ], + &[("path", &path.display()), ("n", &p.games)], )); ui.add(egui::ProgressBar::new(frac).desired_width(400.0)); if ui.button(tr("Cancel")).clicked() { @@ -1624,75 +1225,6 @@ impl Library { }); return; } - #[cfg(web)] - Some(Slot::Failed(_)) if crate::platform::files::chessbase_incomplete(&path) => { - // A ChessBase database's .cbh without its other files (one chosen - // alone at an earlier visit): its folder or all its files. - ui.vertical_centered(|ui| { - ui.add_space(40.0); - ui.label(tr( - "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", - )); - ui.add_space(8.0); - ui.horizontal(|ui| { - if ui.button(tr("📁 Choose the database's folder")).clicked() { - actions.push(LibraryAction::ChooseFolderAgain(path.clone())); - } - if ui.button(tr("Choose the database's files")).clicked() { - actions.push(LibraryAction::ChooseAgain(path.clone())); - } - if ui.button(tr("Remove from list")).clicked() { - actions.push(LibraryAction::RemoveDatabase(path.clone())); - } - }); - }); - return; - } - #[cfg(web)] - Some(Slot::Failed(_)) if crate::platform::files::waiting_to_read(&path) => { - // Chrome, Edge: the file is remembered; the browser asks before the - // page reads it again. - ui.vertical_centered(|ui| { - ui.add_space(40.0); - ui.label(tr( - "The browser remembers this file and asks before the page reads it again.", - )); - ui.add_space(8.0); - ui.horizontal(|ui| { - if ui.button(tr("🔒 Allow reading")).clicked() { - actions.push(LibraryAction::AllowReading(path.clone())); - } - if ui.button(tr("Remove from list")).clicked() { - actions.push(LibraryAction::RemoveDatabase(path.clone())); - } - }); - }); - return; - } - Some(Slot::Failed(_)) - if crate::platform::files::session_only(&path) && !self.files.exists(&path) => - { - // A browser keeps no way back to a file the user chose (Firefox, Safari). - ui.vertical_centered(|ui| { - ui.add_space(40.0); - // Chrome and Edge remember chosen files, not dropped ones. - ui.label(if crate::platform::files::remembers_chosen() { - tr("A dropped file is not remembered: after a reload, choose the file again or keep a copy in the browser.") - } else { - tr("This browser doesn't remember files: after a reload, choose the file again or keep a copy in the browser.") - }); - ui.add_space(8.0); - ui.horizontal(|ui| { - if ui.button(tr("↻ Choose the file again")).clicked() { - actions.push(LibraryAction::ChooseAgain(path.clone())); - } - if ui.button(tr("Remove from list")).clicked() { - actions.push(LibraryAction::RemoveDatabase(path.clone())); - } - }); - }); - return; - } Some(Slot::Failed(e)) => { let e = e.clone(); ui.vertical_centered(|ui| { @@ -1700,7 +1232,7 @@ impl Library { ui.label( RichText::new(trf( "Could not open {path}: {e}", - &[("path", &crate::platform::files::shown(&path)), ("e", &e)], + &[("path", &path.display()), ("e", &e)], )) .color(ui.visuals().error_fg_color), ); @@ -1725,15 +1257,6 @@ impl Library { .entry(path.clone()) .or_insert_with(|| LargeView::for_database(&db, online)); let notes = self.info.get(&path).map_or(0, |i| i.notes.len()); - view.set_marks_db(&db); - if view.marks.is_none() { - let marks = self - .marks - .entry(path.clone()) - .or_insert_with(|| Arc::new(Mutex::new(crate::brilliant::Index::of(&path)))) - .clone(); - view.marks = Some(marks); - } if view.table( ui, &path, @@ -1790,7 +1313,6 @@ impl Library { format, format_hint, online, - keep_copy: crate::platform::files::session_only(path), } } } @@ -1819,237 +1341,6 @@ fn import_error(e: &ImportError) -> String { "The ChessBase 2CBH format is not supported: export the database from ChessBase as CBH or PGN", ) .into(), - ImportError::Unsupported(Unsupported::ChessBaseFiles) => tr( - "A ChessBase database is several files (.cbh, .cbg, .cba…). Choose its folder or all its files at once.", - ) - .into(), - ImportError::Io { source, .. } if source.kind() == std::io::ErrorKind::OutOfMemory => tr( - "The browser doesn't have enough memory for this database. Open it in the desktop program.", - ) - .into(), - // A browser's places of files mean nothing to the user: only what happened. - #[cfg(web)] - ImportError::Io { source, .. } => source.to_string(), e => e.to_string(), } } - -#[cfg(all(test, not(web)))] -mod tests { - use super::*; - - fn toolbar_frame( - library: &mut Library, - ctx: &egui::Context, - width: f32, - events: Vec, - ) -> (Vec<(String, egui::Rect, egui::Color32)>, Vec) { - toolbar_frame_at_size(library, ctx, vec2(width, 900.0), events) - } - - fn toolbar_frame_at_size( - library: &mut Library, - ctx: &egui::Context, - size: egui::Vec2, - events: Vec, - ) -> (Vec<(String, egui::Rect, egui::Color32)>, Vec) { - let mut actions = Vec::new(); - let mut output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)), - events, - ..Default::default() - }, - |ui| { - let databases = library.slots.keys().cloned().collect::>(); - actions = library.show(ui, &databases, &Settings::default()); - }, - ); - output.textures_delta.clear(); - let text = output - .shapes - .iter() - .filter_map(|clipped| { - if let egui::Shape::Text(shape) = &clipped.shape - && shape.pos.y < 40.0 - { - Some(( - shape.galley.text().to_owned(), - egui::Rect::from_min_size(shape.pos, shape.galley.size()), - shape.fallback_color, - )) - } else { - None - } - }) - .collect(); - output.drop_without_applying_deltas(); - (text, actions) - } - - #[test] - fn startup_download_progress_keeps_toolbar_geometry_and_style_stable() { - for height in [590.0, 900.0] { - for width in [640.0, 960.0, 1100.0, 1400.0, 1920.0] { - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let mut library = Library::new(&ctx); - let (pending, _) = - toolbar_frame_at_size(&mut library, &ctx, vec2(width, height), vec![]); - library.online = true; - library.online_running = Some(100_000); - let (ready, _) = - toolbar_frame_at_size(&mut library, &ctx, vec2(width, height), vec![]); - assert_eq!( - pending, ready, - "toolbar changed when background progress arrived at width {width}" - ); - assert!( - ready.iter().any(|(label, _, _)| label == "🌐" - || label == &format!("🌐 {}", tr("Online games"))) - ); - } - } - } - - #[test] - fn resizing_and_update_badge_never_reuse_a_separator_as_button_style() { - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let mut library = Library::new(&ctx); - for (width, update) in [ - (1400.0, None), - (640.0, None), - (960.0, Some("⬆ Update 2.2.0")), - (1920.0, Some("⬆ Update 2.2.0")), - (1100.0, None), - (640.0, None), - (1400.0, None), - ] { - library.update = update.map(str::to_owned); - let (first, _) = toolbar_frame(&mut library, &ctx, width, vec![]); - let (settled, _) = toolbar_frame(&mut library, &ctx, width, vec![]); - assert_eq!( - first, settled, - "first resized frame had a stale response/style at {width}" - ); - for (label, rect, color) in first { - assert!( - rect.left() >= 0.0 && rect.right() <= width, - "{label}: {rect:?}" - ); - if label != tr("Databases") && !label.starts_with('⬆') { - assert_eq!( - color, - ctx.style_of(egui::Theme::Dark) - .visuals - .widgets - .inactive - .fg_stroke - .color, - "false noninteractive style for {label}" - ); - } - } - } - } - - #[test] - fn toolbar_actions_are_available_while_the_database_loads_and_afterwards() { - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - let mut library = Library::new(&ctx); - let path = PathBuf::from("/tmp/chesspenguin-toolbar-regression.pgn"); - let (_tx, rx) = channel(); - library.slots.insert( - path.clone(), - Slot::Loading { - progress: Arc::new(Mutex::new(ScanProgress { - bytes_done: 0, - bytes_total: 100, - games: 0, - })), - cancel: Arc::new(AtomicBool::new(false)), - rx, - }, - ); - library.selected_db = Some(path.clone()); - let (loading, _) = toolbar_frame(&mut library, &ctx, 1400.0, vec![]); - for ready in [false, true] { - if ready { - let opened = chess_import::open_bytes( - "toolbar.pgn", - b"1. e4 e5 *".to_vec(), - &mut |_| {}, - &AtomicBool::new(false), - ) - .unwrap(); - library - .large - .insert(path.clone(), LargeView::for_database(&opened.db, false)); - library - .slots - .insert(path.clone(), Slot::Ready(Arc::new(opened.db))); - library.online = true; - library.online_running = Some(1_000_000); - } - let (texts, _) = toolbar_frame( - &mut library, - &ctx, - 1400.0, - vec![egui::Event::PointerMoved(egui::pos2(-100.0, -100.0))], - ); - assert_eq!(loading, texts, "database completion changed the toolbar"); - for (label, expected) in [ - (tr("+ Add database").to_owned(), LibraryAction::AddDatabases), - (tr("✚ New database").to_owned(), LibraryAction::NewDatabase), - ( - format!("🌐 {}", tr("Online games")), - LibraryAction::OnlineGames, - ), - (tr("♟ New game").to_owned(), LibraryAction::NewGame), - (tr("📋 Paste PGN").to_owned(), LibraryAction::PastePgn), - (tr("♞ Play").to_owned(), LibraryAction::Play), - (tr("🗐 Preparations").to_owned(), LibraryAction::Preparations), - ( - tr("Opening training (α version)").to_owned(), - LibraryAction::OpeningTraining, - ), - (tr("⚙ Settings").to_owned(), LibraryAction::OpenSettings), - ] { - let pos = texts - .iter() - .find(|(text, _, _)| text == &label) - .unwrap() - .1 - .center(); - let button = |pressed| egui::Event::PointerButton { - pos, - button: egui::PointerButton::Primary, - pressed, - modifiers: egui::Modifiers::NONE, - }; - toolbar_frame( - &mut library, - &ctx, - 1400.0, - vec![egui::Event::PointerMoved(pos), button(true)], - ); - let (_, actions) = toolbar_frame(&mut library, &ctx, 1400.0, vec![button(false)]); - assert!( - actions.iter().any(|action| std::mem::discriminant(action) - == std::mem::discriminant(&expected)), - "{label} did not activate, ready={ready}" - ); - } - // egui reads the previous response for styling: let the final hover - // leave before comparing the next data state. - toolbar_frame( - &mut library, - &ctx, - 1400.0, - vec![egui::Event::PointerMoved(egui::pos2(-100.0, -100.0))], - ); - } - } -} diff --git a/apps/desktop/src/maia_download.rs b/apps/desktop/src/maia_download.rs index 3ca7d00..390d5cf 100644 --- a/apps/desktop/src/maia_download.rs +++ b/apps/desktop/src/maia_download.rs @@ -60,7 +60,7 @@ impl Published for Model { } /// `/maia/`. -pub fn dir() -> Option { +fn dir() -> Option { directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") .map(|d| d.data_local_dir().join("maia")) } @@ -102,19 +102,6 @@ pub struct Download { } impl Download { - /// A browser downloads no weights into files: there is no download for it. - #[cfg(web)] - pub fn start(_ctx: &egui::Context, model: Model) -> Download { - Download { - model, - stage: Arc::new(Mutex::new(Stage::Failed( - crate::i18n::tr("not yet for this system").to_owned(), - ))), - cancel: Arc::new(AtomicBool::new(false)), - } - } - - #[cfg(not(web))] pub fn start(ctx: &egui::Context, model: Model) -> Download { let stage = Arc::new(Mutex::new(Stage::Downloading { done: 0 })); let cancel = Arc::new(AtomicBool::new(false)); @@ -155,7 +142,6 @@ impl Drop for Download { } } -#[cfg(not(web))] fn run(model: Model, report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let dir = dir().ok_or("no data directory")?; std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; diff --git a/apps/desktop/src/main.rs b/apps/desktop/src/main.rs index ab8a1a2..cb13429 100644 --- a/apps/desktop/src/main.rs +++ b/apps/desktop/src/main.rs @@ -1,6 +1,111 @@ // No console window for release builds on Windows. #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] +mod adjourned; +mod analysis; +mod app; +mod assets; +mod board; +mod board_search; +mod chatgpt; +mod db_counts; +mod engine_download; +mod engine_offer; +mod engines; +mod examples; +mod file_state; +mod game_view; +mod graphics; +mod i18n; +mod large_db; +mod library; +mod maia_download; +mod notation; +mod online; +mod online_ui; +mod own_db; +mod play; +mod player_games; +mod reference; +mod review; +mod rodent4_download; +mod rodent_download; +mod san; +mod settings; +mod settings_ui; +mod sound; +mod translate; +mod translate_ui; +mod update; +mod update_ui; +mod viewed; +mod widgets; + +/// Learning an opening: shared with the Android app. +use trainer as train; + fn main() -> eframe::Result { - chesspenguin_app::run_native() + // `chesspenguin --bench [report.txt]`: timings instead of the window + // (`docs/dev/import.md`, "Замер на другой машине"). + let args: Vec = std::env::args_os().skip(1).collect(); + if args.first().is_some_and(|a| a == "--bench") { + let Some(db) = args.get(1) else { + eprintln!("usage: chesspenguin --bench [report.txt]"); + std::process::exit(2); + }; + let cache = settings::Settings::cache_dir().map(|d| d.join("boosters")); + let result = match args.get(2) { + Some(file) => std::fs::File::create(file) + .and_then(|mut f| chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut f)), + None => chess_import::bench::run(db.as_ref(), cache.as_deref(), &mut std::io::stdout()), + }; + if let Err(e) = result { + eprintln!("bench: {e}"); + std::process::exit(1); + } + return Ok(()); + } + crate::i18n::set_lang(settings::Settings::load().language); + // The runs of the opening trainer (`CP_TRAINING_FILE` elsewhere: development). + if let Some(file) = std::env::var_os("CP_TRAINING_FILE") + .map(std::path::PathBuf::from) + .or_else(|| { + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_local_dir().join("training.json")) + }) + { + train::set_file(file); + } + graphics::install_panic_hook(); + graphics::init_library_log(); + let mode = graphics::choose(); + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default() + .with_app_id("io.github.vrubelroman.chessPenguin") + .with_title("ChessPenguin") + .with_inner_size([1400.0, 900.0]) + .with_min_inner_size([640.0, 480.0]) + // X11 uses this; on Wayland the icon comes from the .desktop entry matching the app id. + .with_icon( + eframe::icon_data::from_png_bytes(include_bytes!("../assets/icon-256.png")) + .unwrap_or_default(), + ), + wgpu_options: graphics::options(mode), + ..Default::default() + }; + let result = eframe::run_native( + "ChessPenguin", + options, + Box::new(|cc| { + assets::install(&cc.egui_ctx); + Ok(Box::new(app::App::new(&cc.egui_ctx))) + }), + ); + if let Err(e) = &result { + if graphics::retry(&e.to_string()) { + return Ok(()); + } + graphics::fatal(&e.to_string()); + } + result } diff --git a/apps/desktop/src/my_games.rs b/apps/desktop/src/my_games.rs deleted file mode 100644 index 6d18096..0000000 --- a/apps/desktop/src/my_games.rs +++ /dev/null @@ -1,98 +0,0 @@ -//! «My games» of the web version (docs/design/web-version.md §2.3): one PGN database -//! kept in the browser (the page's `/data`, in IndexedDB), always on the shelf. Saving -//! a game (Ctrl+S, 💾) puts it there — into its own record, or as a new one; the user's -//! files are only read. «Download all as PGN» gives it back as a file. - -use std::path::PathBuf; - -use crate::i18n::tr; -use crate::settings::Settings; - -const DIR: &str = "my-games"; - -/// The database: `/data/my-games/.pgn`, named in the language of the first start. -pub fn path() -> PathBuf { - let dir = crate::platform::data_dir().unwrap_or_default().join(DIR); - crate::platform::web::vfs::list(&dir) - .into_iter() - .find(|p| p.extension().is_some_and(|e| e == "pgn")) - .unwrap_or_else(|| dir.join(format!("{}.pgn", tr("My games")))) -} - -/// Makes the database at the first start and keeps it on the shelf; `true` when the -/// settings changed. -pub fn setup(settings: &mut Settings) -> bool { - let path = path(); - if !crate::platform::fs::exists(&path) { - let _ = crate::platform::fs::write_atomic(&path, b""); - } - if settings.databases.contains(&path) { - return false; - } - settings.databases.push(path); - true -} - -/// Whether `path` is «My games». -pub fn is(path: &std::path::Path) -> bool { - path == self::path() -} - -/// Gives all of «My games» as a downloaded PGN file (`ChessPenguin-my-games-.pgn`). -pub fn download_all() -> Result<(), String> { - let text = crate::platform::fs::read_to_string(&path()).map_err(|e| e.to_string())?; - let date = chrono::Local::now().format("%Y-%m-%d"); - crate::platform::files::download_pgn(&format!("ChessPenguin-my-games-{date}.pgn"), &text) -} - -/// Games in «My games» (records of its text; 0 when empty). -pub fn count() -> usize { - crate::platform::fs::read(&path()) - .ok() - .and_then(|b| { - chess_core::PgnDatabase::from_bytes( - b, - Some(chess_core::TextEncoding::Utf8), - &mut |_| {}, - &std::sync::atomic::AtomicBool::new(false), - ) - .ok() - }) - .map_or(0, |db| db.len()) -} - -/// Its size in bytes. -pub fn size() -> u64 { - crate::platform::fs::meta(&path()).map_or(0, |m| m.len) -} - -/// A game left unsaved when the page was closed (docs/design/web-version.md §2.6): one, -/// the last, written every few seconds while it has changes. It guards against a -/// closed tab; it is not a save: offered at the next start, opened or deleted. -#[derive(Clone, serde::Serialize, serde::Deserialize)] -pub struct Draft { - pub title: String, - pub moves: usize, - pub pgn: String, -} - -fn draft_path() -> PathBuf { - crate::platform::data_dir() - .unwrap_or_default() - .join("draft.json") -} - -pub fn write_draft(draft: &Draft) { - if let Ok(json) = serde_json::to_vec(draft) { - let _ = crate::platform::fs::write_atomic(&draft_path(), &json); - } -} - -pub fn read_draft() -> Option { - let bytes = crate::platform::fs::read(&draft_path()).ok()?; - serde_json::from_slice(&bytes).ok() -} - -pub fn delete_draft() { - let _ = crate::platform::fs::remove_file(&draft_path()); -} diff --git a/apps/desktop/src/notation.rs b/apps/desktop/src/notation.rs index 8850cd8..a45cbfe 100644 --- a/apps/desktop/src/notation.rs +++ b/apps/desktop/src/notation.rs @@ -29,84 +29,6 @@ pub struct Notation<'a> { pub dim_until: Option, /// Mistakes on main-line moves (learning an opening): how many, the move was shown. pub mistakes: Option<&'a HashMap>, - /// Arrows and circles of the moves' comments (`[%cal]`, `[%csl]`): a quiet sign by - /// the move ([`shape_counts`]). - pub shapes: Option<&'a HashMap>, -} - -/// How many arrows and circles a move's comment draws on the board. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct ShapeCount { - pub arrows: usize, - pub circles: usize, -} - -impl ShapeCount { - /// «Arrows: 2 · circles: 1 — shown on the board at this move»; a count of none is left out. - pub fn hint(self) -> String { - let (a, c) = (self.arrows, self.circles); - match (a, c) { - (_, 0) => crate::i18n::trf( - "Arrows: {a} — shown on the board at this move", - &[("a", &a)], - ), - (0, _) => crate::i18n::trf( - "Circles: {c} — shown on the board at this move", - &[("c", &c)], - ), - _ => crate::i18n::trf( - "Arrows: {a} · circles: {c} — shown on the board at this move", - &[("a", &a), ("c", &c)], - ), - } - } -} - -/// The nodes of the game whose comment after them draws arrows or circles. -pub fn shape_counts(game: &Game) -> HashMap { - game.all_nodes() - .filter_map(|id| { - let (arrows, circles) = chess_core::shapes(game.node(id)?.comments_after()); - let count = ShapeCount { - arrows: arrows.len(), - circles: circles.len(), - }; - (count != ShapeCount::default()).then_some((id, count)) - }) - .collect() -} - -/// The sign's box; it is drawn this far after the move. -const SIGN: f32 = 10.0; -const SIGN_GAP: f32 = 4.0; - -/// The sign of a move whose comment draws on the board: an arrow if it has one, a ring -/// otherwise. Painted (no font has both at the height of a move's text), so it is sharp -/// at any scale; it does not repeat the shapes' colours, which would argue with NAGs. -fn paint_shapes_sign( - painter: &egui::Painter, - center: egui::Pos2, - count: ShapeCount, - color: Color32, -) { - let stroke = Stroke::new(1.5, color); - if count.arrows > 0 { - let h = SIGN / 2.0 - 0.5; - let (from, tip) = (center + vec2(-h, h), center + vec2(h, -h)); - let dir = (tip - from).normalized(); - let head = 4.5; - let base = tip - dir * head; - let side = vec2(-dir.y, dir.x) * (head * 0.55); - painter.line_segment([from, base + dir * 0.5], stroke); - painter.add(egui::Shape::convex_polygon( - vec![tip, base + side, base - side], - color, - Stroke::NONE, - )); - } else { - // The ring's outer edge within the sign's box, as the arrow's. - painter.circle_stroke(center, SIGN / 2.0 - 1.0, stroke); - } } /// Result of a frame of the notation panel. @@ -136,7 +58,7 @@ pub enum NotationCommand { Paste, /// A game against Maia from this position (docs/design/play-from-position.md). PlayFrom, - /// Add the exact path through this move to an opening repertoire. + /// Learn the opening up to this move (docs/design/opening-trainer.md). Train, } @@ -403,7 +325,6 @@ impl Row { resp.hovered(), dim, ); - let mut right = text_right; if let Some(&(count, shown)) = n.mistakes.and_then(|m| m.get(&id)) { let color = if shown { ui.visuals().warn_fg_color @@ -426,7 +347,6 @@ impl Row { ui.painter().rect_filled(pill, 7.0, color); ui.painter() .galley(pill.min + vec2(4.0, 1.0), galley, Color32::WHITE); - right = pill.right(); let tip = if shown { crate::i18n::trf("Mistakes: {n}; the move was shown", &[("n", &count)]) } else { @@ -434,22 +354,6 @@ impl Row { }; resp.clone().on_hover_text(tip); } - if let Some(&count) = n.shapes.and_then(|s| s.get(&id)) { - let color = if id == n.cursor { - ui.visuals().selection.stroke.color - } else { - ui.visuals().weak_text_color() - }; - let x = - (right + SIGN_GAP + SIGN / 2.0).min(cell.right() - SIGN / 2.0 - 2.0); - paint_shapes_sign( - ui.painter(), - egui::pos2(x, cell.center().y), - count, - color, - ); - resp.clone().on_hover_text(count.hint()); - } handle_move_response(ui, &resp, n, id, out); } None => { @@ -541,57 +445,56 @@ fn handle_move_response( out.context = Some((id, NotationCommand::Delete)); ui.close(); } - if !crate::platform::CAPS.play && !crate::platform::CAPS.training { - return; - } ui.separator(); - if crate::platform::CAPS.play { - let over = n.game.position(id).and_then(|p| { - if p.is_checkmate() { - Some(tr("checkmate")) - } else if p.is_stalemate() { - Some(tr("stalemate")) - } else if p.is_insufficient_material() { - Some(tr("neither side can checkmate")) - } else { - None - } - }); - let play = ui - .add_enabled( - over.is_none(), - egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"), - ) - .on_hover_text(tr("A game against the computer from this position")); - let play = match over { - Some(why) => play.on_disabled_hover_text(crate::i18n::trf( - "The game is over here: {why}", - &[("why", &why)], - )), - None => play, - }; - if play.clicked() { - out.context = Some((id, NotationCommand::PlayFrom)); - ui.close(); + // A finished position has nothing to play. + let over = n.game.position(id).and_then(|p| { + if p.is_checkmate() { + Some(tr("checkmate")) + } else if p.is_stalemate() { + Some(tr("stalemate")) + } else if p.is_insufficient_material() { + Some(tr("neither side can checkmate")) + } else { + None } + }); + let play = ui + .add_enabled( + over.is_none(), + egui::Button::new(tr("Play on from here…")).shortcut_text("Ctrl+G"), + ) + .on_hover_text(tr("A game against the computer from this position")); + let play = match over { + Some(why) => play.on_disabled_hover_text(crate::i18n::trf( + "The game is over here: {why}", + &[("why", &why)], + )), + None => play, + }; + if play.clicked() { + out.context = Some((id, NotationCommand::PlayFrom)); + ui.close(); } - if crate::platform::CAPS.training { - let line = crate::train::TrainStart::from_game(n.game, id); - let add = ui - .add_enabled( - line.is_some(), - egui::Button::new(tr("Add to repertoire…")), - ) - .on_hover_text(tr("Add only the path from the start through this move, with its comments and NAGs")) - .on_disabled_hover_text(if id == NodeId::ROOT { - tr("Select the move up to which to add") - } else { - tr("The line has a null move (--): it cannot be played on the board") - }); - if add.clicked() { - out.context = Some((id, NotationCommand::Train)); - ui.close(); - } + // Learning the opening: the runs of this line so far on the right. + let runs = crate::train::runs_to(n.game, id); + let label = runs + .filter(|&r| r > 0) + .map(|r| crate::i18n::trf("runs: {n}", &[("n", &r)])) + .unwrap_or_default(); + let learn = ui + .add_enabled( + runs.is_some(), + egui::Button::new(tr("Learn the opening up to this move")).shortcut_text(label), + ) + .on_hover_text(tr( + "Replay from memory the moves of both sides from the start of the game up to this move", + )) + .on_disabled_hover_text(tr( + "The line has a null move (--): it cannot be played on the board", + )); + if learn.clicked() { + out.context = Some((id, NotationCommand::Train)); + ui.close(); } }); let _ = ui; @@ -758,7 +661,7 @@ fn mark_block(ui: &mut Ui, n: &Notation, id: NodeId, mark: &Mark, out: &mut Nota }; let label = crate::san::show(&label).into_owned(); let current = shown == Some(i + 1); - let resp = move_chip(ui, &label, None, current, None) + let resp = move_chip(ui, &label, None, current) .on_hover_text(tr("Show this line on the board")); if current && n.scroll_to_cursor { resp.scroll_to_me(Some(egui::Align::Center)); @@ -934,16 +837,11 @@ const MARK_ROOM: f32 = 18.0; fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut NotationResponse) { let (shown, mark) = translated(n, text); - // The start of the game draws on the board: the sign at the block's right edge. - let shapes = (slot == Slot::After(NodeId::ROOT)) - .then(|| n.shapes.and_then(|s| s.get(&NodeId::ROOT)).copied()) - .flatten(); - let room = MARK_ROOM * (u8::from(mark.is_some()) + u8::from(shapes.is_some())) as f32; let mut frame = block_frame(ui); - if room > 0.0 { + if mark.is_some() { frame = frame.inner_margin(egui::Margin { left: 10, - right: 10 + room as i8, + right: 10 + MARK_ROOM as i8, top: 6, bottom: 6, }); @@ -968,18 +866,6 @@ fn comment_block(ui: &mut Ui, n: &Notation, text: &str, slot: Slot, out: &mut No let at = r.response.rect.right_top() + vec2(-8.0, 7.0); translation_mark(ui, at, m, text); } - if let Some(count) = shapes { - let shift = if mark.is_some() { MARK_ROOM } else { 0.0 }; - let center = r.response.rect.right_top() + vec2(-8.0 - shift - SIGN / 2.0, 6.0 + 9.0); - paint_shapes_sign(ui.painter(), center, count, ui.visuals().weak_text_color()); - let id = ui.id().with("root_shapes"); - ui.interact( - egui::Rect::from_center_size(center, vec2(SIGN, SIGN) + vec2(4.0, 4.0)), - id, - Sense::hover(), - ) - .on_hover_text(count.hint()); - } } /// A double click opens the comment for editing; the right button offers that and @@ -1267,7 +1153,6 @@ enum Token { /// The label with the move number, for the move that starts a piece of the flow. numbered: String, color: Option, - shapes: Option, }, Comment { slot: Slot, @@ -1323,13 +1208,7 @@ fn variation_block( /// A move in flowing text: the current one highlighted as in the main-line table, /// the others lit under the mouse. Painted by hand, so its size never changes with the /// mouse (a button's frame does). -fn move_chip( - ui: &mut Ui, - label: &str, - color: Option, - current: bool, - shapes: Option, -) -> egui::Response { +fn move_chip(ui: &mut Ui, label: &str, color: Option, current: bool) -> egui::Response { let sel = ui.visuals().selection; let font = FontId::proportional(15.0); let text_color = if current { @@ -1341,14 +1220,7 @@ fn move_chip( .painter() .layout_no_wrap(label.to_owned(), font, text_color); let pad = vec2(4.0, 2.0); - // The sign and the chip's own right padding after it. - let sign = if shapes.is_some() { - SIGN_GAP + SIGN + 2.0 - } else { - 0.0 - }; - let (rect, resp) = - ui.allocate_exact_size(galley.size() + 2.0 * pad + vec2(sign, 0.0), Sense::click()); + let (rect, resp) = ui.allocate_exact_size(galley.size() + 2.0 * pad, Sense::click()); if current { ui.painter().rect( rect, @@ -1361,18 +1233,7 @@ fn move_chip( ui.painter() .rect_filled(rect, 2.0, ui.visuals().widgets.hovered.weak_bg_fill); } - let text_right = rect.min.x + pad.x + galley.size().x; ui.painter().galley(rect.min + pad, galley, text_color); - if let Some(count) = shapes { - let color = if current { - sel.stroke.color - } else { - ui.visuals().weak_text_color() - }; - let center = egui::pos2(text_right + SIGN_GAP + SIGN / 2.0, rect.center().y); - paint_shapes_sign(ui.painter(), center, count, color); - return resp.on_hover_text(count.hint()); - } resp } @@ -1396,7 +1257,6 @@ fn flow( label, numbered, color, - shapes, } => { let current = *id == n.cursor; // After the editor the flow starts anew: with the move number. @@ -1405,7 +1265,7 @@ fn flow( } else { label }; - let resp = move_chip(ui, label, *color, current, *shapes); + let resp = move_chip(ui, label, *color, current); handle_move_response(ui, &resp, n, *id, out); } Token::Comment { slot, text } => { @@ -1471,7 +1331,6 @@ fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec) label, numbered, color: sym_color, - shapes: n.shapes.and_then(|s| s.get(&node)).copied(), }); let after = comment_text(nd.comments_after()); if !after.is_empty() { @@ -1502,54 +1361,3 @@ fn line_tokens(n: &Notation, first: NodeId, dark: bool, tokens: &mut Vec) } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn shape_counts_find_arrows_and_circles_of_comments_only() { - let game = chess_core::parse_str( - "{[%csl Re4]} 1. e4 {[%cal Gg1f3,Gf1c4] [%csl Ga8] [%clk 0:01:00]} e5 {plain} \ - (1... c5 {[%csl Yd5]}) 2. Nf3 {[%eval 0.3]} *", - ) - .game; - let counts = shape_counts(&game); - let e4 = game.main_child(NodeId::ROOT).unwrap(); - let c5 = game.variations(e4)[0]; - assert_eq!(counts.len(), 3, "{counts:?}"); - assert_eq!( - counts[&NodeId::ROOT], - ShapeCount { - arrows: 0, - circles: 1 - } - ); - assert_eq!( - counts[&e4], - ShapeCount { - arrows: 2, - circles: 1 - } - ); - assert_eq!( - counts[&c5], - ShapeCount { - arrows: 0, - circles: 1 - } - ); - } - - #[test] - fn the_sign_hint_leaves_out_a_count_of_none() { - crate::i18n::set_lang(crate::i18n::Lang::En); - let hint = |arrows, circles| ShapeCount { arrows, circles }.hint(); - assert_eq!( - hint(2, 1), - "Arrows: 2 · circles: 1 — shown on the board at this move" - ); - assert_eq!(hint(2, 0), "Arrows: 2 — shown on the board at this move"); - assert_eq!(hint(0, 1), "Circles: 1 — shown on the board at this move"); - } -} diff --git a/apps/desktop/src/online.rs b/apps/desktop/src/online.rs index 1385d58..dae2c32 100644 --- a/apps/desktop/src/online.rs +++ b/apps/desktop/src/online.rs @@ -1,15 +1,14 @@ //! Games from Lichess and Chess.com on the desktop: the databases live in //! `/online/`; the downloads themselves are the `online-games` crate's //! (shared with the Android app). Both public APIs are probed at start; a platform that -//! does not answer as expected (offline, the API changed) is simply not offered. The -//! web version has no online games: there only the names of such databases are known. +//! does not answer as expected (offline, the API changed) is simply not offered. use std::path::{Path, PathBuf}; +use std::time::Duration; -pub use online_games::{Account, Platform, State}; -#[cfg(not(web))] pub use online_games::{ - Done, Failure, LICHESS_RATE, Lookup, Progress, download, lookup, probe_all, valid_nick, + Account, Done, Failure, LICHESS_RATE, Lookup, Platform, Progress, State, download, lookup, + probe_all, valid_nick, }; /// Where the online databases live. @@ -44,20 +43,18 @@ pub fn ago(t: i64) -> String { } } -#[cfg(not(web))] /// The probe results and what the window shows, kept by the application. pub struct Probe { job: Option>, pub available: [bool; 2], /// When the last probe finished (a platform that did not answer is asked again /// after [`Probe::RETRY`]: the machine may have come online). - last: Option, + last: Option, ctx: egui::Context, } -#[cfg(not(web))] impl Probe { - const RETRY: std::time::Duration = std::time::Duration::from_secs(300); + const RETRY: Duration = Duration::from_secs(300); /// Starts probing both platforms in the background. pub fn start(ctx: &egui::Context) -> Probe { @@ -85,11 +82,7 @@ impl Probe { pub fn poll(&mut self) { if let Some(rx) = &self.job - && let Some(a) = match rx.try_recv() { - Ok(a) => Some(a), - Err(std::sync::mpsc::TryRecvError::Empty) => None, - Err(std::sync::mpsc::TryRecvError::Disconnected) => Some([false; 2]), - } + && let Ok(a) = rx.try_recv() { // A platform that answered once stays offered for the session (a later // failure shows as an error in the window). @@ -97,7 +90,7 @@ impl Probe { *have |= now; } self.job = None; - self.last = Some(web_time::Instant::now()); + self.last = Some(std::time::Instant::now()); } if self.job.is_none() && !self.available.iter().all(|a| *a) { match self.last { @@ -113,68 +106,7 @@ impl Probe { self.available.iter().any(|a| *a) } - pub fn pending(&self) -> bool { - self.job.is_some() - } - - /// An explicit retry from the online-games dialog, without duplicate jobs. - pub fn retry(&mut self) { - if !self.pending() { - self.spawn(); - } - } - - #[cfg(test)] - pub(crate) fn pending_for_test( - ctx: &egui::Context, - ) -> (Self, std::sync::mpsc::Sender<[bool; 2]>) { - let (tx, rx) = std::sync::mpsc::channel(); - ( - Self { - job: Some(rx), - available: [false; 2], - last: None, - ctx: ctx.clone(), - }, - tx, - ) - } - pub fn has(&self, p: Platform) -> bool { self.available[p.index()] } } - -#[cfg(all(test, not(web)))] -mod tests { - use super::*; - - #[test] - fn probe_distinguishes_pending_unavailable_ready_and_disconnected() { - let ctx = egui::Context::default(); - let (mut probe, tx) = Probe::pending_for_test(&ctx); - assert!(probe.pending()); - assert!(!probe.any()); - probe.retry(); // An in-flight request is kept, never duplicated. - tx.send([false, false]).unwrap(); - probe.poll(); - assert!(!probe.pending()); - assert!(!probe.any()); - - let (mut probe, tx) = Probe::pending_for_test(&ctx); - tx.send([true, false]).unwrap(); - probe.poll(); - assert!(!probe.pending()); - assert!(probe.has(Platform::Lichess)); - assert!(!probe.has(Platform::ChessCom)); - - let (mut probe, tx) = Probe::pending_for_test(&ctx); - drop(tx); - probe.poll(); - assert!( - !probe.pending(), - "a failed worker must not leave a perpetual check" - ); - assert!(!probe.any()); - } -} diff --git a/apps/desktop/src/online_ui.rs b/apps/desktop/src/online_ui.rs index 3186754..249cf18 100644 --- a/apps/desktop/src/online_ui.rs +++ b/apps/desktop/src/online_ui.rs @@ -37,7 +37,7 @@ struct Job { work: Background>, /// When Stop was pressed: a download that does not stop soon (a stalled /// connection) leaves the list; its database stays claimed until it ends. - stopped: Option, + stopped: Option, /// Started on its own at the program's start: says something only when it added /// games (no "no new games" on every start, no error over a network that is off). quiet: bool, @@ -198,7 +198,7 @@ impl OnlineDialog { for j in &self.jobs { j.work.cancel(); } - let start = web_time::Instant::now(); + let start = std::time::Instant::now(); while !self.jobs.is_empty() && start.elapsed() < std::time::Duration::from_secs(3) { self.jobs.retain(|j| j.work.poll().is_none()); std::thread::sleep(std::time::Duration::from_millis(30)); @@ -274,8 +274,7 @@ impl OnlineDialog { } /// Collects finished work; the window itself when open. - pub fn show(&mut self, ctx: &egui::Context, probe: &mut Probe) -> Vec { - probe.poll(); + pub fn show(&mut self, ctx: &egui::Context, probe: &Probe) -> Vec { let mut events = Vec::new(); if let Some(l) = &self.lookup && let Some(r) = l.poll() @@ -355,7 +354,7 @@ impl OnlineDialog { events } - fn body(&mut self, ui: &mut Ui, probe: &mut Probe, events: &mut Vec) { + fn body(&mut self, ui: &mut Ui, probe: &Probe, events: &mut Vec) { ui.label( RichText::new(tr( "Any player's games — yours, a pupil's, an opponent's — become a database here, to search and analyse. Only the nickname is needed, no login.", @@ -363,22 +362,6 @@ impl OnlineDialog { .weak(), ); ui.add_space(6.0); - if !probe.any() { - if probe.pending() { - ui.add(egui::Label::new(tr("Checking access to Lichess and Chess.com…")).wrap()); - } else { - ui.add( - egui::Label::new(tr( - "Couldn't connect. Check your internet connection and try again.", - )) - .wrap(), - ); - if ui.button(tr("Retry")).clicked() { - probe.retry(); - } - } - ui.add_space(6.0); - } let both = probe.has(Platform::Lichess) && probe.has(Platform::ChessCom); let mut enter = false; ui.horizontal(|ui| { @@ -659,7 +642,7 @@ impl OnlineDialog { self.jobs[k].work.cancel(); self.jobs[k] .stopped - .get_or_insert_with(web_time::Instant::now); + .get_or_insert_with(std::time::Instant::now); } ui.label( RichText::new(tr( @@ -710,74 +693,3 @@ impl OnlineDialog { } } } - -#[cfg(test)] -mod tests { - use super::*; - - fn rendered_text(dialog: &mut OnlineDialog, probe: &mut Probe) -> Vec { - let ctx = egui::Context::default(); - let mut text = Vec::new(); - for frame in 0..2 { - let output = ctx.run_ui( - egui::RawInput { - screen_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(960.0, 900.0), - )), - time: Some(f64::from(frame)), - ..Default::default() - }, - |ui| { - egui::CentralPanel::default().show(ui, |ui| { - dialog.body(ui, probe, &mut Vec::new()); - }); - }, - ); - text = output - .shapes - .iter() - .filter_map(|s| match &s.shape { - egui::Shape::Text(t) => Some(t.galley.text().to_owned()), - _ => None, - }) - .collect(); - output.drop_without_applying_deltas(); - } - text - } - - #[test] - fn early_online_entry_explains_probe_state_and_only_offers_ready_platforms() { - let ctx = egui::Context::default(); - let (mut probe, tx) = Probe::pending_for_test(&ctx); - let mut dialog = OnlineDialog::default(); - dialog.open(); - dialog.nick = "SomePlayer".to_owned(); - let text = rendered_text(&mut dialog, &mut probe); - assert!( - text.iter() - .any(|t| t == tr("Checking access to Lichess and Chess.com…")) - ); - assert!(!text.iter().any(|t| t == "Lichess" || t == "Chess.com")); - tx.send([false, false]).unwrap(); - probe.poll(); - let text = rendered_text(&mut dialog, &mut probe); - assert!(text.iter().any(|t| t == tr("Couldn't connect. Check your internet connection and try again."))); - assert!(text.iter().any(|t| t == tr("Retry"))); - assert_eq!(dialog.nick, "SomePlayer"); - - let (mut probe, tx) = Probe::pending_for_test(&ctx); - tx.send([true, false]).unwrap(); - probe.poll(); - let text = rendered_text(&mut dialog, &mut probe); - assert!(text.iter().any(|t| t == "Lichess")); - assert!(!text.iter().any(|t| t == "Chess.com")); - assert!( - !text - .iter() - .any(|t| t == tr("Checking access to Lichess and Chess.com…")) - ); - assert_eq!(dialog.nick, "SomePlayer"); - } -} diff --git a/apps/desktop/src/opening_layout.rs b/apps/desktop/src/opening_layout.rs deleted file mode 100644 index c79ce6e..0000000 --- a/apps/desktop/src/opening_layout.rs +++ /dev/null @@ -1,600 +0,0 @@ -//! 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 table of repertoires still shows its numbers whole. -pub(crate) const SIDE_LEAST: f32 = 360.0; -/// Where the width the user dragged the panel to is kept for the app to save -/// (`Settings::opening_side_width`). -pub(crate) const SIDE_WIDTH_ID: &str = "opening_side_width"; -/// 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); - let id = egui::Id::new(SIDE_WIDTH_ID); - let kept = ui.ctx().data(|d| d.get_temp::(id)); - let default = kept.unwrap_or_else(|| side_default(width, room)); - let handle = egui::Id::new("opening_side").with("__resize"); - // Until the user drags it, the panel follows the window: a window that opens - // small and grows gets the width of its final size, not of its first frame. - let dragging = ui - .ctx() - .read_response(handle) - .is_some_and(|r| r.dragged() || r.drag_stopped()); - if kept.is_none() && !dragging { - ui.ctx().data_mut(|d| { - d.remove::(egui::Id::new("opening_side")) - }); - } - let panel = egui::Panel::right("opening_side") - .resizable(true) - .default_size(default.clamp(SIDE_LEAST, most)) - .size_range(SIDE_LEAST..=most) - .show(ui, |ui| side(this, ui)); - // The width the user dragged to is kept; a window that squeezes the panel does - // not change it. - if ui - .ctx() - .read_response(handle) - .is_some_and(|r| r.drag_stopped()) - { - let shown = panel.response.rect.width().round(); - ui.ctx().data_mut(|d| d.insert_temp(id, shown)); - } - panel - }; - 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 panel's width before the user drags it: about a third of the window, the board -/// keeping its room. -pub(crate) fn side_default(width: f32, room: f32) -> f32 { - (width * 0.36).clamp(380.0, 560.0).min(room) -} - -/// 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 -} - -/// 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); - 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) - } -} - -/// `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 { - 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) -> egui::Image<'static> { - crate::widgets::side_king(side == LearningSide::White, KING) -} - -/// The side of the king of [`king`] (as a 14-point ♔ took). -pub(crate) const KING: f32 = 16.0; - -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}"), - }) -} - -/// "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 - .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, - temporary_shapes: 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 deleted file mode 100644 index 48f0f58..0000000 --- a/apps/desktop/src/opening_lines.rs +++ /dev/null @@ -1,566 +0,0 @@ -//! 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 { - layout::path_text(&self.game, node) - } - - 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 = layout::card_inner(ui, SELECTED_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 = 4.0; - if self.cursor == NodeId::ROOT { - layout::line(ui, RichText::new(tr("Start position")).strong()); - } else { - layout::line_left(ui, &self.path_label(self.cursor), true); - } - 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 · consolidated {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, - shapes: 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 deleted file mode 100644 index f75ea2b..0000000 --- a/apps/desktop/src/opening_session.rs +++ /dev/null @@ -1,2519 +0,0 @@ -//! 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, aggregate_scope, 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; -/// 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; -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, .. } => { - // 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)]) - } - } - } -} - -#[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, - }, - /// A hint, or the move revealed after another repertoire move. - Preview, -} - -#[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, - /// 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, -} - -pub struct OpeningSessionUi { - library: Library, - store: LearningStore, - session: LearningSessionSnapshot, - learning: LearningData, - kind: SessionKind, - 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, - 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 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, - 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 start_progress = progress_counts(&library, &learning, &whole); - 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, - unplayed_preview: 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, - start_progress, - whole_scope: whole, - 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; the showing is recorded - // only with the played move. - self.ready_since = None; - let id = unique_id(self.session.id()); - self.show_new_with_id_at(id, 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, 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, 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, - 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 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_for(attempt, CommitKind::Preview, 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; - } - let mut attempts: Vec<_> = self.unplayed_preview.take().into_iter().collect(); - attempts.push(attempt); - self.pending_commit = Some(PendingCommit { - attempts, - 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 => { - self.tally.hints += 1; - self.tally.miss(target); - } - 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.unplayed_preview = None; - 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(), - } - } - - /// «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()?; - 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() || self.stopped { - 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 self.pending_commit.is_some() { - // Between moves: the card keeps what it said. - return 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 { - // 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) - } - - 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 now = layout::now(); - 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 let Some(at) = item.next_review_at { - next = Some(next.map_or(at, |old| old.min(at))); - } - } - _ => unseen += 1, - } - } - let next_review = match next { - 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, - 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), - }); - } - - 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, - temporary_shapes: true, - 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 => { - // 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() { - 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 { - // 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()); - } - 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 path = self.path_text(); - 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, - &path, - |ui| { - if *state == State::Summary { - self.summary_body(ui); - } else { - self.comment(ui, state); - } - }, - 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 { - 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, - true, - ); - 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 = layout::card_inner(ui, CARD_H); - 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, - path: &str, - body: impl FnOnce(&mut Ui), - 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(); - 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()); - }); - // 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| { - 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 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); - } - }); - }); - }); - 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; - -/// (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 deleted file mode 100644 index 5933734..0000000 --- a/apps/desktop/src/opening_session_tests.rs +++ /dev/null @@ -1,2260 +0,0 @@ -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(1920.0, 1080.0), 1360.0), - (vec2(1400.0, 900.0), 896.0), - (vec2(960.0, 600.0), 580.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: 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")); - 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[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. - 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()); - // A finished session shows no «0 left». - assert_eq!(f.ui.counter(&State::Summary).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"); -} - -#[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); - 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()); -} - -#[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.passed_gain, summary.consolidated_gain), (2, 0)); -} - -#[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/apps/desktop/src/own_db.rs b/apps/desktop/src/own_db.rs index 7b86c65..6d5ebd7 100644 --- a/apps/desktop/src/own_db.rs +++ b/apps/desktop/src/own_db.rs @@ -82,20 +82,8 @@ pub enum AfterCreate { AddGame, /// Add a copy of a record of a table to it. AddRecord { path: PathBuf, index: usize }, - /// Copy the chosen records of a table into it, in the table's order (task 42): the - /// file is made by the copy, only when whole. - CopySelection { - path: PathBuf, - records: Vec, - sort: chess_import::chessbase::base::SortKey, - ascending: bool, - hidden: usize, - }, } -/// From this many chosen games on, the dialog says the copy may take a while. -const MANY_GAMES: usize = 50_000; - pub struct NewBaseDialog { pub name: String, pub dir: PathBuf, @@ -133,7 +121,7 @@ impl NewBaseDialog { } } - pub fn path(&self) -> PathBuf { + fn path(&self) -> PathBuf { self.dir.join(format!("{}.pgn", self.stem())) } @@ -155,41 +143,6 @@ impl NewBaseDialog { egui::Modal::new(egui::Id::new("new_base")).show(ctx, |ui| { ui.set_width(440.0); ui.heading(tr("New database")); - let copy = matches!(self.after, AfterCreate::CopySelection { .. }); - if let AfterCreate::CopySelection { - path, - records, - hidden, - .. - } = &self.after - { - let weak = |ui: &mut egui::Ui, text: String| { - ui.add(egui::Label::new(RichText::new(text).weak()).truncate()); - }; - weak( - ui, - trf( - "From the selection: {games} from «{src}»", - &[ - ("games", &crate::i18n::games(records.len())), - ("src", &base_name(path)), - ], - ), - ); - if *hidden > 0 { - weak( - ui, - trf("{k} of them are hidden by the filter now", &[("k", hidden)]), - ); - } - if records.len() >= MANY_GAMES { - weak( - ui, - tr("Many games: writing may take a few minutes; you can cancel it") - .to_owned(), - ); - } - } ui.add_space(8.0); ui.label(tr("Title")); let check = self.check(); @@ -242,21 +195,10 @@ impl NewBaseDialog { let enter = ui.input(|i| i.key_pressed(Key::Enter)); match &check { Ok(false) => { - let label = if copy { - tr("Create and copy") - } else { - tr("Create") - }; - if crate::widgets::primary(ui, label).clicked() || enter { + if crate::widgets::primary(ui, tr("Create")).clicked() || enter { out = Some(NewBaseOutcome::Create(self.path())); } } - // The copy goes into a new file only: the one there is not touched. - Ok(true) if copy => { - ui.add_enabled_ui(false, |ui| { - crate::widgets::primary(ui, tr("Create and copy")) - }); - } Ok(true) => { if crate::widgets::primary(ui, tr("Put it on the shelf")).clicked() || enter @@ -267,12 +209,9 @@ impl NewBaseDialog { // The same main button, only disabled: the row does not jump // when the first letter is typed. Err(_) => { - let label = if copy { - tr("Create and copy") - } else { - tr("Create") - }; - ui.add_enabled_ui(false, |ui| crate::widgets::primary(ui, label)); + ui.add_enabled_ui(false, |ui| { + crate::widgets::primary(ui, tr("Create")) + }); } } if ui.button(tr("Cancel")).clicked() { diff --git a/apps/desktop/src/platform/clipboard.rs b/apps/desktop/src/platform/clipboard.rs deleted file mode 100644 index 82c8cd3..0000000 --- a/apps/desktop/src/platform/clipboard.rs +++ /dev/null @@ -1,50 +0,0 @@ -//! Reading the clipboard on request («Paste PGN», «Paste a line»): at once on a -//! computer; in a browser asked of it (it may ask the user, and answers later). -//! Writing needs nothing of this: `egui::Context::copy_text` works everywhere. - -use std::sync::{Arc, Mutex}; - -/// A reading of the clipboard under way. -pub struct Reading { - text: Arc>>>, -} - -impl Reading { - /// The text once read (`Some(None)`: empty, refused or unavailable). - pub fn poll(&self) -> Option> { - self.text.lock().ok()?.take() - } -} - -/// Starts reading the clipboard's text; `ctx` is woken when it is there. -pub fn read_text(ctx: &egui::Context) -> Reading { - let text = Arc::new(Mutex::new(None)); - #[cfg(not(web))] - { - let _ = ctx; - let read = arboard::Clipboard::new() - .and_then(|mut c| c.get_text()) - .ok(); - if let Ok(mut t) = text.lock() { - *t = Some(read); - } - } - #[cfg(web)] - { - let (slot, ctx) = (text.clone(), ctx.clone()); - wasm_bindgen_futures::spawn_local(async move { - let read = match web_sys::window().map(|w| w.navigator().clipboard()) { - Some(c) => wasm_bindgen_futures::JsFuture::from(c.read_text()) - .await - .ok() - .and_then(|v| v.as_string()), - None => None, - }; - if let Ok(mut t) = slot.lock() { - *t = Some(read); - } - ctx.request_repaint(); - }); - } - Reading { text } -} diff --git a/apps/desktop/src/platform/files.rs b/apps/desktop/src/platform/files.rs deleted file mode 100644 index a67d224..0000000 --- a/apps/desktop/src/platform/files.rs +++ /dev/null @@ -1,475 +0,0 @@ -//! The files the user opens and saves: the system's dialogs on a computer; in a -//! browser its file chooser, files dropped on the page, and downloads. A file the user -//! gives the page is only read (decisions «Веб-версия»): it gets a path of the page's -//! file tree for the session and is opened by that path like a file on a disk. Chrome -//! and Edge remember a chosen file for the next visit ([`super::web::remembered`]). - -use std::path::PathBuf; - -/// The extensions of the databases the program opens (both cases for the dialogs of -/// systems that tell them apart). -const DATABASES: [&str; 10] = [ - "pgn", "PGN", "cbh", "CBH", "cbv", "CBV", "zip", "ZIP", "7z", "7Z", -]; - -/// Databases a browser does not open: their files together larger than this (the -/// program for the computer opens them). -pub const TOO_BIG: u64 = 2_000_000_000; - -/// What the user chose or dropped: the databases to open, the ones left out because -/// they are too big for a browser (name, bytes of their files), the ChessBase -/// databases not all files of which were given (the name of their `.cbh`), whether a -/// chosen (or, on a computer, dropped) folder held no database, and the files dropped -/// on a computer's window that are no databases (their names). -#[derive(Debug, Default, PartialEq)] -pub struct Picked { - pub paths: Vec, - pub too_big: Vec<(String, u64)>, - pub incomplete: Vec, - pub empty_folder: bool, - pub unsupported: Vec, - /// Files dropped on a computer's window that are no longer there (their names). - pub missing: Vec, -} - -/// The files the user gave the page, made databases: the ChessBase ones of their -/// several files (`chess_import::group_chosen`), each kept for the session in a folder -/// of its own. Also the files of each database kept (its path, their places in -/// `files`), for the browser to remember. -#[cfg(web)] -pub(super) fn gather( - files: &[web_sys::File], - folder: bool, -) -> (Picked, Vec<(PathBuf, Vec)>) { - let names: Vec = files.iter().map(|f| f.name()).collect(); - let refs: Vec<&str> = names.iter().map(String::as_str).collect(); - let chosen = chess_import::group_chosen(&refs, folder); - let mut picked = Picked { - incomplete: chosen.incomplete, - ..Picked::default() - }; - let mut kept = Vec::new(); - for db in chosen.databases { - let size: u64 = db.iter().map(|&i| files[i].size() as u64).sum(); - if size > TOO_BIG { - picked.too_big.push((names[db[0]].clone(), size)); - continue; - } - let path = super::web::vfs::add_opened(db.iter().map(|&i| files[i].clone()).collect()); - picked.paths.push(path.clone()); - kept.push((path, db)); - } - picked.empty_folder = folder - && picked.paths.is_empty() - && picked.too_big.is_empty() - && picked.incomplete.is_empty(); - (picked, kept) -} - -/// A ChessBase database's `.cbh` given without the files it cannot be read without -/// (a browser has only the files the user gave it). -pub fn chessbase_incomplete(path: &std::path::Path) -> bool { - #[cfg(web)] - { - let cbh = path - .extension() - .is_some_and(|e| e.eq_ignore_ascii_case("cbh")); - cbh && super::web::vfs::database_files(path).is_ok_and(|files| { - !files - .iter() - .any(|(name, _)| name.to_lowercase().ends_with(".cbg")) - }) - } - #[cfg(not(web))] - { - let _ = path; - false - } -} - -/// How the user's file `path` is named to the user: on a computer its path, in a -/// browser its name (the page's own places, `/opened/…`, mean nothing to the user). -pub fn shown(path: &std::path::Path) -> String { - #[cfg(web)] - return path - .file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default(); - #[cfg(not(web))] - path.display().to_string() -} - -/// A file the browser holds for this visit only (one the user chose or dropped): after -/// a reload it is gone, the user chooses it again or keeps a copy. Never on a computer. -pub fn session_only(path: &std::path::Path) -> bool { - #[cfg(web)] - return path.starts_with(super::web::vfs::OPENED); - #[cfg(not(web))] - { - let _ = path; - false - } -} - -/// Keeps a copy of the session database `path` (all its files) in the browser's -/// storage, where it stays between visits; `then` gets the copy's path. Refused when -/// the browser gives the site too little room (the size and what is free, for the -/// message). -#[cfg(web)] -pub fn keep_copy(path: &std::path::Path, then: impl FnOnce(Result) + 'static) { - use wasm_bindgen::JsCast; - let parts = match super::web::vfs::database_files(path) { - Ok(p) => p, - Err(e) => return then(Err(KeepCopy::Failed(e.to_string()))), - }; - let need: u64 = parts - .iter() - .map(|(_, s)| match s.dyn_ref::() { - Some(b) => b.size() as u64, - None => js_sys::Reflect::get(s, &"length".into()) - .ok() - .and_then(|l| l.as_f64()) - .unwrap_or(0.0) as u64, - }) - .sum(); - if let Some(free) = super::storage_free() - && need + need / 10 > free - { - return then(Err(KeepCopy::NoRoom { need, free })); - } - // A folder of its own, as the database had: the names stay as they were. - let dir = super::data_dir() - .unwrap_or_default() - .join("copies") - .join((js_sys::Date::now() as u64).to_string()); - let first = dir.join(&parts[0].0); - wasm_bindgen_futures::spawn_local(async move { - for (name, source) in parts { - let bytes = match source.dyn_into::() { - Ok(blob) => match wasm_bindgen_futures::JsFuture::from(blob.array_buffer()).await { - Ok(buf) => js_sys::Uint8Array::new(&buf).to_vec(), - Err(e) => return then(Err(KeepCopy::Failed(format!("{e:?}")))), - }, - Err(array) => js_sys::Uint8Array::new(&array).to_vec(), - }; - if let Err(e) = super::fs::write_atomic(&dir.join(name), &bytes) { - return then(Err(KeepCopy::Failed(e.to_string()))); - } - } - then(Ok(first)); - }); -} - -/// Why no copy was kept. -#[cfg(web)] -pub enum KeepCopy { - NoRoom { need: u64, free: u64 }, - Failed(String), -} - -/// Asks the user for databases to open; `then` gets what was chosen (nothing when the -/// user cancelled). The dialog does not hold the screen: `then` comes later. -pub fn pick_databases(then: impl FnOnce(Picked) + Send + 'static) { - #[cfg(not(web))] - { - use crate::i18n::tr; - let _ = std::thread::Builder::new() - .name("dialog".into()) - .spawn(move || { - let picked = rfd::FileDialog::new() - .set_title(tr("Open database")) - .add_filter(tr("Chess databases"), &DATABASES) - .add_filter("PGN", &["pgn", "PGN"]) - .add_filter(tr("All files"), &["*"]) - .pick_files(); - then(Picked { - paths: picked.unwrap_or_default(), - ..Picked::default() - }); - }); - } - #[cfg(web)] - { - let extensions: Vec = DATABASES - .iter() - .step_by(2) - .map(|e| format!(".{e}")) - .collect(); - if super::web::remembered::supported() { - super::web::remembered::pick(&extensions, then); - } else { - super::web::page::pick_files(&extensions.join(","), move |files| { - then(gather(&files, false).0) - }); - } - } -} - -/// Asks the user for a database's folder (a ChessBase database is several files): its -/// databases are found by their files' names. Chrome and Edge remember the folder. -#[cfg(web)] -pub fn pick_database_folder(then: impl FnOnce(Picked) + Send + 'static) { - if super::web::remembered::supported_folder() { - super::web::remembered::pick_folder(then); - } else { - super::web::page::pick_folder(move |files| then(gather(&files, true).0)); - } -} - -/// The browser remembers the files chosen in its dialog for the next visit (Chrome, -/// Edge); the others, and a computer, have no need or no way. -pub fn remembers_chosen() -> bool { - #[cfg(web)] - return super::web::remembered::supported(); - #[cfg(not(web))] - false -} - -/// The browser remembers the file `path` of an earlier visit and asks the user before -/// the page reads it again ([`allow_reading`]). Never on a computer. -pub fn waiting_to_read(path: &std::path::Path) -> bool { - #[cfg(web)] - return super::web::remembered::waiting(path); - #[cfg(not(web))] - { - let _ = path; - false - } -} - -/// Asks the browser to let the page read the remembered file `path` again (soon after -/// the user's click); `then`: whether it is back. -#[cfg(web)] -pub fn allow_reading(path: &std::path::Path, then: impl FnOnce(bool) + 'static) { - super::web::remembered::allow(path, then); -} - -/// The file `path` left the library: a browser forgets it too. -pub fn forget(path: &std::path::Path) { - #[cfg(web)] - super::web::remembered::forget(path); - #[cfg(not(web))] - let _ = path; -} - -/// The files dropped on the window in this frame, as databases to open: `then` gets -/// their paths once read (in a browser they are kept for the session like chosen -/// ones; on a computer they are opened where they are, as «Add database» does). -pub fn take_dropped(ctx: &egui::Context, then: impl FnOnce(Picked) + Send + 'static) { - #[cfg(not(web))] - { - let paths: Vec = ctx.input(|i| { - i.raw - .dropped_files - .iter() - .map(|f| f.path().to_path_buf()) - .filter(|p| p.is_absolute()) - .collect() - }); - if paths.is_empty() { - return; - } - // Folders are listed and files' neighbours looked at: off the screen's thread. - let _ = std::thread::Builder::new() - .name("dropped".into()) - .spawn(move || then(sort_dropped(&paths))); - } - #[cfg(web)] - { - let files: Vec = ctx.input(|i| { - i.raw - .dropped_files - .iter() - .filter_map(|f| f.web_file().cloned()) - .collect() - }); - if files.is_empty() { - return; - } - then(gather(&files, false).0); - } -} - -/// Files are dragged over the window now (the page shows where they go). -pub fn dragging(ctx: &egui::Context) -> bool { - ctx.input(|i| !i.raw.hovered_files.is_empty()) -} - -/// The extensions of the other files of a ChessBase database (beside its `.cbh`). -#[cfg(not(web))] -const CHESSBASE_PARTS: [&str; 14] = [ - "cbg", "cba", "cbp", "cbt", "cbc", "cbs", "cbj", "cbe", "cbm", "cbb", "cbgi", "cbtt", "cbpi", - "cbl", -]; - -/// The databases of the files and folders dropped on a computer's window: a file of -/// [`chess_import::EXTENSIONS`] is one; another file of a ChessBase database (its -/// `.cbg`, `.cba`, …: [`CHESSBASE_PARTS`]) stands for the `.cbh` of the same name -/// beside it; a folder gives the databases in it. Each database once (its real file), -/// in the order dropped; a file no longer there and a file of no database are named. -#[cfg(not(web))] -fn sort_dropped(paths: &[PathBuf]) -> Picked { - use std::collections::{HashMap, HashSet}; - let mut picked = Picked::default(); - let mut seen = HashSet::new(); - // Each folder is listed once, however many of its files were dropped. - let mut listed: HashMap> = HashMap::new(); - let mut list = |dir: &std::path::Path| -> Vec { - listed - .entry(dir.to_path_buf()) - .or_insert_with(|| { - let mut files: Vec = std::fs::read_dir(dir) - .map(|entries| { - entries - .flatten() - .map(|e| e.path()) - .filter(|f| f.is_file()) - .collect() - }) - .unwrap_or_default(); - files.sort(); - files - }) - .clone() - }; - let name = |p: &std::path::Path| { - p.file_name() - .map_or_else(|| p.display().to_string(), |n| n.to_string_lossy().into()) - }; - for p in paths { - let found = if p.is_dir() { - let found: Vec = list(p) - .into_iter() - .filter(|f| chess_import::EXTENSIONS.contains(&extension(f).as_str())) - .collect(); - if found.is_empty() { - picked.empty_folder = true; - } - found - } else if !p.is_file() { - picked.missing.push(name(p)); - continue; - } else { - let ext = extension(p); - if chess_import::EXTENSIONS.contains(&ext.as_str()) { - vec![p.clone()] - } else if CHESSBASE_PARTS.contains(&ext.as_str()) - && let Some(cbh) = p.parent().and_then(|dir| cbh_beside(p, &list(dir))) - { - vec![cbh] - } else { - picked.unsupported.push(name(p)); - continue; - } - }; - for f in found { - if seen.insert(f.canonicalize().unwrap_or_else(|_| f.clone())) { - picked.paths.push(f); - } - } - } - picked -} - -/// The extension of `p`, in lower case. -#[cfg(not(web))] -fn extension(p: &std::path::Path) -> String { - p.extension() - .map(|e| e.to_string_lossy().to_lowercase()) - .unwrap_or_default() -} - -/// The `.cbh` of the ChessBase database the file `part` belongs to, among the files -/// of its folder (names differ in case in sets copied from Windows). -#[cfg(not(web))] -fn cbh_beside(part: &std::path::Path, folder: &[PathBuf]) -> Option { - let stem = part.file_stem()?.to_string_lossy().to_lowercase(); - let want = format!("{stem}.cbh"); - folder - .iter() - .find(|f| { - f.file_name() - .is_some_and(|n| n.to_string_lossy().to_lowercase() == want) - }) - .cloned() -} - -/// Gives `pgn` to the user as the file `name` (a download, where the browser puts -/// them). Only a browser does this: the desktop program saves into files it chose. -#[cfg(web)] -pub fn download_pgn(name: &str, pgn: &str) -> Result<(), String> { - super::web::page::download(name, "application/x-chess-pgn", pgn.as_bytes()) - .map_err(|e| format!("{e:?}")) -} - -#[cfg(all(test, not(web)))] -mod tests { - use super::*; - - #[test] - fn dropped_files_are_sorted_into_databases() { - let dir = std::env::temp_dir().join(format!("cp-dropped-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let base = dir.join("Mega"); - std::fs::create_dir_all(&base).unwrap(); - let touch = |p: &std::path::Path| std::fs::write(p, b"x").unwrap(); - let games = dir.join("games.PGN"); - let archive = dir.join("set.7z"); - let notes = dir.join("notes.txt"); - let cbh = base.join("Mega.CBH"); - let parts = ["Mega.cbg", "Mega.cba", "Mega.cbj", "Mega.CBTT"].map(|n| base.join(n)); - let ini = base.join("Mega.ini"); - let lonely = dir.join("lost.cbg"); - for p in [&games, &archive, ¬es, &cbh, &lonely, &ini] { - touch(p); - } - for p in &parts { - touch(p); - } - let cbv = base.join("Other.cbv"); - touch(&cbv); - let empty = dir.join("empty"); - std::fs::create_dir_all(&empty).unwrap(); - touch(&empty.join("readme.md")); - - // Files of each kind; all the files of a ChessBase database give it once. - let mut dropped = vec![games.clone(), archive.clone()]; - dropped.extend(parts.iter().cloned()); - dropped.push(cbh.clone()); - let picked = sort_dropped(&dropped); - assert_eq!( - picked.paths, - vec![games.clone(), archive.clone(), cbh.clone()] - ); - assert!(picked.unsupported.is_empty() && picked.missing.is_empty()); - assert!(!picked.empty_folder); - - // What is no database is named: another file, a ChessBase part without its - // .cbh, a file of an unknown kind beside a .cbh. - let picked = sort_dropped(&[notes.clone(), lonely.clone(), ini.clone(), games.clone()]); - assert_eq!(picked.paths, vec![games.clone()]); - assert_eq!(picked.unsupported, ["notes.txt", "lost.cbg", "Mega.ini"]); - - // A file no longer there: named, not taken. - let picked = sort_dropped(&[dir.join("gone.pgn"), games.clone()]); - assert_eq!(picked.paths, vec![games.clone()]); - assert_eq!(picked.missing, ["gone.pgn"]); - assert!(picked.unsupported.is_empty()); - - // A folder: its databases (by name); one without any is told. - let picked = sort_dropped(&[base.clone(), empty.clone()]); - assert_eq!(picked.paths, vec![cbh.clone(), cbv.clone()]); - assert!(picked.empty_folder); - - // The same file by a link and by its own path: once. - #[cfg(unix)] - { - let link = dir.join("link.pgn"); - std::os::unix::fs::symlink(&games, &link).unwrap(); - let picked = sort_dropped(&[link.clone(), games.clone()]); - assert_eq!(picked.paths, vec![link]); - } - - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/apps/desktop/src/platform/fs.rs b/apps/desktop/src/platform/fs.rs deleted file mode 100644 index fe980d1..0000000 --- a/apps/desktop/src/platform/fs.rs +++ /dev/null @@ -1,105 +0,0 @@ -//! Files of the program and the files the user opened: the disk on a computer; in a -//! browser the page's files ([`super::web::vfs`]): the program's data kept in the -//! browser's storage, the user's files in memory for the session. - -use std::io; -use std::path::Path; - -/// What is known of a file. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Meta { - pub len: u64, - /// Last change, ms since the Unix epoch (0: not known). - pub modified_ms: u64, - pub readonly: bool, -} - -pub fn read(path: &Path) -> io::Result> { - #[cfg(not(web))] - { - std::fs::read(path) - } - #[cfg(web)] - { - super::web::vfs::read(path) - } -} - -pub fn read_to_string(path: &Path) -> io::Result { - String::from_utf8(read(path)?).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) -} - -/// The first `len` bytes of the file (fewer when it is shorter). -pub fn read_head(path: &Path, len: usize) -> io::Result> { - #[cfg(not(web))] - { - use std::io::Read; - let mut head = Vec::with_capacity(len); - std::fs::File::open(path)? - .take(len as u64) - .read_to_end(&mut head)?; - Ok(head) - } - #[cfg(web)] - { - let mut all = super::web::vfs::read(path)?; - all.truncate(len); - Ok(all) - } -} - -/// Writes the file whole: a reader sees the old text or the new one, never a part -/// (on a computer through a temporary file and a rename; its folder is made). -pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { - #[cfg(not(web))] - { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension(format!("tmp{}", std::process::id())); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path).inspect_err(|_| { - let _ = std::fs::remove_file(&tmp); - }) - } - #[cfg(web)] - { - super::web::vfs::write(path, bytes.to_vec()) - } -} - -pub fn exists(path: &Path) -> bool { - meta(path).is_ok() -} - -pub fn meta(path: &Path) -> io::Result { - #[cfg(not(web))] - { - let m = std::fs::metadata(path)?; - let modified_ms = m - .modified() - .ok() - .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) - .map_or(0, |d| d.as_millis() as u64); - Ok(Meta { - len: m.len(), - modified_ms, - readonly: m.permissions().readonly(), - }) - } - #[cfg(web)] - { - super::web::vfs::meta(path) - } -} - -pub fn remove_file(path: &Path) -> io::Result<()> { - #[cfg(not(web))] - { - std::fs::remove_file(path) - } - #[cfg(web)] - { - super::web::vfs::remove(path) - } -} diff --git a/apps/desktop/src/platform/mod.rs b/apps/desktop/src/platform/mod.rs deleted file mode 100644 index 0e24de6..0000000 --- a/apps/desktop/src/platform/mod.rs +++ /dev/null @@ -1,172 +0,0 @@ -//! What differs between the desktop program and the web version (`docs/dev/web.md`). -//! -//! The interface asks this module, never the system, for: where the program keeps its -//! data ([`config_dir`] and the others), files ([`fs`]), background work ([`spawn`]), -//! the files the user opens or saves ([`files`]), the clipboard ([`clipboard`]) and -//! what the platform offers at all ([`CAPS`]). On a computer it is the system's -//! (`native.rs`); in a browser (`cfg(web)`) the page's (`web/`): the program's data in -//! the browser's storage (IndexedDB), the files the user opened in memory, background -//! work between frames. -#![cfg_attr(web, warn(unused))] - -use std::path::PathBuf; - -#[cfg(not(web))] -mod native; -#[cfg(not(web))] -use native as imp; -#[cfg(web)] -pub mod web; -#[cfg(web)] -use web as imp; - -pub mod clipboard; -pub mod files; -pub mod fs; -pub mod page; -pub mod pgn_store; - -/// What the platform offers the interface: a feature it lacks is not shown. -#[derive(Clone, Copy, Debug)] -pub struct Caps { - /// Checking for a new version and installing it (the web version is always the - /// latest: a reload brings it). - pub updates: bool, - /// Downloading games from Lichess and Chess.com. - pub online_games: bool, - /// Games against the computer (Maia, Rodent). - pub play: bool, - /// Preparing against an opponent. - pub prep: bool, - /// Machine translation of comments. - pub translation: bool, - /// The user's own PGN databases on the disk: new ones, games added and replaced. - pub own_databases: bool, - /// Engines as programs on the disk: chosen, downloaded, started. - pub engine_programs: bool, - /// The opening trainer. - pub training: bool, - /// Saving a game is a download of its PGN (the browser's files are not written). - pub download_pgn: bool, - /// The reference tab (what was played here in the databases) and the search of a - /// position in a database (not in the light web version). - pub reference: bool, - /// Several chosen games copied into a new database in the background (task 42). - pub batch_copy: bool, - /// The search for great moves over a database's list (task 27). - pub great_moves: bool, -} - -/// The features of this platform. -#[cfg(not(web))] -pub const CAPS: Caps = Caps { - updates: true, - online_games: true, - play: true, - prep: true, - translation: true, - own_databases: true, - engine_programs: true, - training: true, - download_pgn: false, - reference: true, - batch_copy: true, - great_moves: true, -}; - -/// The features of this platform: the light web version (`docs/decisions.md`, «Веб-версия»). -#[cfg(web)] -pub const CAPS: Caps = Caps { - updates: false, - online_games: false, - play: false, - prep: false, - translation: false, - own_databases: false, - engine_programs: false, - training: false, - download_pgn: true, - reference: false, - batch_copy: false, - great_moves: false, -}; - -/// The program's settings (`~/.config/chesspenguin`; in a browser, its storage). -pub fn config_dir() -> Option { - imp::config_dir() -} - -/// The program's data kept for good (`~/.local/share/chesspenguin`). -pub fn data_dir() -> Option { - imp::data_dir() -} - -/// Data the program can make again (`~/.cache/chesspenguin`). -pub fn cache_dir() -> Option { - imp::cache_dir() -} - -/// The sample databases: files of the program, written at the first start on a -/// computer; built in and only read in a browser. -pub fn examples_dir() -> Option { - imp::examples_dir() -} - -/// Runs `job` in the background and returns at once: on a thread of its own named -/// `name` on a computer; in a browser (which gives a page no threads) on the page's -/// thread after the current frame, so a job there is one finite piece of work, never a -/// loop that waits. The error: the job could not be started. -pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { - imp::spawn(name, job) -} - -/// Bytes the browser still gives the site to keep (its quota less what is used); `None` -/// on a computer and until the browser answered. -pub fn storage_free() -> Option { - #[cfg(web)] - return web::storage::usage().map(|(used, quota)| quota.saturating_sub(used)); - #[cfg(not(web))] - None -} - -/// A size for people in the interface's language: "340 KB", "96 MB", "9.6 GB" -/// («9,6 ГБ», «9,6 Go»: its units and its decimal sign). -pub fn size_text(bytes: u64) -> String { - use crate::i18n::{tr, trf}; - let b = bytes as f64; - let (n, unit) = if b >= 1e9 { - (format!("{:.1}", b / 1e9), "{n} GB") - } else if b >= 1e6 { - (format!("{:.0}", b / 1e6), "{n} MB") - } else { - (format!("{:.0}", (b / 1e3).max(1.0)), "{n} KB") - }; - // The key's own text where the language writes a decimal point. - let n = if tr("decimal comma") == "," { - n.replace('.', ",") - } else { - n - }; - trf(unit, &[("n", &n)]) -} - -/// A line for the program's log (`chesspenguin.log`; in a browser its console). -pub fn log(line: &str) { - #[cfg(not(web))] - crate::graphics::log(line); - #[cfg(web)] - log::info!("{line}"); -} - -/// Reads a database the library shows away from the screen's thread: its file on the -/// disk on a thread of its own (`progress` follows the reading), or in a browser the -/// file the user gave the page (or a sample built in) in the page's reader, a worker -/// (no progress). `done` gets the database: on that thread, or on the page's. -pub fn open_database( - path: &std::path::Path, - progress: impl FnMut(chess_core::ScanProgress) + Send + 'static, - cancel: std::sync::Arc, - done: impl FnOnce(Result) + Send + 'static, -) -> std::io::Result<()> { - imp::open_database(path, progress, cancel, done) -} diff --git a/apps/desktop/src/platform/native.rs b/apps/desktop/src/platform/native.rs deleted file mode 100644 index b416015..0000000 --- a/apps/desktop/src/platform/native.rs +++ /dev/null @@ -1,46 +0,0 @@ -//! The desktop program: the system's folders, files and threads. - -use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicBool; - -use chess_core::ScanProgress; -use chess_import::{ImportError, Opened}; - -fn project() -> Option { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") -} - -pub fn config_dir() -> Option { - project().map(|d| d.config_dir().to_path_buf()) -} - -pub fn data_dir() -> Option { - project().map(|d| d.data_dir().to_path_buf()) -} - -pub fn cache_dir() -> Option { - project().map(|d| d.cache_dir().to_path_buf()) -} - -pub fn examples_dir() -> Option { - project().map(|d| d.data_local_dir().join("examples")) -} - -pub fn spawn(name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { - std::thread::Builder::new() - .name(name.to_owned()) - .spawn(job) - .map(drop) -} - -pub fn open_database( - path: &Path, - mut progress: impl FnMut(ScanProgress) + Send + 'static, - cancel: std::sync::Arc, - done: impl FnOnce(Result) + Send + 'static, -) -> std::io::Result<()> { - let path = path.to_owned(); - spawn("db-open", move || { - done(chess_import::open(&path, &mut progress, &cancel)); - }) -} diff --git a/apps/desktop/src/platform/page.rs b/apps/desktop/src/platform/page.rs deleted file mode 100644 index ea73823..0000000 --- a/apps/desktop/src/platform/page.rs +++ /dev/null @@ -1,110 +0,0 @@ -//! The program as a page of a browser (docs/design/web-version.md §1.1, §1.3): a game -//! on the screen is an entry of the browser's history, so its «Back» means «← Library»; -//! unsaved work makes the browser ask before the page is left. A desktop program has -//! neither: nothing happens there. - -#[cfg(web)] -mod imp { - use std::cell::Cell; - - use wasm_bindgen::JsCast; - use wasm_bindgen::prelude::*; - - thread_local! { - /// The history has our entry for the game on the screen. - static IN_GAME: Cell = const { Cell::new(false) }; - /// «Back» was pressed (the entry left) and not taken yet. - static BACK: Cell = const { Cell::new(false) }; - /// Our own `history.back()`: its `popstate` is not the user's. - static OWN_BACK: Cell = const { Cell::new(false) }; - static LISTENING: Cell = const { Cell::new(false) }; - static WARN: Cell = const { Cell::new(false) }; - /// The page's `beforeunload`: the browser asks before the page is left. - static ASK: Closure = - Closure::new(|e: web_sys::BeforeUnloadEvent| { - e.prevent_default(); - e.set_return_value(""); - }); - } - - fn listen(ctx: &egui::Context) { - if LISTENING.replace(true) { - return; - } - let ctx = ctx.clone(); - let on_pop = Closure::::new(move || { - if OWN_BACK.replace(false) { - return; - } - if IN_GAME.replace(false) { - BACK.set(true); - ctx.request_repaint(); - } - }); - if let Some(w) = web_sys::window() { - let _ = w.add_event_listener_with_callback("popstate", on_pop.as_ref().unchecked_ref()); - } - // Listens as long as the page lives. - on_pop.forget(); - } - - pub fn game_shown(ctx: &egui::Context, shown: bool) { - listen(ctx); - let Some(history) = web_sys::window().and_then(|w| w.history().ok()) else { - return; - }; - if shown && !IN_GAME.get() { - let state = js_sys::Object::new(); - let _ = js_sys::Reflect::set(&state, &"cpGame".into(), &JsValue::TRUE); - if history.push_state(&state, "").is_ok() { - IN_GAME.set(true); - } - } else if !shown && IN_GAME.get() { - // The game left by the program's own button: its entry goes too. - IN_GAME.set(false); - OWN_BACK.set(true); - let _ = history.back(); - } - } - - pub fn take_back() -> bool { - BACK.replace(false) - } - - pub fn warn_on_leave(warn: bool) { - if WARN.replace(warn) == warn { - return; - } - let Some(w) = web_sys::window() else { return }; - if warn { - ASK.with(|ask| w.set_onbeforeunload(Some(ask.as_ref().unchecked_ref()))); - } else { - w.set_onbeforeunload(None); - } - } -} - -/// The game is on the screen (`true`) or not: kept in step with the browser's history. -pub fn game_shown(ctx: &egui::Context, shown: bool) { - #[cfg(web)] - imp::game_shown(ctx, shown); - #[cfg(not(web))] - let _ = (ctx, shown); -} - -/// The browser's «Back» left the game since the last call (then it is «← Library»). -pub fn take_back() -> bool { - #[cfg(web)] - return imp::take_back(); - #[cfg(not(web))] - false -} - -/// Whether leaving the page (closing the tab, reloading) should be asked about: the -/// browser asks in its own words. -pub fn warn_on_leave(warn: bool) { - #[cfg(web)] - imp::warn_on_leave(warn); - #[cfg(not(web))] - let _ = warn; -} diff --git a/apps/desktop/src/platform/pgn_store.rs b/apps/desktop/src/platform/pgn_store.rs deleted file mode 100644 index 3f85435..0000000 --- a/apps/desktop/src/platform/pgn_store.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! Writing games into a PGN database the library has open: its file on a computer -//! (`chess_core::pgn::store`, as before); in a browser the page's file of that path -//! (only the program's own: «My games»; the user's files are only read). The text -//! written is the same byte for byte. - -use std::path::Path; - -use chess_core::PgnDatabase; -use chess_core::pgn::store::{self, Appended, Removed, WriteError}; - -#[cfg(web)] -fn write(path: &Path, bytes: Vec) -> Result<(), WriteError> { - super::web::vfs::write(path, bytes).map_err(WriteError::Io) -} - -#[cfg(web)] -fn utf8(db: &PgnDatabase) -> Result<(), WriteError> { - if db.encoding() != chess_core::TextEncoding::Utf8 && !db.detected_encoding().ascii_only { - return Err(WriteError::Encoding); - } - Ok(()) -} - -/// Adds `record` at the end of `db` (the file `path`). -pub fn append(db: &PgnDatabase, path: &Path, record: &str) -> Result { - #[cfg(not(web))] - { - let _ = path; - store::append(db, record) - } - #[cfg(web)] - { - utf8(db)?; - let (bytes, offset) = store::appended(db, record); - write(path, bytes)?; - Ok(Appended { offset }) - } -} - -/// Replaces record `index` of `db` with `record`. -pub fn replace( - db: &PgnDatabase, - path: &Path, - index: usize, - record: &str, -) -> Result<(), WriteError> { - #[cfg(not(web))] - { - let _ = path; - store::replace(db, index, record) - } - #[cfg(web)] - { - utf8(db)?; - write(path, store::replaced(db, index, record)?) - } -} - -/// Removes record `index` of `db`; [`restore`] puts it back. -pub fn remove(db: &PgnDatabase, path: &Path, index: usize) -> Result { - #[cfg(not(web))] - { - let _ = path; - store::remove(db, index) - } - #[cfg(web)] - { - utf8(db)?; - let (bytes, gone) = store::removed(db, index)?; - write(path, bytes)?; - Ok(gone) - } -} - -/// Puts a removed record back at its place. -pub fn restore(db: &PgnDatabase, path: &Path, removed: &Removed) -> Result<(), WriteError> { - #[cfg(not(web))] - { - let _ = path; - store::restore(db, removed) - } - #[cfg(web)] - { - write(path, store::restored(db, removed)?) - } -} diff --git a/apps/desktop/src/platform/web/engine.rs b/apps/desktop/src/platform/web/engine.rs deleted file mode 100644 index 94d15df..0000000 --- a/apps/desktop/src/platform/web/engine.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! Stockfish 19 for the web version (npm `stockfish@19.0.1`, nmrugg/stockfish.js, -//! GPL-3.0): the single-threaded build, served by our site beside the program -//! (`/app/engine/`, apps/web/build.sh). Its `.wasm` (99 MB, 78 MB in Brotli) is -//! downloaded only when the user agrees (decisions «Веб-версия»), checked against its -//! SHA-256 and kept in the browser's Cache Storage. A worker of the engine gets it as a -//! `blob:` address after `#` (the script takes the wasm's address from there): no worker -//! downloads it again. -//! -//! Its search is that of the official Stockfish 19 (the same evaluations, node for node: -//! docs/research/web-version-tech.md §2.2), so a game review gives the same marks. - -use std::cell::RefCell; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; - -use sha2::{Digest, Sha256}; -use wasm_bindgen::JsCast; -use wasm_bindgen::JsValue; -use wasm_bindgen_futures::JsFuture; - -/// The engine's worker script and its WebAssembly, relative to the page. -pub const SCRIPT: &str = "engine/stockfish-19-single.js"; -const WASM: &str = "engine/stockfish-19-single.wasm"; -/// The wasm as published (`stockfish@19.0.1`, `bin/stockfish-19-single.wasm`). -pub const WASM_BYTES: u64 = 99_169_054; -const WASM_SHA256: &str = "991bede2f253ebb08ff01fcc48270f4b9c8e66b12d5bd5f8d6f52eb3e3b3a740"; -/// What travels over the network (the site sends it in Brotli). -pub const DOWNLOAD_MB: u64 = 78; -/// The cache of the engine; another version of it gets another name. -const CACHE: &str = "chesspenguin-engine-sf19.0.1"; - -thread_local! { - /// The cached wasm as a `blob:` address, once it is there. - static BLOB: RefCell> = const { RefCell::new(None) }; -} - -/// Why the engine could not be downloaded. -#[derive(Debug)] -pub enum Fetch { - Network(String), - Server(u16), - /// Not the published file. - Checksum, - /// The browser would not keep it (space, a private window). - Storage(String), - Cancelled, -} - -fn js(e: JsValue) -> String { - e.as_string() - .or_else(|| { - e.dyn_ref::() - .map(|e| String::from(e.message())) - }) - .unwrap_or_else(|| format!("{e:?}")) -} - -fn caches() -> Result { - web_sys::window().ok_or("no window")?.caches().map_err(js) -} - -async fn open() -> Result { - JsFuture::from(caches()?.open(CACHE)) - .await - .map_err(js)? - .dyn_into() - .map_err(js) -} - -/// Makes the cached engine usable (a `blob:` address); called at the start. -pub async fn probe() { - let found = async { - let cache = open().await?; - let hit = JsFuture::from(cache.match_with_str(WASM)) - .await - .map_err(js)?; - let Ok(response) = hit.dyn_into::() else { - return Ok::<_, String>(None); - }; - let blob: web_sys::Blob = JsFuture::from(response.blob().map_err(js)?) - .await - .map_err(js)? - .dyn_into() - .map_err(js)?; - if blob.size() as u64 != WASM_BYTES { - return Ok(None); - } - web_sys::Url::create_object_url_with_blob(&blob) - .map(Some) - .map_err(js) - }; - match found.await { - Ok(url) => BLOB.with_borrow_mut(|b| *b = url), - Err(e) => log::warn!("the engine's cache: {e}"), - } -} - -/// The address of a worker of the engine, once it is downloaded. -pub fn worker_script() -> Option { - BLOB.with_borrow(|b| b.as_ref().map(|url| format!("{SCRIPT}#{url}"))) -} - -/// Downloads the engine into the cache; `progress(done, total)` on the way. -pub async fn download(progress: impl Fn(u64, u64), cancel: Arc) -> Result<(), Fetch> { - let window = web_sys::window().ok_or_else(|| Fetch::Network("no window".into()))?; - let response: web_sys::Response = JsFuture::from(window.fetch_with_str(WASM)) - .await - .map_err(|e| Fetch::Network(js(e)))? - .dyn_into() - .map_err(|e| Fetch::Network(js(e)))?; - if !response.ok() { - return Err(Fetch::Server(response.status())); - } - let body = response - .body() - .ok_or_else(|| Fetch::Network("no body".into()))?; - let reader: web_sys::ReadableStreamDefaultReader = body - .get_reader() - .dyn_into() - .map_err(|e| Fetch::Network(js(e.into())))?; - let mut bytes: Vec = Vec::with_capacity(WASM_BYTES as usize); - let mut hasher = Sha256::new(); - loop { - if cancel.load(Ordering::Relaxed) { - let _ = reader.cancel(); - return Err(Fetch::Cancelled); - } - let chunk = JsFuture::from(reader.read()) - .await - .map_err(|e| Fetch::Network(js(e)))?; - let done = js_sys::Reflect::get(&chunk, &"done".into()) - .map(|d| d.is_truthy()) - .unwrap_or(true); - if done { - break; - } - let value: js_sys::Uint8Array = js_sys::Reflect::get(&chunk, &"value".into()) - .map_err(|e| Fetch::Network(js(e)))? - .dyn_into() - .map_err(|e| Fetch::Network(js(e)))?; - let start = bytes.len(); - bytes.resize(start + value.length() as usize, 0); - value.copy_to(&mut bytes[start..]); - hasher.update(&bytes[start..]); - if bytes.len() as u64 > WASM_BYTES { - return Err(Fetch::Checksum); - } - progress(bytes.len() as u64, WASM_BYTES); - } - let digest: String = hasher - .finalize() - .iter() - .map(|b| format!("{b:02x}")) - .collect(); - if bytes.len() as u64 != WASM_BYTES || digest != WASM_SHA256 { - return Err(Fetch::Checksum); - } - let storage = |e: JsValue| Fetch::Storage(js(e)); - let init = web_sys::ResponseInit::new(); - let headers = web_sys::Headers::new().map_err(storage)?; - headers - .set("Content-Type", "application/wasm") - .map_err(storage)?; - init.set_headers(&headers); - let stored = web_sys::Response::new_with_opt_u8_array_and_init(Some(&mut bytes), &init) - .map_err(storage)?; - let cache = open().await.map_err(Fetch::Storage)?; - JsFuture::from(cache.put_with_str(WASM, &stored)) - .await - .map_err(storage)?; - drop(bytes); - probe().await; - if worker_script().is_none() { - return Err(Fetch::Storage("the browser did not keep the engine".into())); - } - Ok(()) -} - -/// Removes the downloaded engine from the browser. -pub fn remove() { - if let Some(url) = BLOB.with_borrow_mut(Option::take) { - let _ = web_sys::Url::revoke_object_url(&url); - } - if let Ok(c) = caches() { - let _ = c.delete(CACHE); - } -} - -/// Whether the engine is downloaded and ready. -pub fn ready() -> bool { - BLOB.with_borrow(Option::is_some) -} - -/// Engines working at once for a game review: one per logical processor, as on a -/// computer, at most `limit` (each worker holds its own copy of the engine, ≈ 130 MB). -pub fn workers(limit: usize) -> usize { - let cpus = web_sys::window().map_or(1.0, |w| w.navigator().hardware_concurrency()) as usize; - cpus.clamp(1, limit) -} diff --git a/apps/desktop/src/platform/web/idb.rs b/apps/desktop/src/platform/web/idb.rs deleted file mode 100644 index 3641f1c..0000000 --- a/apps/desktop/src/platform/web/idb.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! The program's data in the browser's storage: one IndexedDB database, a store of -//! files by path, read whole at the start (settings and marks are small), every write -//! going there behind the interface, in the order made; and a store of the user's files -//! a Chromium browser remembers (their handles, by the page's path: [`super::remembered`]). - -use wasm_bindgen::JsCast; -use wasm_bindgen::prelude::*; - -const DB: &str = "chesspenguin"; -const STORE: &str = "files"; -const HANDLES: &str = "handles"; -/// 2: the store of handles. -const VERSION: u32 = 2; - -/// The request's outcome once it is done. -async fn done(request: &web_sys::IdbRequest) -> Result { - let promise = js_sys::Promise::new(&mut |resolve, reject| { - let ok = Closure::once_into_js(move |ev: web_sys::Event| { - let r = ev - .target() - .and_then(|t| t.dyn_into::().ok()) - .and_then(|r| r.result().ok()) - .unwrap_or(JsValue::UNDEFINED); - let _ = resolve.call1(&JsValue::NULL, &r); - }); - let err = Closure::once_into_js(move |ev: web_sys::Event| { - let _ = reject.call1(&JsValue::NULL, &ev); - }); - request.set_onsuccess(Some(ok.unchecked_ref())); - request.set_onerror(Some(err.unchecked_ref())); - }); - wasm_bindgen_futures::JsFuture::from(promise).await -} - -async fn open() -> Result { - let factory = web_sys::window() - .ok_or("no window")? - .indexed_db()? - .ok_or("no IndexedDB")?; - let request = factory.open_with_u32(DB, VERSION)?; - let upgrade = Closure::once_into_js(move |ev: web_sys::Event| { - if let Some(db) = ev - .target() - .and_then(|t| t.dyn_into::().ok()) - .and_then(|r| r.result().ok()) - .and_then(|r| r.dyn_into::().ok()) - { - for store in [STORE, HANDLES] { - if !db.object_store_names().contains(store) { - let _ = db.create_object_store(store); - } - } - } - }); - request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); - done(&request).await?.dyn_into() -} - -thread_local! { - /// The database once opened (`None` until then, or when the browser refused it: - /// a private window of some browsers; then nothing is kept between visits). - static OPENED: std::cell::RefCell> = - const { std::cell::RefCell::new(None) }; -} - -/// Everything kept: (path, bytes). Empty when the browser keeps nothing for the page. -pub async fn load_all() -> Vec<(String, Vec)> { - let db = match open().await { - Ok(db) => db, - Err(e) => { - log::warn!("browser storage unavailable: {e:?}"); - return Vec::new(); - } - }; - let read = async { - let tx = db.transaction_with_str(STORE)?; - let store = tx.object_store(STORE)?; - let keys = done(&store.get_all_keys()?).await?; - let values = done(&store.get_all()?).await?; - let keys: js_sys::Array = keys.dyn_into()?; - let values: js_sys::Array = values.dyn_into()?; - Ok::<_, JsValue>( - keys.iter() - .zip(values.iter()) - .filter_map(|(k, v)| { - let bytes = v.dyn_into::().ok()?.to_vec(); - Some((k.as_string()?, bytes)) - }) - .collect(), - ) - }; - let files = read.await.unwrap_or_else(|e| { - log::warn!("browser storage unreadable: {e:?}"); - Vec::new() - }); - OPENED.with_borrow_mut(|o| *o = Some(db)); - files -} - -fn store_named(name: &str) -> Option { - OPENED.with_borrow(|db| { - let tx = db - .as_ref()? - .transaction_with_str_and_mode(name, web_sys::IdbTransactionMode::Readwrite) - .ok()?; - tx.object_store(name).ok() - }) -} - -fn store() -> Option { - store_named(STORE) -} - -/// The handles kept: (the page's path, the handle). Read after [`load_all`]. -pub async fn handles() -> Vec<(String, JsValue)> { - let Some(db) = OPENED.with_borrow(|db| db.clone()) else { - return Vec::new(); - }; - let read = async { - let tx = db.transaction_with_str(HANDLES)?; - let store = tx.object_store(HANDLES)?; - let keys: js_sys::Array = done(&store.get_all_keys()?).await?.dyn_into()?; - let values: js_sys::Array = done(&store.get_all()?).await?.dyn_into()?; - Ok::<_, JsValue>( - keys.iter() - .zip(values.iter()) - .filter_map(|(k, v)| Some((k.as_string()?, v))) - .collect(), - ) - }; - read.await.unwrap_or_else(|e: JsValue| { - log::warn!("browser storage: remembered files unreadable: {e:?}"); - Vec::new() - }) -} - -pub fn put_handle(path: &str, handle: &JsValue) { - if let Some(store) = store_named(HANDLES) - && let Err(e) = store.put_with_key(handle, &JsValue::from_str(path)) - { - log::warn!("browser storage: cannot remember {path}: {e:?}"); - } -} - -pub fn delete_handle(path: &str) { - if let Some(store) = store_named(HANDLES) { - let _ = store.delete(&JsValue::from_str(path)); - } -} - -/// Keeps `bytes` as `path` (transactions of one page run in the order made). -pub fn put(path: String, bytes: Vec) { - if let Some(store) = store() { - let value = js_sys::Uint8Array::from(bytes.as_slice()); - if let Err(e) = store.put_with_key(&value, &JsValue::from_str(&path)) { - log::warn!("browser storage: cannot keep {path}: {e:?}"); - } - } -} - -pub fn delete(path: String) { - if let Some(store) = store() - && let Err(e) = store.delete(&JsValue::from_str(&path)) - { - log::warn!("browser storage: cannot delete {path}: {e:?}"); - } -} diff --git a/apps/desktop/src/platform/web/import.rs b/apps/desktop/src/platform/web/import.rs deleted file mode 100644 index dde9afd..0000000 --- a/apps/desktop/src/platform/web/import.rs +++ /dev/null @@ -1,316 +0,0 @@ -//! Opening a database without holding the page: a Web Worker runs a second instance of -//! the program (`import-worker.js` → [`answer`]) that reads the file — PGN, CBV, ZIP, -//! 7Z, converted and indexed — and gives back its text and index; the page puts the -//! database together from them without reading it again -//! (`chess_core::PgnDatabase::from_index`); the cards of the shelf only ask it how many -//! games a file holds. One worker serves the visit and reads the files one after -//! another, in the order they were given. - -use std::cell::RefCell; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -use chess_core::{PgnDatabase, PgnIndex}; -use chess_import::{Database, Format, ImportError, Opened, PgnDb, Unsupported}; -use serde::{Deserialize, Serialize}; -use wasm_bindgen::JsCast; -use wasm_bindgen::prelude::*; - -/// The worker's script, beside the page. -const SCRIPT: &str = "import-worker.js"; - -/// What the worker gives back besides the text. -#[derive(Serialize, Deserialize)] -struct Read { - index: PgnIndex, - /// Its place in [`Format::ALL`]. - format: usize, - notes: Vec, -} - -/// Why the worker could not read a file: [`ImportError`] in serde's terms. -#[derive(Serialize, Deserialize)] -enum Failure { - Io(String), - Corrupt(String), - Encrypted, - ChessBase2, - ChessBaseFiles, - Empty, - Cancelled, -} - -impl Failure { - fn of(e: ImportError) -> Failure { - match e { - ImportError::Io { source, .. } => Failure::Io(source.to_string()), - ImportError::Corrupt(s) => Failure::Corrupt(s), - ImportError::Unsupported(Unsupported::Encrypted) => Failure::Encrypted, - ImportError::Unsupported(Unsupported::ChessBase2) => Failure::ChessBase2, - ImportError::Unsupported(Unsupported::ChessBaseFiles) => Failure::ChessBaseFiles, - ImportError::Empty => Failure::Empty, - ImportError::Cancelled => Failure::Cancelled, - } - } - - fn error(self, path: &Path) -> ImportError { - match self { - Failure::Io(e) => io_error(path, e), - Failure::Corrupt(s) => ImportError::Corrupt(s), - Failure::Encrypted => ImportError::Unsupported(Unsupported::Encrypted), - Failure::ChessBase2 => ImportError::Unsupported(Unsupported::ChessBase2), - Failure::ChessBaseFiles => ImportError::Unsupported(Unsupported::ChessBaseFiles), - Failure::Empty => ImportError::Empty, - Failure::Cancelled => ImportError::Cancelled, - } - } -} - -fn io_error(path: &Path, e: impl ToString) -> ImportError { - ImportError::Io { - path: path.to_owned(), - source: std::io::Error::other(e.to_string()), - } -} - -fn set(object: &js_sys::Object, key: &str, value: &JsValue) { - let _ = js_sys::Reflect::set(object, &key.into(), value); -} - -thread_local! { - /// The worker's side: the files of the database being given, one by one (so that - /// the worker holds each file's bytes once: in the program, not also in the page's - /// script). - static GIVEN: RefCell)>> = const { RefCell::new(Vec::new()) }; -} - -/// The worker's side: one more file of the database to read (its own file first). -pub fn give(name: String, bytes: Vec) { - // The reader's panics to the console (the page's own hook is eframe's). - static HOOK: std::sync::Once = std::sync::Once::new(); - HOOK.call_once(|| { - std::panic::set_hook(Box::new(|info| { - web_sys::console::error_1(&format!("the reader: {info}").into()); - })); - }); - GIVEN.with_borrow_mut(|g| g.push((name, bytes))); -} - -/// The worker's side: reads the database given ([`give`]). The answer: `{text, index}` -/// (the text and the index in JSON), only `{games}` when `count` is asked, or `{error}` -/// (a [`Failure`] in JSON). -pub fn answer(count: bool) -> JsValue { - let never = std::sync::atomic::AtomicBool::new(false); - let answer = js_sys::Object::new(); - let mut files = GIVEN.with_borrow_mut(std::mem::take); - if files.is_empty() { - files.push((String::new(), Vec::new())); - } - let name = files[0].0.clone(); - let chessbase = name.to_lowercase().ends_with(".cbh"); - let opened = if chessbase { - chess_import::open_chessbase_owned(&name, files, &mut |_| {}, &never) - } else { - let bytes = files.swap_remove(0).1; - chess_import::open_bytes(&name, bytes, &mut |_| {}, &never) - }; - let read = opened.and_then(|opened| { - // Read from bytes, a database is always converted to PGN. - let Database::Pgn(pgn) = opened.db else { - return Err(ImportError::Corrupt("not a PGN database".into())); - }; - Ok((pgn.db, opened.format, opened.notes)) - }); - match read { - Ok((db, _, _)) if count => set(&answer, "games", &JsValue::from(db.len() as f64)), - Ok((db, format, notes)) => { - let (text, index) = db.into_index(); - let read = Read { - index, - format: Format::ALL.iter().position(|f| *f == format).unwrap_or(0), - notes, - }; - set(&answer, "text", &js_sys::Uint8Array::from(text.as_slice())); - let json = serde_json::to_string(&read).unwrap_or_default(); - set(&answer, "index", &JsValue::from_str(&json)); - } - Err(e) => { - let json = serde_json::to_string(&Failure::of(e)).unwrap_or_default(); - set(&answer, "error", &JsValue::from_str(&json)); - } - } - answer.into() -} - -/// Who waits for an answer. -enum Waiting { - Open(PathBuf, Box)>), - Count(Box)>), -} - -impl Waiting { - fn out_of_memory(self) { - match self { - Waiting::Open(path, done) => done(Err(ImportError::Io { - path, - source: std::io::Error::from(std::io::ErrorKind::OutOfMemory), - })), - Waiting::Count(done) => done(None), - } - } - - fn failed(self, e: impl ToString) { - match self { - Waiting::Open(path, done) => done(Err(io_error(&path, e))), - Waiting::Count(done) => done(None), - } - } -} - -thread_local! { - static WORKER: RefCell> = const { RefCell::new(None) }; - static WAITING: RefCell> = RefCell::new(HashMap::new()); - static NEXT: RefCell = const { RefCell::new(0) }; -} - -/// The worker's answer to a request: the database, or why there is none. -fn answered(data: JsValue) { - let get = |k: &str| js_sys::Reflect::get(&data, &k.into()).unwrap_or(JsValue::UNDEFINED); - let id = get("id").as_f64().unwrap_or(-1.0) as u32; - if let Some(e) = get("crashed").as_string() { - // The worker's program stopped (out of its memory, most likely: a browser gives - // a page at most 4 GB): this database cannot be read here; the others waiting - // go to a new worker's program — they fail too, to be opened again. - log::warn!("the reader stopped: {e}"); - if let Some(w) = WORKER.with_borrow_mut(Option::take) { - w.terminate(); - } - for (n, waiting) in WAITING.with_borrow_mut(std::mem::take) { - if n == id { - waiting.out_of_memory(); - } else { - waiting.failed(&e); - } - } - return; - } - let (path, done) = match WAITING.with_borrow_mut(|w| w.remove(&id)) { - Some(Waiting::Open(path, done)) => (path, done), - Some(Waiting::Count(done)) => { - done(get("games").as_f64().map(|n| n as usize)); - return; - } - None => return, - }; - if let Some(json) = get("error").as_string() { - let e = serde_json::from_str::(&json) - .map_or_else(|_| io_error(&path, json.clone()), |f| f.error(&path)); - done(Err(e)); - return; - } - let text = get("text") - .dyn_into::() - .map(|a| a.to_vec()); - let read = get("index") - .as_string() - .and_then(|j| serde_json::from_str::(&j).ok()); - let (Ok(text), Some(read)) = (text, read) else { - done(Err(io_error( - &path, - "the reader's answer is not a database", - ))); - return; - }; - let db = PgnDatabase::from_index(text, read.index); - log::info!( - "database read: {} ({} games)", - path.file_name().unwrap_or_default().to_string_lossy(), - db.len() - ); - done(Ok(Opened { - db: Database::Pgn(PgnDb::new(db)), - format: Format::ALL.get(read.format).copied().unwrap_or(Format::Pgn), - notes: read.notes, - })) -} - -fn worker() -> Result { - if let Some(w) = WORKER.with_borrow(|w| w.clone()) { - return Ok(w); - } - let options = web_sys::WorkerOptions::new(); - options.set_type(web_sys::WorkerType::Module); - let w = web_sys::Worker::new_with_options(SCRIPT, &options)?; - let on_message = - Closure::::new(|e: web_sys::MessageEvent| { - answered(e.data()); - }); - w.set_onmessage(Some(on_message.as_ref().unchecked_ref())); - // The worker serves the whole visit. - on_message.forget(); - let on_error = Closure::::new(|e: web_sys::ErrorEvent| { - // The worker itself failed (out of memory, its script not loaded): the files - // waiting for it fail, and the next one gets a new worker. - let message = e.message(); - if let Some(w) = WORKER.with_borrow_mut(Option::take) { - w.terminate(); - } - for (_, waiting) in WAITING.with_borrow_mut(std::mem::take) { - waiting.failed(&message); - } - }); - w.set_onerror(Some(on_error.as_ref().unchecked_ref())); - on_error.forget(); - WORKER.with_borrow_mut(|slot| *slot = Some(w.clone())); - Ok(w) -} - -/// Reads the page's file `path` in the worker; `done` gets the database on the page's -/// thread. -pub fn open(path: &Path, done: impl FnOnce(Result) + 'static) { - ask(path, false, Waiting::Open(path.to_owned(), Box::new(done))); -} - -/// How many games the page's file `path` holds (`None`: it cannot be read), read in -/// the worker; `done` gets it on the page's thread. -pub fn count(path: &Path, done: impl FnOnce(Option) + 'static) { - ask(path, true, Waiting::Count(Box::new(done))); -} - -fn ask(path: &Path, count: bool, waiting: Waiting) { - let files = match super::vfs::database_files(path) { - Ok(f) => f, - Err(e) => return waiting.failed(e), - }; - let w = match worker() { - Ok(w) => w, - Err(e) => return waiting.failed(format!("{e:?}")), - }; - let id = NEXT.with_borrow_mut(|n| { - *n += 1; - *n - }); - WAITING.with_borrow_mut(|m| m.insert(id, waiting)); - let names = js_sys::Array::new(); - let parts = js_sys::Array::new(); - // The bytes the page holds go over without a copy; the user's files are the - // browser's, read by the worker. - let transfer = js_sys::Array::new(); - for (name, source) in files { - names.push(&JsValue::from_str(&name)); - if let Some(array) = source.dyn_ref::() { - transfer.push(&array.buffer()); - } - parts.push(&source); - } - let message = js_sys::Object::new(); - set(&message, "id", &JsValue::from(id)); - set(&message, "names", &names); - set(&message, "parts", &parts); - set(&message, "count", &JsValue::from_bool(count)); - if let Err(e) = w.post_message_with_transfer(&message, &transfer) - && let Some(waiting) = WAITING.with_borrow_mut(|m| m.remove(&id)) - { - waiting.failed(format!("{e:?}")); - } -} diff --git a/apps/desktop/src/platform/web/mod.rs b/apps/desktop/src/platform/web/mod.rs deleted file mode 100644 index 4515a21..0000000 --- a/apps/desktop/src/platform/web/mod.rs +++ /dev/null @@ -1,63 +0,0 @@ -//! The web version: a page in a browser, without threads, processes or a file system. -//! -//! The program's folders are names in the page's own file tree ([`vfs`]): `/config`, -//! `/data` and `/cache` are kept in the browser's storage ([`idb`], loaded before the -//! interface starts, written behind it); `/examples` (the samples, built in) and -//! `/opened` (the files the user gave the page, only read: decisions «Веб-версия») live -//! for the session. Background work runs on the page's thread after the frame. - -pub mod engine; -pub mod idb; -pub mod import; -pub mod page; -pub mod remembered; -pub mod storage; -pub mod vfs; - -use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicBool; - -use chess_core::ScanProgress; -use chess_import::{ImportError, Opened}; - -pub fn config_dir() -> Option { - Some(PathBuf::from(vfs::CONFIG)) -} - -pub fn data_dir() -> Option { - Some(PathBuf::from(vfs::DATA)) -} - -pub fn cache_dir() -> Option { - Some(PathBuf::from(vfs::CACHE)) -} - -pub fn examples_dir() -> Option { - Some(PathBuf::from(vfs::EXAMPLES)) -} - -/// The page has no threads: the job runs on its thread once the current frame is -/// done (the screen shows the state before it, «Opening…», first). -pub fn spawn(_name: &str, job: impl FnOnce() + Send + 'static) -> std::io::Result<()> { - wasm_bindgen_futures::spawn_local(async move { - page::next_task().await; - job(); - }); - Ok(()) -} - -pub fn open_database( - path: &Path, - _progress: impl FnMut(ScanProgress) + Send + 'static, - cancel: std::sync::Arc, - done: impl FnOnce(Result) + Send + 'static, -) -> std::io::Result<()> { - import::open(path, move |read| { - done(if cancel.load(std::sync::atomic::Ordering::Relaxed) { - Err(ImportError::Cancelled) - } else { - read - }) - }); - Ok(()) -} diff --git a/apps/desktop/src/platform/web/page.rs b/apps/desktop/src/platform/web/page.rs deleted file mode 100644 index e00806f..0000000 --- a/apps/desktop/src/platform/web/page.rs +++ /dev/null @@ -1,144 +0,0 @@ -//! The page around the program: choosing files, downloads, the next task. - -use std::cell::RefCell; - -use wasm_bindgen::JsCast; -use wasm_bindgen::prelude::*; - -/// The elements through which files and a folder are chosen (one each for the page; -/// checks give them files). -pub const OPEN_INPUT_ID: &str = "cp-open-files"; -pub const OPEN_FOLDER_ID: &str = "cp-open-folder"; -/// The program's canvas (`page/index.html`). -const CANVAS_ID: &str = "cp-canvas"; - -fn document() -> Option { - web_sys::window()?.document() -} - -/// Resolves after the tasks queued now: the page draws its frame first. -pub async fn next_task() { - let promise = js_sys::Promise::new(&mut |resolve, _| { - if let Some(w) = web_sys::window() { - let _ = w.set_timeout_with_callback(&resolve); - } - }); - let _ = wasm_bindgen_futures::JsFuture::from(promise).await; -} - -type Picked = Box)>; - -thread_local! { - /// What to do with the files chosen next. - static ON_PICKED: RefCell> = const { RefCell::new(None) }; -} - -/// The page's file input `id`, made once: hidden, several files, `accept` the -/// extensions; `folder`: it chooses a folder (`webkitdirectory`, every browser has it). -fn open_input(id: &str, accept: &str, folder: bool) -> Result { - let doc = document().ok_or("no document")?; - if let Some(el) = doc.get_element_by_id(id) { - let input: web_sys::HtmlInputElement = el.dyn_into()?; - input.set_accept(accept); - return Ok(input); - } - let input: web_sys::HtmlInputElement = doc.create_element("input")?.dyn_into()?; - input.set_id(id); - input.set_type("file"); - input.set_multiple(true); - input.set_accept(accept); - if folder { - input.set_attribute("webkitdirectory", "")?; - } - input.style().set_property("display", "none")?; - let on_change = Closure::::new(move |ev: web_sys::Event| { - let Some(input) = ev - .target() - .and_then(|t| t.dyn_into::().ok()) - else { - return; - }; - let files: Vec = input - .files() - .map(|list| (0..list.length()).filter_map(|i| list.get(i)).collect()) - .unwrap_or_default(); - // The same file chosen again is a change too. - input.set_value(""); - // The keys go to the program again, not to the hidden input. - if let Some(canvas) = document() - .and_then(|d| d.get_element_by_id(CANVAS_ID)) - .and_then(|c| c.dyn_into::().ok()) - { - let _ = canvas.focus(); - } - let files = if folder { - // The folder's own files: a database's folder, not what is below it. - files - .into_iter() - .filter(|f| { - js_sys::Reflect::get(f, &"webkitRelativePath".into()) - .ok() - .and_then(|p| p.as_string()) - .is_none_or(|p| p.matches('/').count() <= 1) - }) - .collect() - } else { - files - }; - if let Some(then) = ON_PICKED.with_borrow_mut(Option::take) { - then(files); - } - }); - input.add_event_listener_with_callback("change", on_change.as_ref().unchecked_ref())?; - // The input lives as long as the page. - on_change.forget(); - doc.body().ok_or("no body")?.append_child(&input)?; - Ok(input) -} - -/// Asks the user for files (the browser's dialog); `then` gets them once chosen (not -/// read: the page's reader reads them). Must run soon after the user's click or key (a -/// browser opens the dialog only then: egui handles input in the next frame, well -/// within that time). -pub fn pick_files(accept: &str, then: impl FnOnce(Vec) + 'static) { - pick(OPEN_INPUT_ID, accept, false, then); -} - -/// Asks the user for a folder; `then` gets the files right in it. -pub fn pick_folder(then: impl FnOnce(Vec) + 'static) { - pick(OPEN_FOLDER_ID, "", true, then); -} - -fn pick(id: &str, accept: &str, folder: bool, then: impl FnOnce(Vec) + 'static) { - match open_input(id, accept, folder) { - Ok(input) => { - ON_PICKED.with_borrow_mut(|p| *p = Some(Box::new(then))); - input.click(); - } - Err(e) => log::warn!("cannot choose files: {e:?}"), - } -} - -/// Gives the user `bytes` as a downloaded file named `name`. -pub fn download(name: &str, mime: &str, bytes: &[u8]) -> Result<(), JsValue> { - let doc = document().ok_or("no document")?; - let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); - let opts = web_sys::BlobPropertyBag::new(); - opts.set_type(mime); - let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts)?; - let url = web_sys::Url::create_object_url_with_blob(&blob)?; - let a: web_sys::HtmlAnchorElement = doc.create_element("a")?.dyn_into()?; - a.set_href(&url); - a.set_download(name); - a.style().set_property("display", "none")?; - let body = doc.body().ok_or("no body")?; - body.append_child(&a)?; - a.click(); - body.remove_child(&a)?; - // The download has taken the data by the next task. - wasm_bindgen_futures::spawn_local(async move { - next_task().await; - let _ = web_sys::Url::revoke_object_url(&url); - }); - Ok(()) -} diff --git a/apps/desktop/src/platform/web/remembered.rs b/apps/desktop/src/platform/web/remembered.rs deleted file mode 100644 index 21ae25e..0000000 --- a/apps/desktop/src/platform/web/remembered.rs +++ /dev/null @@ -1,306 +0,0 @@ -//! Databases a Chromium browser remembers (Chrome, Edge: the File System Access API): -//! files chosen through `showOpenFilePicker`, or a database's folder chosen through -//! `showDirectoryPicker`, leave handles the page keeps in the browser's storage; at the -//! next visit the database is there again through them — at once when the browser still -//! allows reading, else after the user's «Allow reading» (the browser's own question). -//! Only reading: the page never writes the user's files (decisions «Веб-версия»). -//! Firefox and Safari have no such handles: there the user chooses the file again -//! ([`super::page::pick_files`]). -//! -//! What is kept for a database (its path on the page): `{handles: [file handles]}`, its -//! own file first, or `{dir: folder handle, names: [its files' names]}`; a bare file -//! handle (an earlier version) is a database of one file. - -use std::cell::RefCell; -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -use wasm_bindgen::JsCast; -use wasm_bindgen::prelude::*; - -use crate::platform::files::{Picked, gather}; - -thread_local! { - /// Databases of earlier visits the browser asks about first: the page's path, what - /// is kept for it. - static WAITING: RefCell> = RefCell::new(HashMap::new()); - /// The handle of a `.cbh` chosen alone: the folder's dialog opens where it is. - static LONE_CBH: RefCell> = const { RefCell::new(None) }; -} - -fn get(object: &JsValue, key: &str) -> JsValue { - js_sys::Reflect::get(object, &key.into()).unwrap_or(JsValue::UNDEFINED) -} - -fn set(object: &JsValue, key: &str, value: &JsValue) { - let _ = js_sys::Reflect::set(object, &key.into(), value); -} - -/// Calls `object.method(arg)` (its promise, not awaited): within the user's gesture. -fn start(object: &JsValue, method: &str, arg: &JsValue) -> Result { - let f: js_sys::Function = get(object, method).dyn_into()?; - f.call1(object, arg)?.dyn_into() -} - -/// Calls `object.method(arg)` and waits for the promise it gives. -async fn call(object: &JsValue, method: &str, arg: &JsValue) -> Result { - wasm_bindgen_futures::JsFuture::from(start(object, method, arg)?).await -} - -/// `{mode: "read"}`: the permission asked for. -fn read_mode() -> JsValue { - let o = js_sys::Object::new(); - set(&o, "mode", &"read".into()); - o.into() -} - -/// The browser remembers chosen files (it has `showOpenFilePicker`). -pub fn supported() -> bool { - web_sys::window().is_some_and(|w| get(&w, "showOpenFilePicker").is_function()) -} - -/// The browser remembers a chosen folder (it has `showDirectoryPicker`). -pub fn supported_folder() -> bool { - web_sys::window().is_some_and(|w| get(&w, "showDirectoryPicker").is_function()) -} - -async fn file_of(handle: &JsValue) -> Result { - call(handle, "getFile", &JsValue::UNDEFINED) - .await? - .dyn_into() -} - -/// Opens a dialog of the window (`showOpenFilePicker`, `showDirectoryPicker`) now, -/// within the user's gesture. -fn dialog(method: &str, options: &js_sys::Object) -> Result { - let window = web_sys::window().ok_or("no window")?; - start(&window, method, options) -} - -/// Asks the user for files (the browser's dialog, `extensions` like `.pgn`); `then` -/// gets the databases they make, each remembered. Must run soon after the user's click -/// or key, like [`super::page::pick_files`]. -pub fn pick(extensions: &[String], then: impl FnOnce(Picked) + 'static) { - let accept = js_sys::Object::new(); - let list = extensions - .iter() - .map(|e| JsValue::from_str(e)) - .collect::(); - set(&accept, "application/octet-stream", &list); - let kind = js_sys::Object::new(); - set(&kind, "accept", &accept); - let options = js_sys::Object::new(); - set(&options, "multiple", &JsValue::TRUE); - set(&options, "types", &js_sys::Array::of1(&kind)); - set(&options, "id", &"chesspenguin-databases".into()); - let chosen = dialog("showOpenFilePicker", &options); - wasm_bindgen_futures::spawn_local(async move { - // Cancelled by the user: an error, nothing chosen. - let handles: Vec = match chosen { - Ok(p) => wasm_bindgen_futures::JsFuture::from(p) - .await - .and_then(|h| h.dyn_into::()) - .map(|a| a.to_vec()) - .unwrap_or_default(), - Err(_) => Vec::new(), - }; - let mut files = Vec::new(); - let mut kept_handles = Vec::new(); - for h in handles { - match file_of(&h).await { - Ok(f) => { - files.push(f); - kept_handles.push(h); - } - Err(e) => log::warn!("cannot read a chosen file: {e:?}"), - } - } - let (picked, kept) = gather(&files, false); - for (path, members) in kept { - let entry = js_sys::Object::new(); - let list: js_sys::Array = members.iter().map(|&i| kept_handles[i].clone()).collect(); - set(&entry, "handles", &list); - super::idb::put_handle(&path.to_string_lossy(), &entry); - } - // A .cbh alone: the folder's dialog will open beside it. - let lone = picked.incomplete.first().and_then(|name| { - files - .iter() - .position(|f| f.name() == *name) - .map(|i| kept_handles[i].clone()) - }); - LONE_CBH.with_borrow_mut(|l| *l = lone); - then(picked); - }); -} - -/// Asks the user for a database's folder; `then` gets the databases in it (the files -/// right in it, found by their names), each remembered with the folder. -pub fn pick_folder(then: impl FnOnce(Picked) + 'static) { - let options = js_sys::Object::new(); - set(&options, "id", &"chesspenguin-databases".into()); - set(&options, "mode", &"read".into()); - if let Some(cbh) = LONE_CBH.with_borrow_mut(Option::take) { - set(&options, "startIn", &cbh); - } - let chosen = dialog("showDirectoryPicker", &options); - wasm_bindgen_futures::spawn_local(async move { - let dir = match chosen { - Ok(p) => wasm_bindgen_futures::JsFuture::from(p).await.ok(), - Err(_) => None, - }; - let Some(dir) = dir else { - return then(Picked::default()); - }; - let mut files = Vec::new(); - if let Err(e) = folder_files(&dir, &mut files).await { - log::warn!("cannot read the folder: {e:?}"); - } - let (mut picked, kept) = gather(&files, true); - for (path, members) in kept { - let entry = js_sys::Object::new(); - set(&entry, "dir", &dir); - let names: js_sys::Array = members - .iter() - .map(|&i| JsValue::from_str(&files[i].name())) - .collect(); - set(&entry, "names", &names); - super::idb::put_handle(&path.to_string_lossy(), &entry); - } - picked.empty_folder = - picked.paths.is_empty() && picked.too_big.is_empty() && picked.incomplete.is_empty(); - then(picked); - }); -} - -/// The files right in the folder `dir` (its `values()`, an asynchronous iterator). -async fn folder_files(dir: &JsValue, out: &mut Vec) -> Result<(), JsValue> { - let entries = js_sys::Reflect::apply( - &get(dir, "values").dyn_into::()?, - dir, - &js_sys::Array::new(), - )?; - loop { - let step = call(&entries, "next", &JsValue::UNDEFINED).await?; - if get(&step, "done").is_truthy() { - return Ok(()); - } - let handle = get(&step, "value"); - if get(&handle, "kind").as_string().as_deref() == Some("file") { - out.push(file_of(&handle).await?); - } - } -} - -/// What the browser is asked to let the page read: the folder, or the files. -fn targets(kept: &JsValue) -> Vec { - let dir = get(kept, "dir"); - if !dir.is_undefined() { - return vec![dir]; - } - match get(kept, "handles").dyn_into::() { - Ok(list) => list.to_vec(), - // A bare file handle. - Err(_) => vec![kept.clone()], - } -} - -/// The database's files through what is kept for it, its own first. -async fn files_of(kept: &JsValue) -> Result, JsValue> { - let dir = get(kept, "dir"); - let mut files = Vec::new(); - if dir.is_undefined() { - for h in targets(kept) { - files.push(file_of(&h).await?); - } - } else { - let names: js_sys::Array = get(kept, "names").dyn_into()?; - for name in names.iter() { - files.push(file_of(&call(&dir, "getFileHandle", &name).await?).await?); - } - } - Ok(files) -} - -/// Brings back the databases remembered at earlier visits that the browser still lets -/// the page read (nothing is read now: the page's reader reads them when opened); the -/// others wait for the user ([`waiting`], [`allow`]). Called once before the -/// interface starts. -pub async fn restore() { - if !supported() { - return; - } - for (path, kept) in super::idb::handles().await { - let path = PathBuf::from(path); - let mut granted = true; - for t in targets(&kept) { - let state = call(&t, "queryPermission", &read_mode()) - .await - .ok() - .and_then(|s| s.as_string()); - granted &= state.as_deref() == Some("granted"); - } - if !granted { - WAITING.with_borrow_mut(|w| w.insert(path, kept)); - continue; - } - match files_of(&kept).await { - Ok(files) => { - log::info!("remembered file read again: {}", path.display()); - super::vfs::put_opened(&path, files); - } - Err(e) => log::warn!("a remembered file is gone: {e:?}"), - } - } -} - -/// The browser remembers the database `path` and asks the user before it is read again. -pub fn waiting(path: &Path) -> bool { - WAITING.with_borrow(|w| w.contains_key(path)) -} - -/// Asks the browser to let the page read `path` again (its question to the user; soon -/// after the user's click). `then`: whether the database is back at its path. -pub fn allow(path: &Path, then: impl FnOnce(bool) + 'static) { - let Some(kept) = WAITING.with_borrow(|w| w.get(path).cloned()) else { - then(false); - return; - }; - let path = path.to_owned(); - // Asked now, all within the user's gesture. - let asked: Vec<_> = targets(&kept) - .iter() - .map(|t| start(t, "requestPermission", &read_mode())) - .collect(); - wasm_bindgen_futures::spawn_local(async move { - let mut granted = true; - for a in asked { - granted &= match a { - Ok(p) => wasm_bindgen_futures::JsFuture::from(p) - .await - .ok() - .and_then(|s| s.as_string()) - .is_some_and(|s| s == "granted"), - Err(_) => false, - }; - } - let files = if granted { - files_of(&kept).await.ok() - } else { - None - }; - let back = files.is_some(); - if let Some(files) = files { - log::info!("remembered file allowed again: {}", path.display()); - WAITING.with_borrow_mut(|w| w.remove(&path)); - super::vfs::put_opened(&path, files); - } - then(back); - }); -} - -/// The database `path` is no longer the library's: the browser's handles are let go. -pub fn forget(path: &Path) { - WAITING.with_borrow_mut(|w| w.remove(path)); - super::idb::delete_handle(&path.to_string_lossy()); -} diff --git a/apps/desktop/src/platform/web/storage.rs b/apps/desktop/src/platform/web/storage.rs deleted file mode 100644 index b345c95..0000000 --- a/apps/desktop/src/platform/web/storage.rs +++ /dev/null @@ -1,72 +0,0 @@ -//! What the browser gives the site to keep: the space used and left -//! (`navigator.storage.estimate()`: the site's quota, not the disk's free space) and -//! whether its data is kept for good (`persist()`: not cleared when space runs low). -//! Both are asked for in the background; the screen shows what came last. - -use std::cell::Cell; - -use wasm_bindgen::JsCast; -use wasm_bindgen_futures::JsFuture; - -thread_local! { - static USAGE: Cell> = const { Cell::new(None) }; - static PERSISTED: Cell> = const { Cell::new(None) }; -} - -fn manager() -> Option { - Some(web_sys::window()?.navigator().storage()) -} - -fn number(o: &wasm_bindgen::JsValue, key: &str) -> Option { - js_sys::Reflect::get(o, &key.into()) - .ok()? - .as_f64() - .map(|n| n as u64) -} - -/// Asks the browser again how much is used and left; `then` once it answered. -pub fn refresh(then: impl FnOnce() + 'static) { - wasm_bindgen_futures::spawn_local(async move { - if let Some(m) = manager() { - if let Ok(p) = m.estimate() - && let Ok(e) = JsFuture::from(p).await - && let (Some(usage), Some(quota)) = (number(&e, "usage"), number(&e, "quota")) - { - USAGE.set(Some((usage, quota))); - } - if let Ok(p) = m.persisted() - && let Ok(v) = JsFuture::from(p).await - { - PERSISTED.set(v.as_bool()); - } - } - then(); - }); -} - -/// (used, quota) in bytes, as the browser last said. -pub fn usage() -> Option<(u64, u64)> { - USAGE.get() -} - -/// Whether the site's data is kept for good (`None`: not known yet). -pub fn persisted() -> Option { - PERSISTED.get() -} - -/// Asks the browser to keep the site's data for good (Firefox asks the user; Chromium -/// and Safari decide themselves); `then` with the answer. -pub fn persist(then: impl FnOnce(bool) + 'static) { - wasm_bindgen_futures::spawn_local(async move { - let granted = match manager().and_then(|m| m.persist().ok()) { - Some(p) => JsFuture::from(p) - .await - .ok() - .and_then(|v| v.dyn_into::().ok()) - .is_some_and(|b| b.value_of()), - None => false, - }; - PERSISTED.set(Some(granted)); - then(granted); - }); -} diff --git a/apps/desktop/src/platform/web/vfs.rs b/apps/desktop/src/platform/web/vfs.rs deleted file mode 100644 index eee561c..0000000 --- a/apps/desktop/src/platform/web/vfs.rs +++ /dev/null @@ -1,236 +0,0 @@ -//! The page's file tree: files by path, in memory. The program's data (`/config`, -//! `/data`, `/cache`) is written through to the browser's storage ([`super::idb`]) and -//! read from it at the start ([`load`]); the rest lives for the session. The user's -//! files are the browser's `File`s, not their contents: the page's reader reads them -//! (`super::import`), so a database's bytes never fill the page's memory. - -use std::cell::RefCell; -use std::collections::BTreeMap; -use std::io; -use std::path::{Path, PathBuf}; - -use crate::platform::fs::Meta; - -pub const CONFIG: &str = "/config"; -pub const DATA: &str = "/data"; -pub const CACHE: &str = "/cache"; -pub const EXAMPLES: &str = "/examples"; -pub const OPENED: &str = "/opened"; - -/// The folders kept in the browser's storage. -const KEPT: [&str; 3] = [CONFIG, DATA, CACHE]; - -struct Entry { - content: Content, - modified_ms: u64, - readonly: bool, -} - -enum Content { - Bytes(Vec), - /// A file the user gave the page: the browser reads it when asked. - File(web_sys::File), -} - -impl Content { - fn len(&self) -> u64 { - match self { - Content::Bytes(b) => b.len() as u64, - Content::File(f) => f.size() as u64, - } - } -} - -thread_local! { - static FILES: RefCell> = const { RefCell::new(BTreeMap::new()) }; - /// The number of the last file opened (each gets a folder of its own; numbered from - /// the visit's start time, so that a file of an earlier visit keeps its own). - static OPENED_COUNT: RefCell = const { RefCell::new(0) }; -} - -fn now_ms() -> u64 { - js_sys::Date::now() as u64 -} - -fn kept(path: &Path) -> bool { - KEPT.iter().any(|k| path.starts_with(k)) -} - -fn not_found(path: &Path) -> io::Error { - io::Error::new( - io::ErrorKind::NotFound, - format!("{}: no such file", path.display()), - ) -} - -/// Takes in what the browser's storage keeps; called once before the interface starts. -pub async fn load() { - let stored = super::idb::load_all().await; - FILES.with_borrow_mut(|files| { - for (path, bytes) in stored { - files.insert( - PathBuf::from(path), - Entry { - content: Content::Bytes(bytes), - modified_ms: 0, - readonly: false, - }, - ); - } - }); -} - -/// The file's bytes; a user's file is read by the page's reader instead -/// ([`source`]). -pub fn read(path: &Path) -> io::Result> { - FILES.with_borrow( - |files| match &files.get(path).ok_or_else(|| not_found(path))?.content { - Content::Bytes(b) => Ok(b.clone()), - Content::File(_) => Err(io::Error::new( - io::ErrorKind::Unsupported, - "the user's file is read by the page's reader", - )), - }, - ) -} - -/// The file for the page's reader: its bytes (a `Uint8Array`) or the user's `File`. -pub fn source(path: &Path) -> io::Result { - FILES.with_borrow(|files| { - Ok( - match &files.get(path).ok_or_else(|| not_found(path))?.content { - Content::Bytes(b) => js_sys::Uint8Array::from(b.as_slice()).into(), - Content::File(f) => f.clone().into(), - }, - ) - }) -} - -pub fn meta(path: &Path) -> io::Result { - FILES.with_borrow(|files| { - files - .get(path) - .map(|e| Meta { - len: e.content.len(), - modified_ms: e.modified_ms, - readonly: e.readonly, - }) - .ok_or_else(|| not_found(path)) - }) -} - -pub fn write(path: &Path, bytes: Vec) -> io::Result<()> { - let keep = kept(path); - FILES.with_borrow_mut(|files| { - if files.get(path).is_some_and(|e| e.readonly) { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - format!("{}: only read", path.display()), - )); - } - if keep { - super::idb::put(path.to_string_lossy().into_owned(), bytes.clone()); - } - files.insert( - path.to_owned(), - Entry { - content: Content::Bytes(bytes), - modified_ms: now_ms(), - readonly: false, - }, - ); - Ok(()) - }) -} - -pub fn remove(path: &Path) -> io::Result<()> { - FILES.with_borrow_mut(|files| { - files.remove(path).ok_or_else(|| not_found(path))?; - if kept(path) { - super::idb::delete(path.to_string_lossy().into_owned()); - } - Ok(()) - }) -} - -/// The files right in the folder `dir`. -pub fn list(dir: &Path) -> Vec { - FILES.with_borrow(|files| { - files - .keys() - .filter(|p| p.parent() == Some(dir)) - .cloned() - .collect() - }) -} - -/// A database the user gave the page (chosen, dropped, found in a chosen folder): -/// its files (its own first: a ChessBase database's `.cbh`, then its other files), -/// kept for the session, only read, in a folder of their own; the path of the first. -pub fn add_opened(files: Vec) -> PathBuf { - let n = OPENED_COUNT.with_borrow_mut(|n| { - *n = (*n + 1).max(now_ms()); - *n - }); - let path = Path::new(OPENED) - .join(n.to_string()) - .join(files.first().map(name_of).unwrap_or_default()); - put_opened(&path, files); - path -} - -/// A database of an earlier visit the browser let the page read again, at its old -/// path (its other files beside it). -pub fn put_opened(path: &Path, files: Vec) { - let dir = path.parent().unwrap_or(Path::new(OPENED)).to_owned(); - FILES.with_borrow_mut(|entries| { - for (i, f) in files.into_iter().enumerate() { - let at = if i == 0 { - path.to_owned() - } else { - dir.join(name_of(&f)) - }; - entries.insert( - at, - Entry { - content: Content::File(f), - modified_ms: now_ms(), - readonly: true, - }, - ); - } - }); -} - -/// A file's name, not a path (a browser gives no folders; this makes sure). -fn name_of(f: &web_sys::File) -> String { - let name = f.name(); - name.rsplit(['/', '\\']).next().unwrap_or(&name).to_owned() -} - -/// The files of the database `path` for the page's reader: (name, [`source`]); a -/// ChessBase database's `.cbh` with the files of its name beside it. -pub fn database_files(path: &Path) -> io::Result> { - let name = |p: &Path| { - p.file_name() - .map(|n| n.to_string_lossy().into_owned()) - .unwrap_or_default() - }; - let mut out = vec![(name(path), source(path)?)]; - let cbh = path - .extension() - .is_some_and(|e| e.eq_ignore_ascii_case("cbh")); - if cbh && let Some(dir) = path.parent() { - let stem = |p: &Path| { - p.file_stem() - .map(|s| s.to_string_lossy().to_lowercase()) - .unwrap_or_default() - }; - for p in list(dir) { - if p != path && stem(&p) == stem(path) { - out.push((name(&p), source(&p)?)); - } - } - } - Ok(out) -} diff --git a/apps/desktop/src/play.rs b/apps/desktop/src/play.rs index 6d0055b..01749fc 100644 --- a/apps/desktop/src/play.rs +++ b/apps/desktop/src/play.rs @@ -4,8 +4,7 @@ use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; -use std::time::Duration; -use web_time::Instant; +use std::time::{Duration, Instant}; use chess_core::shakmaty::{Chess, Color, Move, Position}; use serde::{Deserialize, Serialize}; @@ -458,27 +457,6 @@ struct Request { pause: Duration, } -/// The engine judging a game (Stockfish at `exe`), waking `ctx` with its answers. -/// A browser starts no engine processes: there is no judge there, and the game goes -/// without resignations, as when the engine does not start. -pub fn start_judge(exe: crate::engines::EngineLocation, ctx: &egui::Context) -> Option { - #[cfg(not(web))] - { - let crate::engines::EngineLocation::Program(exe) = exe; - let ctx = ctx.clone(); - Some(Judge::start( - uci::EngineConfig::new(exe), - Vec::new(), - Box::new(move || ctx.request_repaint()), - )) - } - #[cfg(web)] - { - let _ = (exe, ctx); - None - } -} - /// What computes the opponent's moves. enum Worker { /// Maia in a thread of her own; her error, if loading failed. @@ -488,8 +466,7 @@ enum Worker { generation: u64, error: Arc>>, }, - /// Rodent, a UCI engine (the shared crate's player): a process, not in a browser. - #[cfg(not(web))] + /// Rodent, a UCI engine (the shared crate's player). Rodent(::play::rodent::RodentPlayer), } @@ -574,7 +551,6 @@ impl Opponent { pause, }); } - #[cfg(not(web))] Worker::Rodent(player) => { if let (Some(pos), Some(now)) = (engine_pos, positions.last().cloned()) { player.ask(pos, now, pause); @@ -585,7 +561,6 @@ impl Opponent { /// Rodent (`exe` in its folder) playing in `style` at `uci_elo` (none: full /// strength), with its opening book. - #[cfg(not(web))] pub fn start_rodent( exe: std::path::PathBuf, style: String, @@ -610,28 +585,10 @@ impl Opponent { } } - /// An opponent that did not start, for `why`: the game ends at once with it (in a - /// browser, which starts no engine processes, Rodent). - #[cfg(web)] - pub fn not_started(why: String) -> Opponent { - let (tx, _) = channel(); - let (_, rx) = channel(); - Opponent { - worker: Worker::Maia { - tx, - rx, - generation: 0, - error: Arc::new(Mutex::new(Some(why))), - }, - thinking: false, - } - } - /// Forgets what was asked (its answer will be dropped). pub fn forget(&mut self) { match &mut self.worker { Worker::Maia { generation, .. } => *generation += 1, - #[cfg(not(web))] Worker::Rodent(player) => player.forget(), } self.thinking = false; @@ -650,7 +607,6 @@ impl Opponent { } } } - #[cfg(not(web))] Worker::Rodent(player) => { if let Some((m, pause)) = player.answer() { self.thinking = false; @@ -662,13 +618,13 @@ impl Opponent { } pub fn failed(&self) -> Option { + use ::play::rodent::Failure; match &self.worker { Worker::Maia { error, .. } => error.lock().ok().and_then(|g| g.clone()), - #[cfg(not(web))] Worker::Rodent(player) => player.failure().map(|f| match f { - ::play::rodent::Failure::Start(e) => start_failure(&e), - ::play::rodent::Failure::Stopped => tr("it stopped while playing").to_owned(), - ::play::rodent::Failure::Search(e) => e, + Failure::Start(e) => start_failure(&e), + Failure::Stopped => tr("it stopped while playing").to_owned(), + Failure::Search(e) => e, }), } } @@ -1557,34 +1513,11 @@ impl Dialog { section(ui, tr("Your colour")); ui.horizontal(|ui| { for (c, label) in [ - (ColorChoice::White, tr("White")), + (ColorChoice::White, tr("♔ White")), (ColorChoice::Random, tr("Random")), - (ColorChoice::Black, tr("Black")), + (ColorChoice::Black, tr("♚ Black")), ] { - let size = [(W - 2.0 * GAP) / 3.0, TILE_H]; - let on = self.prefs.color == c; - let king = match c { - ColorChoice::White => Some(true), - ColorChoice::Black => Some(false), - ColorChoice::Random => None, - }; - let clicked = match king { - Some(white) => ui - .add_sized( - size, - egui::Button::selectable( - on, - ( - crate::widgets::side_king(white, 16.0), - RichText::new(label).size(14.0), - ), - ) - .frame_when_inactive(true), - ) - .clicked(), - None => choice(ui, on, label, size).clicked(), - }; - if clicked { + if choice(ui, self.prefs.color == c, label, [(W - 2.0 * GAP) / 3.0, TILE_H]).clicked() { self.prefs.color = c; } } @@ -1877,7 +1810,6 @@ 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_saved.rs b/apps/desktop/src/prep_saved.rs deleted file mode 100644 index 238b8d1..0000000 --- a/apps/desktop/src/prep_saved.rs +++ /dev/null @@ -1,350 +0,0 @@ -//! Saved preparations: a preparation against an opponent kept for good (not in the -//! cache) and opened again from «Preparations» in the library. One per player of a -//! database: saving the same player of the same database again replaces it. Each is -//! two files in `/preparations/`: `.json`, what the list shows, and -//! `.report.json`, the report with the engine's evaluations (so the errors found -//! come back without the engine, even after the cache was cleared). - -use std::path::{Path, PathBuf}; - -use prep::{ErrorCounts, Period, Player, PrepReport}; -use serde::{Deserialize, Serialize}; - -use crate::prep_ui::ColorChoice; - -/// Version of the eligibility rules used for the saved error counters. -pub const ERROR_SELECTION_VERSION: u32 = 1; - -/// What the list of preparations knows of one. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct SavedPrep { - /// The name in the list (the player's at first; the user can rename it). - pub title: String, - /// The database. - pub path: PathBuf, - pub player: Player, - pub names: Vec, - pub plies: usize, - pub period: Period, - pub color: ColorChoice, - /// Unused legacy book choice, preserved when old preparations are saved again. - #[serde(default)] - pub book: PathBuf, - /// Seconds since 1970, of the last save. - pub saved: u64, - /// The report's games and errors at that save. - pub games: u32, - pub errors: ErrorCounts, - /// The errors were searched (else the counts mean nothing). - pub evaluated: bool, - #[serde(default)] - pub error_selection_version: u32, -} - -impl SavedPrep { - pub fn errors_current(&self) -> bool { - self.error_selection_version == ERROR_SELECTION_VERSION - } -} - -/// The folder of the saved preparations. -pub fn dir() -> Option { - crate::platform::data_dir().map(|d| d.join("preparations")) -} - -/// The id of the preparation of the player named `names` in the database `path`: by -/// the names, not the database's name ids, which change when a game before his first -/// one is deleted or the database is replaced by a new version. -pub fn id(path: &Path, names: &[String]) -> String { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - let mut eat = |b: u8| { - h ^= u64::from(b); - h = h.wrapping_mul(0x0000_0100_0000_01b3); - }; - for b in path.to_string_lossy().bytes() { - eat(b); - } - let mut names: Vec<&String> = names.iter().collect(); - names.sort(); - names.dedup(); - for n in names { - eat(0); - for b in n.bytes() { - eat(b); - } - } - format!("{h:016x}") -} - -fn meta_path(dir: &Path, id: &str) -> PathBuf { - dir.join(format!("{id}.json")) -} - -fn report_path(dir: &Path, id: &str) -> PathBuf { - dir.join(format!("{id}.report.json")) -} - -/// Writes through a file beside it, so a crash leaves the old file or the new one. -fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent)?; - } - let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path) -} - -/// Every saved preparation (id, what it is), the last saved first. -pub fn list(dir: &Path) -> Vec<(String, SavedPrep)> { - let Ok(entries) = std::fs::read_dir(dir) else { - return Vec::new(); - }; - let mut out: Vec<(String, SavedPrep)> = entries - .filter_map(|e| { - let path = e.ok()?.path(); - let name = path.file_name()?.to_str()?; - let id = name.strip_suffix(".json")?; - if id.ends_with(".report") { - return None; - } - let meta = serde_json::from_slice(&std::fs::read(&path).ok()?).ok()?; - Some((id.to_owned(), meta)) - }) - .collect(); - out.sort_by(|a, b| b.1.saved.cmp(&a.1.saved).then(a.1.title.cmp(&b.1.title))); - out -} - -/// The preparation `id`, if saved. -pub fn get(dir: &Path, id: &str) -> Option { - serde_json::from_slice(&std::fs::read(meta_path(dir, id)).ok()?).ok() -} - -/// Its report, if it can be read. -pub fn report(dir: &Path, id: &str) -> Option { - let mut report: PrepReport = - serde_json::from_slice(&std::fs::read(report_path(dir, id)).ok()?).ok()?; - // Stored evaluations remain useful when the rules for selecting errors change. - report.refresh(); - Some(report) -} - -/// Keeps `meta` and `report` as the preparation of their player and database (the -/// report first: a list entry never points to a missing report). -pub fn save(dir: &Path, meta: &SavedPrep, report: &PrepReport) -> std::io::Result<()> { - let id = id(&meta.path, &meta.names); - let bytes = serde_json::to_vec(report).map_err(std::io::Error::other)?; - write_atomic(&report_path(dir, &id), &bytes)?; - save_meta(dir, meta) -} - -/// Writes only the list entry: a preparation is kept from the moment it is started, -/// before its report is built. -pub fn save_meta(dir: &Path, meta: &SavedPrep) -> std::io::Result<()> { - let bytes = serde_json::to_vec_pretty(meta).map_err(std::io::Error::other)?; - write_atomic(&meta_path(dir, &id(&meta.path, &meta.names)), &bytes) -} - -/// A new name in the list. -pub fn rename(dir: &Path, id: &str, title: &str) -> std::io::Result<()> { - let mut meta = get(dir, id).ok_or_else(|| std::io::Error::other("no such preparation"))?; - meta.title = title.to_owned(); - let bytes = serde_json::to_vec_pretty(&meta).map_err(std::io::Error::other)?; - write_atomic(&meta_path(dir, id), &bytes) -} - -/// Removes the preparation (the list entry first). -pub fn delete(dir: &Path, id: &str) -> std::io::Result<()> { - std::fs::remove_file(meta_path(dir, id))?; - let _ = std::fs::remove_file(report_path(dir, id)); - Ok(()) -} - -/// Seconds since 1970 now. -pub fn now() -> u64 { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn meta(path: &str, ids: [u32; 1], title: &str, saved: u64) -> SavedPrep { - SavedPrep { - title: title.to_owned(), - path: PathBuf::from(path), - player: Player::new(ids), - names: vec![title.to_owned()], - plies: 20, - period: Period::Months(24), - color: ColorChoice::Black, - book: PathBuf::new(), - saved, - games: 3, - errors: ErrorCounts::default(), - evaluated: false, - error_selection_version: ERROR_SELECTION_VERSION, - } - } - - #[test] - fn legacy_error_counts_are_not_marked_current() { - let current = meta("/db/a.pgn", [7], "Target", 10); - assert!(current.errors_current()); - let mut json = serde_json::to_value(¤t).expect("metadata"); - json.as_object_mut() - .unwrap() - .remove("error_selection_version"); - let legacy: SavedPrep = serde_json::from_value(json).expect("legacy metadata"); - assert!(!legacy.errors_current()); - let future = SavedPrep { - error_selection_version: ERROR_SELECTION_VERSION + 1, - ..current - }; - assert!(!future.errors_current()); - } - - #[test] - fn saved_listed_replaced_renamed_and_deleted() { - let dir = std::env::temp_dir().join(format!("cp-prep-saved-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - assert!(list(&dir).is_empty()); - let report: PrepReport = serde_json::from_str(REPORT).expect("report"); - let a = meta("/db/a.pgn", [7], "Вафин", 10); - let b = meta("/db/a.pgn", [8], "Иванов", 20); - save(&dir, &a, &report).expect("save"); - save(&dir, &b, &report).expect("save"); - let l = list(&dir); - assert_eq!(l.len(), 2); - assert_eq!(l[0].1.title, "Иванов", "the last saved first"); - // The same player of the same database: replaced, not added. - let a2 = SavedPrep { - saved: 30, - plies: 30, - ..a.clone() - }; - save(&dir, &a2, &report).expect("save"); - let l = list(&dir); - assert_eq!(l.len(), 2); - assert_eq!(l[0].1, a2); - let ida = id(&a.path, &a.names); - assert!(report_path(&dir, &ida).exists()); - assert!(super::report(&dir, &ida).is_some()); - rename(&dir, &ida, "Вафин — финал").expect("rename"); - assert_eq!(get(&dir, &ida).unwrap().title, "Вафин — финал"); - delete(&dir, &ida).expect("delete"); - assert_eq!(list(&dir).len(), 1); - assert!(!report_path(&dir, &ida).exists()); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn legacy_book_choice_is_preserved() { - let dir = std::env::temp_dir().join(format!("cp-prep-legacy-book-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut a = meta("/db/a.pgn", [7], "Вафин", 10); - a.book = PathBuf::from("/db/book.pgn"); - save_meta(&dir, &a).expect("save_meta"); - let ida = id(&a.path, &a.names); - let path = meta_path(&dir, &ida); - let json = std::fs::read_to_string(&path).expect("metadata"); - let without_book = json.replace(&format!("\"book\": \"{}\",", a.book.display()), ""); - std::fs::write(&path, without_book).expect("legacy metadata"); - let mut loaded = get(&dir, &ida).expect("defaulted legacy book"); - assert_eq!(loaded.book, PathBuf::new()); - loaded.book = a.book.clone(); - save_meta(&dir, &loaded).expect("save legacy book"); - assert_eq!(get(&dir, &ida).expect("metadata").book, a.book); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn saved_report_rejudges_stale_errors_without_losing_evaluations() { - let dir = std::env::temp_dir().join(format!("cp-prep-rejudge-{}", std::process::id())); - let mut stale: PrepReport = serde_json::from_str(REPORT).expect("report"); - stale.search = game_review::SEARCH_VERSION; - stale.games.push(prep::GameInfo { - index: 0, - white: true, - opponent: "Other".into(), - opponent_elo: 0, - date: String::new(), - outcome: prep::Outcome::Unknown, - ucis: vec!["e2e4".into(), "e7e5".into(), "g1f3".into()], - sans: vec!["e4".into(), "e5".into(), "Nf3".into()], - keys: vec![1, 2, 3, 4], - opening: None, - named: None, - book: None, - }); - stale.white.games = vec![0]; - for (key, cp, best) in [ - (1, 0, "e2e4"), - (2, 0, "c7c5"), - (3, 150, "f1c4"), - (4, 0, "b8c6"), - ] { - stale.evals.insert( - key, - prep::PositionEval { - nodes: 1000, - eval: prep::Eval::Cp(cp), - pv: vec![best.into()], - depth: 10, - }, - ); - } - // This cached Nf3 error followed Black's earlier error, so it no longer - // belongs in preparation despite its evaluations being fully cached. - stale.white.errors.push(prep::OpeningError { - game: 0, - ply: 2, - key: 3, - uci: "g1f3".into(), - san: "Nf3".into(), - best_uci: "f1c4".into(), - best_san: "Bc4".into(), - judgement: prep::Judgement::Mistake, - before: prep::Eval::Cp(150), - after: prep::Eval::Cp(0), - opening: None, - }); - stale.white.counts.mistakes = 1; - let metadata = meta("/db/stale.pgn", [7], "Target", 10); - save(&dir, &metadata, &stale).expect("save stale report"); - let key = id(&metadata.path, &metadata.names); - let stored = std::fs::read(report_path(&dir, &key)).expect("stored bytes"); - let loaded = super::report(&dir, &key).expect("load saved report"); - assert!(loaded.white.errors.is_empty()); - assert_eq!(loaded.white.counts.total(), 0); - assert_eq!(loaded.evals, stale.evals); - assert_eq!(loaded.games, stale.games); - assert_eq!(std::fs::read(report_path(&dir, &key)).unwrap(), stored); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn started_preparation_is_listed_before_its_report_exists() { - let dir = std::env::temp_dir().join(format!("cp-prep-meta-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let a = meta("/db/a.pgn", [7], "Вафин", 10); - save_meta(&dir, &a).expect("save_meta"); - assert_eq!(list(&dir).len(), 1, "in the list from the start"); - let ida = id(&a.path, &a.names); - assert!(super::report(&dir, &ida).is_none(), "no report yet"); - let report: PrepReport = serde_json::from_str(REPORT).expect("report"); - save(&dir, &a, &report).expect("save"); - assert!(super::report(&dir, &ida).is_some()); - let _ = std::fs::remove_dir_all(&dir); - } - - const REPORT: &str = r#"{"version":4,"fingerprint":1,"player":{"ids":[7]},"names":["A"], - "plies":20,"side_white":true,"side_black":true,"games":[],"skipped":0,"openings":[], - "white":{"white":true,"games":[],"tree":{"nodes":[]},"families":[],"errors":[], - "repeated":[],"counts":{"inaccuracies":0,"mistakes":0,"blunders":0}}, - "black":{"white":false,"games":[],"tree":{"nodes":[]},"families":[],"errors":[], - "repeated":[],"counts":{"inaccuracies":0,"mistakes":0,"blunders":0}}, - "book":null,"engine":null,"evals":{}}"#; -} diff --git a/apps/desktop/src/prep_ui.rs b/apps/desktop/src/prep_ui.rs deleted file mode 100644 index 78322f4..0000000 --- a/apps/desktop/src/prep_ui.rs +++ /dev/null @@ -1,6469 +0,0 @@ -//! Preparing against an opponent on the desktop (docs/design/opponent-prep.md): the -//! dialog that picks the database, the player's spellings and the colour; -//! the report screen — the repertoire tree, the openings, the errors, the board of the -//! chosen position and the games through it — and the engine run over the opening -//! positions. The data are the `prep` crate's; the engine job is the same as the game -//! analysis's (`game_review::run`), one at a time for the whole program. - -use std::collections::{HashMap, HashSet}; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc::{Receiver, channel}; - -use chess_import::Database; -use chess_import::chessbase::base::{Side, fold}; -use egui::{Color32, Key, KeyboardShortcut, Modifiers, RichText, Sense, Ui, vec2}; -use egui_extras::{Column, TableBuilder}; -use game_review::{JobEvent, JobSettings, Judgement}; -use prep::{ - Candidate, ErrorCounts, GameInfo, Options, Period, Player, PositionCache, PrepReport, Tally, -}; -use serde::{Deserialize, Serialize}; -use shakmaty::uci::UciMove; -use shakmaty::{Chess, Color, Move, Position, Square}; - -use crate::board::{Arrow, BoardState, BoardView}; -use crate::board_search::{Background, PREVIEW_ARROW}; -use crate::i18n::{tr, trf}; -use crate::large_db::grouped; -use crate::reference::RefDb; -use crate::review; -use crate::settings::Settings; - -/// «Prepare against…» as the library asks it: the name typed or picked and the colour -/// of the filter (§2.1). -#[derive(Clone, Debug, Default)] -pub struct PrepEntry { - pub query: String, - /// The name id when it was picked from the list. - pub exact: Option, - pub side: Side, -} - -/// A table's order: the column and the direction. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct SortBy { - pub key: K, - pub ascending: bool, -} - -impl SortBy { - /// A click on the header of `key`: the same column turns the order round, another - /// one starts in its natural direction (names A–Z, numbers and dates high first). - fn click(&mut self, key: K, ascending_first: bool) { - if self.key == key { - self.ascending = !self.ascending; - } else { - *self = SortBy { - key, - ascending: ascending_first, - }; - } - } - - /// `ord` (ascending) in this table's direction. - fn apply(&self, ord: std::cmp::Ordering) -> std::cmp::Ordering { - if self.ascending { ord } else { ord.reverse() } - } -} - -/// The columns the repertoire tree orders the moves of a position by. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum TreeSort { - Games, - Share, - Score, - Last, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum OpeningSort { - Name, - Eco, - Games, - Share, - Score, - Last, - Errors, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum RepeatedSort { - Move, - Times, - Score, - Opening, -} - -/// «By opening» of the errors tab. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum VariationSort { - Games, - Errors, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum GameSort { - White, - WhiteElo, - Black, - BlackElo, - Result, - Date, - Then, - Event, - Errors, -} - -/// The order of every table of the screen (kept in the settings). -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct PrepSorts { - pub tree: SortBy, - pub openings: SortBy, - pub repeated: SortBy, - pub variations: SortBy, - pub games: SortBy, -} - -impl Default for PrepSorts { - fn default() -> Self { - // Most played, most repeated, worst, newest first. - PrepSorts { - tree: SortBy { - key: TreeSort::Games, - ascending: false, - }, - openings: SortBy { - key: OpeningSort::Games, - ascending: false, - }, - repeated: SortBy { - key: RepeatedSort::Times, - ascending: false, - }, - variations: SortBy { - key: VariationSort::Errors, - ascending: false, - }, - games: SortBy { - key: GameSort::Date, - ascending: false, - }, - } - } -} - -/// A sort column of the errors tab (its two parts). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SortKeyOf { - Repeated(RepeatedSort), - Variation(VariationSort), -} - -/// A value a table is ordered by. -#[derive(Clone, Debug, PartialEq, PartialOrd)] -enum SortVal { - Num(f64), - Text(String), -} - -fn num(x: impl Into) -> SortVal { - SortVal::Num(x.into()) -} - -/// `a` against `b` (a value never compared to another kind is equal). -fn cmp_val(a: &SortVal, b: &SortVal) -> std::cmp::Ordering { - a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal) -} - -/// A score for ordering: games without a result last when high first. -fn score_val(t: &Tally) -> SortVal { - num(t.score().unwrap_or(-1.0)) -} - -/// A sortable column's header: the title with ▲/▼ when the table is ordered by it; -/// a click is noted in `clicked`. -fn sort_col( - h: &mut egui_extras::TableRow<'_, '_>, - text: &str, - hint: &str, - key: K, - sort: SortBy, - clicked: &mut Option, -) { - h.col(|ui| { - let r = crate::widgets::sort_header(ui, text, (sort.key == key).then_some(sort.ascending)); - let r = if hint.is_empty() { - r - } else { - r.on_hover_text(hint) - }; - if r.clicked() { - *clicked = Some(key); - } - }); -} - -/// The colour switch of the report. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub enum ColorChoice { - White, - Black, - Both, -} - -impl ColorChoice { - pub fn side(self) -> Side { - match self { - ColorChoice::White => Side::White, - ColorChoice::Black => Side::Black, - ColorChoice::Both => Side::Any, - } - } - - fn from_side(side: Side) -> Self { - match side { - Side::White => ColorChoice::White, - Side::Black => ColorChoice::Black, - Side::Any => ColorChoice::Both, - } - } - - /// The colours shown, White first. - fn colours(self) -> Vec { - match self { - ColorChoice::White => vec![true], - ColorChoice::Black => vec![false], - ColorChoice::Both => vec![true, false], - } - } - - fn label(self) -> &'static str { - match self { - ColorChoice::White => tr("White"), - ColorChoice::Black => tr("Black"), - ColorChoice::Both => tr("Both"), - } - } -} - -/// "Mega Database 2026 · 11.7M games" for the pickers. -fn db_label(d: &RefDb) -> String { - match &d.db { - Some(db) => format!("{} · {}", d.name, crate::i18n::games_short(db.len())), - None => format!("{} · {}", d.name, tr("not open")), - } -} - -// ----- the dialog ------------------------------------------------------------------ - -/// What «Open report» starts. -pub struct PrepStart { - pub path: PathBuf, - pub player: Player, - pub side: ColorChoice, -} - -// ----- the period ------------------------------------------------------------------ - -/// The periods offered, in the menu's order. -const PERIODS: [Period; 8] = [ - Period::All, - Period::Months(3), - Period::Months(6), - Period::Months(12), - Period::Months(24), - Period::Last(50), - Period::Last(100), - Period::Last(200), -]; - -/// The period in a narrow row: «3 mo.», «Last 100». -fn period_short(p: Period) -> String { - match p { - Period::All => tr("All").to_owned(), - Period::Months(12) => tr("1 yr").to_owned(), - Period::Months(24) => tr("2 yrs").to_owned(), - Period::Months(m) => trf("{n} mo.", &[("n", &m)]), - Period::Last(n) => trf("Last {n}", &[("n", &n)]), - } -} - -/// `yyyymmdd` as «18.10.2026», «10.2026», «2026». -fn shown_date(d: u32) -> String { - match (d / 10000, d / 100 % 100, d % 100) { - (0, ..) => String::new(), - (y, 0, _) => y.to_string(), - (y, m, 0) => format!("{m:02}.{y}"), - (y, m, day) => format!("{day:02}.{m:02}.{y}"), - } -} - -fn period_label(p: Period) -> String { - match p { - Period::All => tr("All games").to_owned(), - Period::Months(12) => tr("Last year").to_owned(), - Period::Months(24) => tr("Last 2 years").to_owned(), - Period::Months(3) => tr("Last 3 months").to_owned(), - Period::Months(6) => tr("Last 6 months").to_owned(), - Period::Months(m) => trf("Last {n} months", &[("n", &m)]), - Period::Last(n) => trf("Last {n} games", &[("n", &n)]), - } -} - -pub enum DialogOutcome { - Open(PrepStart), - Cancel, - /// A database of the shelf is needed but not read yet. - LoadDb(PathBuf), -} - -/// The words of a name for matching: folded, without full stops and commas. -fn name_words(s: &str) -> Vec { - fold(s) - .split(|c: char| c.is_whitespace() || c == ',') - .map(|w| w.trim_matches('.').to_owned()) - .filter(|w| !w.is_empty()) - .collect() -} - -/// Splits the names that match a query into those that match it word for word (an -/// initial like «Р.» matches the beginning of a word) and the similar ones, which -/// only start with its words («Вафин» ⊂ «Вафина»): most likely other people. -pub fn split_candidates(query: &str, list: Vec) -> (Vec, Vec) { - let folded = fold(query); - let wanted: Vec<(String, bool)> = folded - .split(|c: char| c.is_whitespace() || c == ',') - .filter(|w| !w.is_empty()) - .map(|w| (w.trim_matches('.').to_owned(), w.ends_with('.'))) - .filter(|(w, _)| !w.is_empty()) - .collect(); - let (mut exact, mut similar) = (Vec::new(), Vec::new()); - for c in list { - let words = name_words(&c.name); - let whole = wanted.iter().all(|(q, initial)| { - words - .iter() - .any(|w| w == q || (*initial && w.starts_with(q.as_str()))) - }); - if whole { - exact.push(c); - } else { - similar.push(c); - } - } - (exact, similar) -} - -/// Up to this many names are offered. -const CANDIDATES: usize = 40; - -/// The name search in the background: the names and how many match in all. -type SearchJob = Background<(Vec, usize)>; -/// The count of the ticked names' games by colour (White, Black). -type CountJob = Background<(u32, u32)>; - -pub struct PrepDialog { - pub path: PathBuf, - /// The shelf (set by the application every frame). - pub dbs: Vec, - query: String, - /// The query the lists answer. - answered: Option, - search: Option<(String, SearchJob)>, - exact: Vec, - similar: Vec, - total: usize, - ticked: Vec, - /// The name the dialog was opened with (ticked by itself when found). - wanted: Option, - side: ColorChoice, - /// Games of the ticked names by colour, and the job counting them. - counts: Option<(Vec, (u32, u32))>, - count_job: Option<(Vec, CountJob)>, - focus_query: bool, - typed_at: f64, - /// `CP_PREP_OPEN`: «Open report» pressed by itself once a name is ticked. - auto_open: bool, -} - -impl PrepDialog { - pub fn new(path: PathBuf, entry: PrepEntry) -> Self { - PrepDialog { - path, - dbs: Vec::new(), - query: entry.query, - answered: None, - search: None, - exact: Vec::new(), - similar: Vec::new(), - total: 0, - ticked: Vec::new(), - wanted: entry.exact, - side: ColorChoice::from_side(entry.side), - counts: None, - count_job: None, - focus_query: true, - typed_at: f64::NEG_INFINITY, - auto_open: std::env::var_os("CP_PREP_OPEN").is_some(), - } - } - - fn db(&self) -> Option> { - self.dbs - .iter() - .find(|d| d.path == self.path) - .and_then(|d| d.db.clone()) - } - - /// Starts the name search for the query, when the lists do not answer it yet. - fn search(&mut self, ctx: &egui::Context, db: &Arc) { - let query = self.query.trim().to_owned(); - if self.answered.as_deref() == Some(query.as_str()) - || self.search.as_ref().is_some_and(|(q, _)| *q == query) - { - return; - } - if query.is_empty() { - self.answered = Some(query); - self.search = None; - self.exact.clear(); - self.similar.clear(); - self.total = 0; - return; - } - let (db, q) = (db.clone(), query.clone()); - let now = ctx.input(|i| i.time); - self.search = Background::spawn(ctx, now, move |_, _| { - Some(prep::candidates(&db, &q, CANDIDATES)) - }) - .map(|j| (query, j)); - } - - fn poll(&mut self, ctx: &egui::Context, db: &Arc) { - if let Some((q, job)) = &self.search - && let Some(r) = job.poll() - { - let q = q.clone(); - self.search = None; - if let Some((list, total)) = r { - let (exact, similar) = split_candidates(&q, list); - self.exact = exact; - self.similar = similar; - self.total = total; - self.answered = Some(q.clone()); - // Ticked by itself: the name the dialog was opened with, the name equal - // to the query, else the only name that matches word for word. - let folded = fold(&q); - let auto = self - .wanted - .take() - .filter(|id| self.exact.iter().any(|c| c.id == *id)) - .or_else(|| { - self.exact - .iter() - .find(|c| fold(&c.name) == folded) - .map(|c| c.id) - }) - .or_else(|| (self.exact.len() == 1).then(|| self.exact[0].id)); - self.ticked = auto.into_iter().collect(); - } - } - // The games by colour of the ticked names. - if let Some((ids, job)) = &self.count_job - && let Some(r) = job.poll() - { - let ids = ids.clone(); - self.count_job = None; - if let Some(c) = r { - self.counts = Some((ids, c)); - } - } - let mut ids = self.ticked.clone(); - ids.sort_unstable(); - if !ids.is_empty() - && self.counts.as_ref().is_none_or(|(c, _)| *c != ids) - && self.count_job.as_ref().is_none_or(|(c, _)| *c != ids) - { - let (db, player) = (db.clone(), Player::new(ids.iter().copied())); - let now = ctx.input(|i| i.time); - self.count_job = Background::spawn(ctx, now, move |_, cancel| { - let found = prep::games_of(&db, &player, Side::Any, cancel)?; - let white = found.iter().filter(|(_, w)| *w).count() as u32; - Some((white, found.len() as u32 - white)) - }) - .map(|j| (ids, j)); - } - } - - /// Draws the dialog; what was chosen, if anything. - pub fn show(&mut self, ctx: &egui::Context, _settings: &mut Settings) -> Option { - let db = self.db(); - if let Some(db) = &db { - self.search(ctx, db); - self.poll(ctx, db); - } - let own_name = base_name(&self.path); - let mut outcome = None; - let ready = db.is_some() && !self.ticked.is_empty(); - let ticked_names: Vec = self - .exact - .iter() - .chain(self.similar.iter()) - .filter(|c| self.ticked.contains(&c.id)) - .map(|c| c.name.clone()) - .collect(); - let ticked_games: u32 = self - .exact - .iter() - .chain(self.similar.iter()) - .filter(|c| self.ticked.contains(&c.id)) - .map(|c| c.games) - .sum(); - let counts = self - .counts - .as_ref() - .filter(|(ids, _)| { - let mut t = self.ticked.clone(); - t.sort_unstable(); - *ids == t - }) - .map(|(_, c)| *c); - let modal = egui::Modal::new(egui::Id::new("prep_dialog")).show(ctx, |ui| { - let screen = ctx.content_rect(); - ui.set_width((screen.width() - 40.0).min(520.0)); - ui.heading(tr("Preparing against an opponent")); - ui.add_space(6.0); - let label_w = 60.0; - // The body scrolls in a low window; the buttons stay under it. - egui::ScrollArea::vertical() - .max_height((screen.height() - 140.0).max(120.0)) - .auto_shrink([false, true]) - .show(ui, |ui| { - ui.horizontal(|ui| { - ui.add_sized([label_w, 20.0], egui::Label::new(tr("Database"))); - let width = ui.available_width() - 8.0; - let mut pick = None; - let current = self - .dbs - .iter() - .find(|d| d.path == self.path) - .map(db_label) - .unwrap_or_else(|| own_name.clone()); - egui::ComboBox::from_id_salt("prep_dialog_db") - .selected_text(current) - .width(width) - .truncate() - .show_ui(ui, |ui| { - for d in &self.dbs { - if ui - .selectable_label(d.path == self.path, db_label(d)) - .clicked() - { - pick = Some(d.path.clone()); - } - } - }); - if let Some(p) = pick.filter(|p| *p != self.path) { - self.path = p; - self.answered = None; - self.search = None; - self.ticked.clear(); - self.counts = None; - self.count_job = None; - } - }); - ui.horizontal(|ui| { - ui.add_sized([label_w, 20.0], egui::Label::new(tr("Player"))); - let r = ui.add( - egui::TextEdit::singleline(&mut self.query) - .hint_text(tr("Name or part of it")) - .desired_width(ui.available_width() - 34.0), - ); - if std::mem::take(&mut self.focus_query) && self.query.is_empty() { - r.request_focus(); - } - if r.changed() { - self.typed_at = ui.input(|i| i.time); - self.ticked.clear(); - } - if !self.query.is_empty() - && crate::widgets::small_close_button(ui) - .on_hover_text(tr("Clear")) - .clicked() - { - self.query.clear(); - self.ticked.clear(); - self.typed_at = ui.input(|i| i.time); - } - }); - ui.add_space(2.0); - match &db { - None if self - .dbs - .iter() - .any(|d| d.path == self.path && d.failed.is_some()) => - { - let why = self - .dbs - .iter() - .find(|d| d.path == self.path) - .and_then(|d| d.failed.clone()) - .unwrap_or_default(); - ui.label( - RichText::new(trf( - "This database cannot be opened: {e}", - &[("e", &why)], - )) - .color(ui.visuals().warn_fg_color), - ); - } - None => { - ui.horizontal(|ui| { - ui.add(egui::Spinner::new().size(14.0)); - ui.label(RichText::new(tr("Opening the database…")).weak()); - }); - outcome = Some(DialogOutcome::LoadDb(self.path.clone())); - } - Some(_) => self.candidate_list(ui, label_w), - } - if !self.ticked.is_empty() { - ui.add_space(2.0); - ui.label( - RichText::new(trf( - "Selected: {names} · {n}", - &[ - ("names", &ticked_names.join(", ")), - ("n", &crate::i18n::games(ticked_games as usize)), - ], - )) - .weak(), - ); - } - ui.add_space(8.0); - ui.horizontal_wrapped(|ui| { - ui.add_sized([label_w, 20.0], egui::Label::new(tr("Colour"))); - let (w, b) = match counts { - Some((w, b)) => (w.to_string(), b.to_string()), - None if self.ticked.is_empty() => ("—".to_owned(), "—".to_owned()), - None => ("…".to_owned(), "…".to_owned()), - }; - ui.radio_value( - &mut self.side, - ColorChoice::White, - trf("White — {n}", &[("n", &w)]), - ); - ui.radio_value( - &mut self.side, - ColorChoice::Black, - trf("Black — {n}", &[("n", &b)]), - ); - ui.radio_value(&mut self.side, ColorChoice::Both, tr("Both")); - }); - }); - ui.add_space(10.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let open = ui - .add_enabled( - ready, - egui::Button::new(RichText::new(tr("Open report")).strong()) - .min_size(vec2(0.0, 30.0)), - ) - .on_disabled_hover_text(tr("Tick a player")); - if open.clicked() { - outcome = Some(DialogOutcome::Open(self.start())); - } - if ui.button(tr("Cancel")).clicked() { - outcome = Some(DialogOutcome::Cancel); - } - }); - }); - if modal.should_close() { - outcome = Some(DialogOutcome::Cancel); - } - if outcome.is_none() - && ready - && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) - { - outcome = Some(DialogOutcome::Open(self.start())); - } - if outcome.is_none() && ready && self.auto_open && self.search.is_none() { - self.auto_open = false; - outcome = Some(DialogOutcome::Open(self.start())); - } - if self.search.is_some() || self.count_job.is_some() { - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - } - outcome - } - - fn start(&self) -> PrepStart { - PrepStart { - path: self.path.clone(), - player: Player::new(self.ticked.iter().copied()), - side: self.side, - } - } - - /// The names that match: tick boxes, the similar names apart. - fn candidate_list(&mut self, ui: &mut Ui, indent: f32) { - if self.search.is_some() && self.answered.as_deref() != Some(self.query.trim()) { - ui.horizontal(|ui| { - ui.add_space(indent); - ui.add(egui::Spinner::new().size(12.0)); - ui.label(RichText::new(tr("Searching…")).weak()); - }); - return; - } - if self.query.trim().is_empty() { - ui.horizontal(|ui| { - ui.add_space(indent); - ui.label( - RichText::new(tr("Type a name: the players of the database are offered")) - .weak(), - ); - }); - return; - } - if self.exact.is_empty() && self.similar.is_empty() { - ui.horizontal(|ui| { - ui.add_space(indent); - ui.label(RichText::new(tr("No such player in this database")).weak()); - }); - return; - } - let rows = self.exact.len() + self.similar.len() + usize::from(!self.similar.is_empty()); - let height = (rows as f32 * 22.0).min(8.0 * 22.0) + 4.0; - egui::ScrollArea::vertical() - .id_salt("prep_candidates") - .max_height(height) - .auto_shrink([false, true]) - .show(ui, |ui| { - let row = |ui: &mut Ui, c: &Candidate, ticked: &mut Vec| { - ui.horizontal(|ui| { - ui.add_space(indent); - let mut on = ticked.contains(&c.id); - let width = ui.available_width() - 90.0; - ui.allocate_ui(vec2(width, 20.0), |ui| { - if ui.add(egui::Checkbox::new(&mut on, &c.name)).changed() { - if on { - ticked.push(c.id); - } else { - ticked.retain(|id| *id != c.id); - } - } - }); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(RichText::new(crate::i18n::games(c.games as usize)).weak()); - }); - }); - }; - for c in &self.exact { - row(ui, c, &mut self.ticked); - } - if !self.similar.is_empty() { - ui.horizontal(|ui| { - ui.add_space(indent); - ui.label( - RichText::new(tr("Similar names — most likely other people")) - .weak() - .small(), - ); - }); - for c in &self.similar { - row(ui, c, &mut self.ticked); - } - } - if self.total > self.exact.len() + self.similar.len() { - ui.horizontal(|ui| { - ui.add_space(indent); - ui.label( - RichText::new(trf( - "{n} more matches…", - &[("n", &(self.total - self.exact.len() - self.similar.len()))], - )) - .weak(), - ); - }); - } - }); - } -} - -/// The file's name without its extension. -fn base_name(path: &Path) -> String { - path.file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default() -} - -// ----- the saved preparations ----------------------------------------------------- - -/// What the «Preparations» window asks of the application. -pub enum ListOutcome { - /// The saved preparation of this id. - Open(String), - /// «New preparation…»: the dialog for the chosen database. - New, - Close, -} - -/// The library's «Preparations»: the saved ones, to open, rename or delete. -pub struct PrepList { - items: Vec<(String, crate::prep_saved::SavedPrep)>, - /// The entry being renamed and the name typed. - renaming: Option<(String, String)>, - /// The entry asked about before deleting. - deleting: Option, - error: Option, - /// When the entries were last read (a report being built in the background - /// changes them on disk while this window is open). - last_reload: f64, -} - -impl PrepList { - pub fn new() -> Self { - let mut list = PrepList { - items: Vec::new(), - renaming: None, - deleting: None, - error: None, - last_reload: 0.0, - }; - list.reload(); - list - } - - fn reload(&mut self) { - self.items = crate::prep_saved::dir() - .as_deref() - .map(crate::prep_saved::list) - .unwrap_or_default(); - } - - /// `can_new`: a database is chosen to prepare in. - pub fn show(&mut self, ctx: &egui::Context, can_new: bool) -> Option { - let mut out = None; - let now = ctx.input(|i| i.time); - if now - self.last_reload > 2.0 { - self.reload(); - self.last_reload = now; - } - // Escape while renaming ends the renaming only. - let was_renaming = self.renaming.is_some(); - let modal = egui::Modal::new(egui::Id::new("prep_list")).show(ctx, |ui| { - let screen = ctx.content_rect(); - ui.set_width((screen.width() - 40.0).min(560.0)); - ui.heading(tr("Preparations")); - ui.add_space(6.0); - if self.items.is_empty() { - ui.label( - RichText::new(tr( - "Nothing yet. A preparation is saved by itself as soon as you start it: prepare against a player.", - )) - .weak(), - ); - } - egui::ScrollArea::vertical() - .max_height((screen.height() - 180.0).max(120.0)) - .auto_shrink([false, true]) - .show(ui, |ui| { - for (id, item) in self.items.clone() { - self.row(ui, &id, &item, &mut out); - ui.separator(); - } - }); - if let Some(e) = &self.error { - ui.label(RichText::new(e).color(ui.visuals().warn_fg_color)); - } - ui.add_space(6.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(tr("Close")).clicked() { - out = Some(ListOutcome::Close); - } - if ui - .add_enabled(can_new, egui::Button::new(tr("♟ New preparation…"))) - .on_disabled_hover_text(tr("Add a database to the shelf first")) - .on_hover_text(tr("Choose a player in the current database")) - .clicked() - { - out = Some(ListOutcome::New); - } - }); - }); - if modal.should_close() && !was_renaming { - out = out.or(Some(ListOutcome::Close)); - } - out - } - - fn row( - &mut self, - ui: &mut Ui, - id: &str, - item: &crate::prep_saved::SavedPrep, - out: &mut Option, - ) { - let found = item.path.exists(); - if self.renaming.as_ref().is_some_and(|(r, _)| r == id) { - self.rename_row(ui, id); - return; - } - let deleting = self.deleting.as_deref() == Some(id); - // The buttons' room first: the texts are cut to what is left. - let gap = ui.spacing().item_spacing.x; - let pad = 2.0 * ui.spacing().button_padding.x; - let bw = |t: &str| text_width(ui, t, egui::TextStyle::Button) + pad + gap; - let buttons = if deleting { - text_width(ui, tr("Delete?"), egui::TextStyle::Body) - + gap - + bw(tr("Delete")) - + bw(tr("No")) - } else { - bw(tr("Open")) + bw("✏") + bw("🗑") - }; - let text_w = (ui.available_width() - buttons - 2.0 * gap).max(80.0); - ui.horizontal(|ui| { - let mut open = false; - ui.allocate_ui(vec2(text_w, 0.0), |ui| { - ui.set_max_width(text_w); - ui.vertical(|ui| { - let title = ui - .add( - egui::Label::new(RichText::new(&item.title).strong()) - .truncate() - .sense(Sense::click()), - ) - .on_hover_text(tr("Double-click to open")); - open |= found && title.double_clicked(); - let mut about = vec![base_name(&item.path)]; - // «за 2 года · 8 партий», «последние 100»: the number once. - match item.period { - Period::All => about.push(crate::i18n::games(item.games as usize)), - Period::Last(n) => about.push(trf("last {n}", &[("n", &n)])), - p => { - let label = period_label(p); - let mut chars = label.chars(); - let lower = chars - .next() - .map(|c| c.to_lowercase().chain(chars).collect()) - .unwrap_or_default(); - about.push(lower); - about.push(crate::i18n::games(item.games as usize)); - } - } - about.push( - match item.color { - ColorChoice::White => tr("as White"), - ColorChoice::Black => tr("as Black"), - ColorChoice::Both => tr("both colours"), - } - .to_owned(), - ); - ui.add(egui::Label::new(RichText::new(about.join(" · ")).weak()).truncate()); - let when = chrono::DateTime::::from( - std::time::UNIX_EPOCH + std::time::Duration::from_secs(item.saved), - ) - .format("%d.%m.%Y") - .to_string(); - let errors = if item.evaluated && !item.errors_current() { - String::new() - } else if item.evaluated { - let e = &item.errors; - trf( - "errors: ?? {b} · ? {m} · ?! {i}", - &[ - ("b", &e.blunders), - ("m", &e.mistakes), - ("i", &e.inaccuracies), - ], - ) - } else { - tr("errors not searched").to_owned() - }; - let path = item.path.display().to_string(); - if found { - let saved = trf("saved {date}", &[("date", &when)]); - let line = if errors.is_empty() { - saved - } else { - format!("{errors} · {saved}") - }; - ui.add(egui::Label::new(RichText::new(line).small().weak()).truncate()); - } else { - ui.add( - egui::Label::new( - RichText::new(trf( - "database not found: {path}", - &[("path", &path)], - )) - .small() - .color(ui.visuals().warn_fg_color), - ) - .truncate(), - ) - .on_hover_text(path); - } - }); - }); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if deleting { - if ui.button(tr("No")).clicked() { - self.deleting = None; - } - if ui.button(tr("Delete")).clicked() { - self.deleting = None; - if let Some(dir) = crate::prep_saved::dir() - && let Err(e) = crate::prep_saved::delete(&dir, id) - { - self.error = Some(e.to_string()); - } - self.reload(); - } - ui.label(tr("Delete?")); - return; - } - if ui.button("🗑").on_hover_text(tr("Delete")).clicked() { - self.deleting = Some(id.to_owned()); - } - if ui.button("✏").on_hover_text(tr("Rename")).clicked() { - self.renaming = Some((id.to_owned(), item.title.clone())); - } - open |= ui - .add_enabled(found, egui::Button::new(tr("Open"))) - .on_disabled_hover_text(tr( - "The database is not found: put the file back or delete the preparation", - )) - .clicked(); - }); - if open { - *out = Some(ListOutcome::Open(id.to_owned())); - } - }); - } - - /// The name being typed: Enter or «OK» keeps it, Escape or «Cancel» does not. - fn rename_row(&mut self, ui: &mut Ui, id: &str) { - let mut done = None; - ui.horizontal(|ui| { - let gap = ui.spacing().item_spacing.x; - let pad = 2.0 * ui.spacing().button_padding.x; - let buttons = text_width(ui, tr("OK"), egui::TextStyle::Button) - + text_width(ui, tr("Cancel"), egui::TextStyle::Button) - + 2.0 * (pad + gap); - if let Some((_, text)) = self.renaming.as_mut() { - let r = ui.add( - egui::TextEdit::singleline(text) - .desired_width((ui.available_width() - buttons - gap).max(80.0)), - ); - r.request_focus(); - if ui.input(|i| i.key_pressed(Key::Enter)) { - done = Some(true); - } - if ui.input(|i| i.key_pressed(Key::Escape)) { - done = Some(false); - } - } - if ui.button(tr("OK")).clicked() { - done = Some(true); - } - if ui.button(tr("Cancel")).clicked() { - done = Some(false); - } - }); - if let Some(ok) = done { - let (_, text) = self.renaming.take().unwrap_or_default(); - let text = text.trim(); - if ok - && !text.is_empty() - && let Some(dir) = crate::prep_saved::dir() - { - if let Err(e) = crate::prep_saved::rename(&dir, id, text) { - self.error = Some(e.to_string()); - } - self.reload(); - } - } - } -} - -// ----- the screen ------------------------------------------------------------------ - -/// What the screen asks of the application. -pub enum PrepAction { - /// «⬅ Library»: the report stays in the stack. - Back, - OpenSettings, - /// A game of the report in the game screen, at move `ply` (0: the start). - OpenGame { - path: PathBuf, - index: usize, - ply: usize, - }, - /// The engine run started (the live engine pauses) / ended. - EngineStarted, - EngineEnded, - NeedEngine, - Toast(String), - CopyText(String, &'static str), - /// The line as a new game (no database). - OpenPgn(String), - /// The position on the search board of this database. - FindPosition(PathBuf, Chess, Vec, bool), - PlayFrom(Box), - SettingsChanged, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Tab { - Repertoire, - Openings, - Errors, -} - -/// What is chosen: a node of the tree, an opening, an error — the board and the games -/// list follow it. -#[derive(Clone, Debug, PartialEq, Eq)] -enum Selection { - None, - Node { - white: bool, - node: u32, - }, - Opening { - white: bool, - family: usize, - variation: Option, - }, - Repeated { - white: bool, - index: usize, - }, - Error { - white: bool, - index: usize, - }, -} - -/// A row of the games list (the names and the event come from the database once). -#[derive(Clone)] -struct ListRow { - white: String, - black: String, - white_elo: u16, - black_elo: u16, - result: &'static str, - event: String, -} - -use crate::review::JobMsg; - -struct EngineJob { - runner: crate::review::JobRunner, - rx: Receiver, - cancel: Arc, - total: usize, - done: usize, - /// Engine processes of the run. - processes: usize, - /// Evaluations since the cache was saved. - unsaved: usize, -} - -impl Drop for EngineJob { - fn drop(&mut self) { - self.cancel.store(true, Ordering::Relaxed); - } -} - -/// The position shown on the board: the line to it and the positions along it. -struct Shown { - sans: Vec, - ucis: Vec, - positions: Vec, - /// The ply shown (`positions[ply]`); the last by default, a click on the line - /// takes the board back along it. - ply: usize, - /// Arrows at the last ply (an error: the move played and the better one). - arrows: Vec, - /// «after 3.Bb5 · better 3.d4 · +0.3 → −1.5» under the line, for an error. - note: Option, - opening: Option, - /// The player's colour the position was chosen from (the board's orientation). - white: bool, -} - -/// An error at a node of the tree: by (the key before the move, the move). -#[derive(Clone)] -struct Mark { - judgement: Judgement, - best_san: String, - before: game_review::Eval, - after: game_review::Eval, - games: u32, -} - -/// A row of the repertoire tree as laid out. -#[derive(Clone, Copy, PartialEq, Eq)] -enum TreeRow { - Node { - white: bool, - node: u32, - depth: usize, - }, - /// «other moves (n)» under a node. - Others { - white: bool, - parent: u32, - depth: usize, - count: usize, - }, -} - -/// A row of the errors tab. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ErrRow { - /// «Repeated errors — …» / «By opening». - RepeatedTitle, - OpeningsTitle, - /// A repeated error (colour, index into `repeated`) and one of its games. - Repeated { - white: bool, - index: usize, - }, - RepeatedGame { - white: bool, - index: usize, - game: u32, - }, - /// A variation with errors (colour, family, variation) and one of its errors. - Variation { - white: bool, - family: usize, - variation: usize, - }, - Error { - white: bool, - index: usize, - }, -} - -impl ErrRow { - fn is_title(self) -> bool { - matches!(self, ErrRow::RepeatedTitle | ErrRow::OpeningsTitle) - } -} - -/// The engine part of the controls. -enum EngineTexts { - Running, - /// A button to start or go on, and a note beside it. - Button { - label: String, - note: Option, - }, - /// Done: a quiet label. - Done { - label: String, - note: Option, - }, -} - -/// Where the engine run stands for the colour(s) shown. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum EngineState { - Running, - /// No evaluation yet. - NotRun, - /// Some positions evaluated (a run stopped, a new depth, new games). - Partial { - done: usize, - total: usize, - }, - Complete { - total: usize, - }, -} - -/// Fewer games: the percentages are shown weak. -const FEW_GAMES: u32 = 5; -const BOARD_MIN: f32 = 220.0; -const RIGHT_MIN: f32 = 560.0; -const ROW_H: f32 = 24.0; - -/// The folder of the prep caches (the reports and the evaluations by position). -fn cache_dir() -> Option { - Settings::cache_dir().map(|d| d.join("prep")) -} - -pub struct PrepScreen { - /// This screen's own number (`engine_offer::next_serial`). - pub serial: u64, - /// The engine is taken by another job (the search for great moves, task 27): the - /// search for opening errors does not start, and says why. - pub engine_blocked: Option, - pub path: PathBuf, - db: Arc, - db_name: String, - pub player: Player, - pub names: Vec, - /// On the screen (else kept in the stack under the library). - pub shown: bool, - color: ColorChoice, - plies: usize, - period: Period, - /// Kept in «Preparations» (`prep_saved`): every change is written there too. - /// Every started preparation is kept from the start; the flag goes off only if it - /// was deleted from «Preparations» while this screen lives (not written back then). - saved: bool, - /// A period asked for where the settings are not at hand (applied in `show`). - want_period: Option, - report: Option, - rows: Vec, - /// The games read in the background (hundreds in a moment, a Mega filter in seconds). - build: Option>, - build_total: usize, - job: Option, - cache: PositionCache, - nps_per_thread: Option, - error: Option, - dialog_open: bool, - /// The report changed since it was written to the cache. - dirty: bool, - /// Evaluations came in since the last re-judging (done at most once a second). - pending_refresh: bool, - last_refresh: f64, - marks: [HashMap<(u64, String), Mark>; 2], - tab: Tab, - branches_from: u32, - expanded: HashSet<(bool, u32)>, - others_open: HashSet<(bool, u32)>, - open_families: HashSet<(bool, usize)>, - open_repeated: HashSet<(bool, usize)>, - open_variations: HashSet<(bool, usize, usize)>, - /// The row of the errors tab the keyboard is on. - err_cursor: Option, - /// Inaccuracies shown (`settings.prep.inaccuracies`, read every frame). - show_inaccuracies: bool, - /// The board stands over the lists (a narrow or low window); the window is low. - stacked: bool, - low_window: bool, - selection: Selection, - shown_pos: Option, - /// The user turned the board (else it is the player's colour). - flipped: Option, - board_state: BoardState, - /// In a low window the board is a panel over the lists, opened by a button. - board_popup: bool, - /// The order of each table (the settings' `prep.sorts`, written back on change). - sorts: PrepSorts, - /// The keyboard is in the games list (else in the tab's table). - focus_games: bool, - games_cursor: Option, - hover_arrow: Option<(Square, Square)>, - scroll_to_selected: bool, - /// The games list's height, once the user dragged the border (else 35 %). - games_height: Option, - /// The one automatic engine start of this report was considered. - auto_done: bool, -} - -/// Plays `ucis` from the start; stops at a move that cannot be read. -fn replay(ucis: &[String]) -> Vec { - let mut pos = Chess::default(); - let mut out = vec![pos.clone()]; - for u in ucis { - let Some(m) = u.parse::().ok().and_then(|u| u.to_move(&pos).ok()) else { - break; - }; - pos.play_unchecked(m); - out.push(pos.clone()); - } - out -} - -/// "3.Bb5" / "2…Nc6" for move `ply` (0-based), in the chosen notation. -fn short_label(ply: usize, san: &str) -> String { - let number = ply / 2 + 1; - let label = if ply.is_multiple_of(2) { - format!("{number}.{san}") - } else { - format!("{number}…{san}") - }; - crate::san::show(&label).into_owned() -} - -/// The line as text: "1.e4 c5 2.Nf3 Nc6". -fn line_text(sans: &[String]) -> String { - let mut out = String::new(); - for (i, san) in sans.iter().enumerate() { - if !out.is_empty() { - out.push(' '); - } - if i.is_multiple_of(2) { - out.push_str(&format!("{}.", i / 2 + 1)); - } - out.push_str(san); - } - crate::san::show_line(&out) -} - -/// The table's line ("1. e4 c5 2. Nf3") as the program writes lines: moves with -/// their numbers joined ("1.e4", "c5", "2.Nf3"). -fn table_line(line: &str) -> Vec { - let mut out: Vec = Vec::new(); - let mut number: Option<&str> = None; - for tok in line.split_whitespace() { - if tok.ends_with('.') - && tok - .trim_end_matches('.') - .chars() - .all(|c| c.is_ascii_digit()) - { - number = Some(tok); - } else { - out.push(match number.take() { - Some(n) if n.ends_with("...") => format!("{}…{tok}", n.trim_end_matches('.')), - Some(n) => format!("{n}{tok}"), - None => tok.to_owned(), - }); - } - } - out -} - -/// The moves in `width`: whole moves, the first and the last kept, «…» for the middle -/// ones that do not fit (they matter less). -fn fit_line(ui: &Ui, tokens: &[String], width: f32) -> String { - let fits = |t: &str| text_width(ui, t, egui::TextStyle::Body) <= width; - let full = crate::san::show_line(&tokens.join(" ")); - if fits(&full) || tokens.len() < 3 { - return full; - } - // Drop moves from the middle until the rest fits. - let mut head = tokens.len().div_ceil(2); - let mut tail = tokens.len() - head; - loop { - if head > 1 && head >= tail { - head -= 1; - } else if tail > 1 { - tail -= 1; - } else { - return crate::san::show_line(&format!("{} … {}", tokens[0], tokens[tokens.len() - 1])); - } - let text = format!( - "{} … {}", - tokens[..head].join(" "), - tokens[tokens.len() - tail..].join(" ") - ); - let text = crate::san::show_line(&text); - if fits(&text) { - return text; - } - } -} - -/// "01.2026 – 10.2026" from the games' dates (empty without dates). -fn period(games: &[GameInfo]) -> String { - let dated: Vec<&GameInfo> = games.iter().filter(|g| g.date_number() > 0).collect(); - let first = dated.iter().min_by_key(|g| g.date_number()); - let last = dated.iter().max_by_key(|g| g.date_number()); - let month = |g: &GameInfo| -> String { - let parts: Vec<&str> = g.date.split('.').collect(); - match parts.as_slice() { - [y, m, ..] if m.chars().all(|c| c.is_ascii_digit()) && !m.is_empty() => { - format!("{m}.{y}") - } - [y, ..] => (*y).to_string(), - _ => String::new(), - } - }; - match (first, last) { - (Some(a), Some(b)) => { - let (a, b) = (month(a), month(b)); - if a == b { a } else { format!("{a} – {b}") } - } - _ => String::new(), - } -} - -/// The results as a bar, by lightness (White's wins light, draws grey, Black's wins -/// dark, as on the search board) with no numbers in it: the score beside it is the -/// player's, the percentages are in its tooltip. Faint over few games. -fn score_bar(ui: &mut Ui, t: &Tally, white: bool, few: bool) { - let (rect, resp) = ui.allocate_exact_size(vec2(56.0, 12.0), Sense::hover()); - let (white_wins, black_wins) = if white { - (t.wins, t.losses) - } else { - (t.losses, t.wins) - }; - let decided = white_wins + t.draws + black_wins; - let fade = |c: Color32| if few { c.gamma_multiply(0.45) } else { c }; - let painter = ui.painter(); - let outline = if ui.visuals().dark_mode { - Color32::from_gray(0x70) - } else { - ui.visuals().weak_text_color() - }; - if decided > 0 { - let mut x = rect.left(); - for (n, fill) in [ - (white_wins, Color32::from_gray(0xe8)), - (t.draws, Color32::from_gray(0x8c)), - (black_wins, Color32::from_gray(0x2b)), - ] { - let w = rect.width() * n as f32 / decided as f32; - if w > 0.0 { - painter.rect_filled( - egui::Rect::from_min_max( - egui::pos2(x, rect.top()), - egui::pos2(x + w, rect.bottom()), - ), - 0.0, - fade(fill), - ); - } - x += w; - } - } - painter.rect_stroke( - rect, - 2.0, - egui::Stroke::new(1.0, fade(outline)), - egui::StrokeKind::Inside, - ); - if decided > 0 { - let pct = |n: u32| 100 * n / decided; - resp.on_hover_text(trf( - "White wins {w} % · draws {d} % · Black wins {b} %", - &[ - ("w", &pct(white_wins)), - ("d", &pct(t.draws)), - ("b", &pct(black_wins)), - ], - )); - } -} - -fn score_text(t: &Tally) -> String { - t.score() - .map_or_else(|| "—".to_owned(), |s| format!("{:.0} %", 100.0 * s)) -} - -/// "+10 =1 −3". -fn tally_hint(t: &Tally) -> String { - format!("+{} ={} −{}", t.wins, t.draws, t.losses) -} - -fn judgement_weight(j: Judgement) -> u32 { - match j { - Judgement::Blunder => 3, - Judgement::Mistake => 2, - Judgement::Inaccuracy => 1, - Judgement::Great | Judgement::Brilliant => 0, - } -} - -/// A move's mark as a pill: the symbol in white on the colour of the sign. -fn pill(ui: &mut Ui, j: Judgement) -> egui::Response { - let text = review::judgement_symbol(j); - let font = egui::FontId::proportional(11.0); - let galley = ui - .painter() - .layout_no_wrap(text.to_owned(), font, Color32::WHITE); - let size = vec2(galley.size().x + 8.0, 16.0); - let (rect, resp) = ui.allocate_exact_size(size, Sense::hover()); - ui.painter() - .rect_filled(rect, 8.0, review::judgement_color(j)); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, Color32::WHITE); - resp -} - -const COUNTS_GAP: f32 = 4.0; - -fn count_parts(c: &ErrorCounts) -> Vec<(u32, Judgement)> { - [ - (c.inaccuracies, Judgement::Inaccuracy), - (c.mistakes, Judgement::Mistake), - (c.blunders, Judgement::Blunder), - ] - .into_iter() - .filter(|(n, _)| *n > 0) - .collect() -} - -/// The width of [`counts_text`], including its separator Labels and gaps. -fn errors_text_width(ui: &Ui, c: &ErrorCounts) -> f32 { - let parts = count_parts(c); - let counts = parts - .iter() - .map(|(n, j)| { - text_width( - ui, - &format!("{n} {}", review::judgement_symbol(*j)), - egui::TextStyle::Body, - ) - }) - .sum::(); - let separators = parts.len().saturating_sub(1) as f32; - counts + separators * text_width(ui, "·", egui::TextStyle::Body) + 2.0 * separators * COUNTS_GAP -} - -/// "3 ? · 1 ??" in the colours of the signs (nothing when there are none). -fn counts_text(ui: &mut Ui, c: &ErrorCounts) { - let dark = ui.visuals().dark_mode; - let old_gap = ui.spacing().item_spacing.x; - ui.spacing_mut().item_spacing.x = COUNTS_GAP; - for (i, (n, j)) in count_parts(c).into_iter().enumerate() { - if i > 0 { - ui.label(RichText::new("·").weak()); - } - ui.label( - RichText::new(format!("{n} {}", review::judgement_symbol(j))) - .color(review::judgement_text_color(j, dark)), - ); - } - ui.spacing_mut().item_spacing.x = old_gap; -} - -impl PrepScreen { - pub fn new( - start: PrepStart, - db: Arc, - settings: &Settings, - ctx: &egui::Context, - ) -> Self { - let dir = cache_dir(); - let mut cache = dir.as_deref().map(PositionCache::load).unwrap_or_default(); - // A saved preparation of this player: its depth and games, its report. - let saved_dir = crate::prep_saved::dir(); - let names = start.player.names(&db); - let saved_id = crate::prep_saved::id(&start.path, &names); - let saved = saved_dir - .as_deref() - .and_then(|d| crate::prep_saved::get(d, &saved_id)); - let saved_report = saved - .as_ref() - .and(saved_dir.as_deref()) - .and_then(|d| crate::prep_saved::report(d, &saved_id)); - let had_saved_report = saved_report.is_some(); - let plies = saved - .as_ref() - .map_or(settings.prep.plies, |s| s.plies) - .clamp(2, 60); - let period = saved.as_ref().map_or(settings.prep.period, |s| s.period); - let options = Options { - plies, - side: Side::Any, - period, - }; - // The saved report as it is, when the database is the same; else its - // evaluations serve the report made again (new games of the database). - let fresh = saved_report.and_then(|r| { - if r.search != game_review::SEARCH_VERSION { - return None; - } - if r.fingerprint == prep::fingerprint(&db) - && r.options() == options - && r.player == start.player - { - return Some(r); - } - for (k, e) in r.evals { - cache.insert(k, e); - } - None - }); - let mut screen = PrepScreen { - serial: crate::engine_offer::next_serial(), - engine_blocked: None, - db_name: base_name(&start.path), - path: start.path, - db, - player: start.player, - names, - shown: true, - color: start.side, - plies, - period, - saved: crate::prep_saved::dir().is_some(), - want_period: None, - report: None, - rows: Vec::new(), - build: None, - build_total: 0, - job: None, - cache, - nps_per_thread: None, - error: None, - dialog_open: false, - dirty: false, - pending_refresh: false, - last_refresh: 0.0, - marks: [HashMap::new(), HashMap::new()], - tab: match std::env::var("CP_PREP_TAB").as_deref() { - Ok("openings") => Tab::Openings, - Ok("errors") => Tab::Errors, - _ => Tab::Repertoire, - }, - branches_from: settings.prep.branches_from.clamp(1, 20), - expanded: HashSet::new(), - others_open: HashSet::new(), - open_families: HashSet::new(), - open_repeated: HashSet::new(), - open_variations: HashSet::new(), - err_cursor: None, - show_inaccuracies: settings.prep.inaccuracies, - stacked: false, - low_window: false, - selection: Selection::None, - shown_pos: None, - flipped: None, - board_state: BoardState::default(), - board_popup: false, - sorts: settings.prep.sorts.clone(), - focus_games: false, - games_cursor: None, - hover_arrow: None, - scroll_to_selected: false, - games_height: None, - auto_done: false, - }; - let cached = fresh.or_else(|| { - dir.as_deref() - .and_then(|d| PrepReport::load(d, &screen.db, &screen.player, &options)) - }); - match cached { - Some(r) => screen.take_report(r), - None => screen.rebuild(ctx), - } - // A preparation is kept from the moment it is started: the list entry at - // once, the report as soon as it is built (then `save` writes both). - // A saved report missing on disk (a crash between the writes) is restored - // from the cache the same way. - let restore = saved.is_some() && !had_saved_report && screen.report.is_some(); - let rejudged = - saved.as_ref().is_some_and(|s| !s.errors_current()) && screen.report.is_some(); - if screen.saved && (saved.is_none() || restore || rejudged) { - let result = if screen.report.is_some() { - screen.keep() - } else { - screen.keep_meta() - }; - if let Err(e) = result { - eprintln!("prep saved: {e}"); - // Not silently unsaved: told on the screen, tried again by `save`. - screen.dirty = true; - screen.error = Some(trf("Could not save: {e}", &[("e", &e.to_string())])); - } - } - screen - } - - /// The same database and player: the report as it was. - pub fn matches(&self, path: &Path, player: &Player) -> bool { - self.path == path && self.player == *player - } - - pub fn running(&self) -> bool { - self.job.is_some() - } - - /// The background work goes on while the report is not on the screen (a game - /// opened from it, the library): its results are taken in here. - pub fn poll_quietly(&mut self, ctx: &egui::Context, settings: &Settings) { - let mut actions = Vec::new(); - self.poll(ctx, settings, &mut actions); - } - - /// The engine run after an engine was installed for it. - pub fn start_after_engine(&mut self, ctx: &egui::Context) -> Vec { - let mut actions = Vec::new(); - self.start_engine(ctx, &mut actions); - actions - } - - pub fn title(&self) -> String { - let name = self.names.first().cloned().unwrap_or_default(); - trf("Preparing against {name}", &[("name", &name)]) - } - - /// Reads the games anew (a new depth; the database read again). - fn rebuild(&mut self, ctx: &egui::Context) { - self.job = None; - let (db, player) = (self.db.clone(), self.player.clone()); - let options = self.options(); - self.build_total = 0; - let now = ctx.input(|i| i.time); - self.build = Background::spawn(ctx, now, move |progress, cancel| { - prep::build(&db, &player, &options, progress, cancel) - }); - } - - /// A report arrived (built or from the cache): the rows of the games list, the - /// cached evaluations, the default expansion. - fn take_report(&mut self, mut report: PrepReport) { - self.auto_done = false; - let taken = report.take_cached(&self.cache); - self.dirty |= taken > 0; - self.rows = report - .games - .iter() - .map(|g| { - let r = self.db.row(g.index as usize); - ListRow { - white: r.white, - black: r.black, - white_elo: r.white_elo, - black_elo: r.black_elo, - result: r.result, - event: r.event, - } - }) - .collect(); - // Everything folded: the user opens what he wants (the roots too). - self.expanded.clear(); - self.others_open.clear(); - self.open_families.clear(); - self.open_variations.clear(); - self.open_repeated.clear(); - self.report = Some(report); - self.rebuild_marks(); - self.selection = Selection::None; - self.shown_pos = None; - self.games_cursor = None; - self.err_cursor = None; - } - - /// The same player asked for again from the dialog: its colour. - pub fn reopen(&mut self, side: ColorChoice) { - self.shown = true; - // Deleted from «Preparations» while this screen was hidden: not written back. - self.saved &= crate::prep_saved::dir().is_some_and(|d| { - crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names)).is_some() - }); - self.set_color(side); - } - - fn set_color(&mut self, color: ColorChoice) { - // The colour a saved preparation opens with. - self.dirty |= self.saved && color != self.color; - self.color = color; - // A selection of a colour no longer shown is dropped. - let keep = match &self.selection { - Selection::None => true, - Selection::Node { white, .. } - | Selection::Opening { white, .. } - | Selection::Repeated { white, .. } - | Selection::Error { white, .. } => color.colours().contains(white), - }; - if !keep { - self.select(Selection::None); - } - } - - /// Games of the colour(s) shown. - fn shown_games(&self) -> usize { - self.report.as_ref().map_or(0, |r| { - self.color - .colours() - .iter() - .map(|&w| r.color(w).games.len()) - .sum() - }) - } - - /// What the report is built with. - fn options(&self) -> Options { - Options { - plies: self.plies, - side: Side::Any, - period: self.period, - } - } - - /// Another depth: the report of that depth from the cache, else built anew. - fn set_plies(&mut self, plies: usize, settings: &mut Settings, ctx: &egui::Context) { - if plies == self.plies { - return; - } - self.stop_engine(&mut Vec::new()); - self.save(); - self.plies = plies; - settings.prep.plies = plies; - self.load_or_build(ctx); - } - - /// Other games of the player: the report of them from the cache, else built anew. - fn set_period(&mut self, period: Period, settings: &mut Settings, ctx: &egui::Context) { - if period == self.period { - return; - } - self.stop_engine(&mut Vec::new()); - self.save(); - self.period = period; - settings.prep.period = period; - self.load_or_build(ctx); - } - - /// The report of the current options from the cache, else built anew. - fn load_or_build(&mut self, ctx: &egui::Context) { - self.report = None; - let options = self.options(); - let cached = cache_dir() - .as_deref() - .and_then(|d| PrepReport::load(d, &self.db, &self.player, &options)); - match cached { - Some(r) => { - self.take_report(r); - if let Some(report) = self.report.as_mut() - && report.engine_stopped - { - report.engine_stopped = false; - self.dirty = true; - } - self.dirty |= self.saved; - self.save(); - } - None => self.rebuild(ctx), - } - } - - /// The judgement is shown (inaccuracies can be hidden). - fn visible(&self, j: Judgement) -> bool { - self.show_inaccuracies || j != Judgement::Inaccuracy - } - - /// The counts as shown. - fn shown_counts(&self, c: &ErrorCounts) -> ErrorCounts { - let mut c = *c; - if !self.show_inaccuracies { - c.inaccuracies = 0; - } - c - } - - /// The engine run for the colour(s) shown. - fn engine_state(&self) -> EngineState { - if self.job.is_some() { - return EngineState::Running; - } - let Some(report) = &self.report else { - return EngineState::NotRun; - }; - let side = self.color.side(); - if !report.evaluated() { - // Stopped before the first evaluation: not «never run», but 0 of N with - // «Continue». - if report.engine_stopped { - let total = report.distinct_positions_for(side); - return EngineState::Partial { done: 0, total }; - } - return EngineState::NotRun; - } - let total = report.distinct_positions_for(side); - let missing = report.missing_for(side); - if missing == 0 { - EngineState::Complete { total } - } else { - EngineState::Partial { - done: total - missing, - total, - } - } - } - - /// Judges the errors anew (`f` changes the evaluations): the lists of errors are - /// rebuilt, so a chosen error is found again in them by what it is, not by its - /// place (else the choice is dropped). - fn rejudge(&mut self, f: impl FnOnce(&mut PrepReport)) { - let Some(report) = self.report.as_mut() else { - return; - }; - // What the selection and the errors tab's row are, by content. - let error_id = |r: &PrepReport, white: bool, i: usize| { - r.color(white).errors.get(i).map(|e| (e.game, e.ply)) - }; - let repeated_id = |r: &PrepReport, white: bool, i: usize| { - r.color(white) - .repeated - .get(i) - .map(|x| (x.key, x.uci.clone())) - }; - let sel = match &self.selection { - Selection::Error { white, index } => { - error_id(report, *white, *index).map(|id| (*white, Ok(id))) - } - Selection::Repeated { white, index } => { - repeated_id(report, *white, *index).map(|id| (*white, Err(id))) - } - _ => None, - }; - let cursor = match self.err_cursor { - Some(ErrRow::Error { white, index }) => { - error_id(report, white, index).map(|id| (white, Ok(id))) - } - Some(ErrRow::Repeated { white, index }) => { - repeated_id(report, white, index).map(|id| (white, Err(id))) - } - _ => None, - }; - let open: Vec<(bool, (u64, String))> = self - .open_repeated - .iter() - .filter_map(|&(w, i)| repeated_id(report, w, i).map(|id| (w, id))) - .collect(); - f(report); - let find = |r: &PrepReport, - white: bool, - id: &Result<(u32, u32), (u64, String)>| - -> Option { - match id { - Ok((game, ply)) => r - .color(white) - .errors - .iter() - .position(|e| e.game == *game && e.ply == *ply), - Err((key, uci)) => r - .color(white) - .repeated - .iter() - .position(|x| x.key == *key && x.uci == *uci), - } - }; - if let Some((white, id)) = &sel { - let found = find(report, *white, id); - self.selection = match (found, id) { - (Some(index), Ok(_)) => Selection::Error { - white: *white, - index, - }, - (Some(index), Err(_)) => Selection::Repeated { - white: *white, - index, - }, - (None, _) => Selection::None, - }; - if found.is_none() { - self.shown_pos = None; - } - } - if let Some((white, id)) = &cursor { - self.err_cursor = match (find(report, *white, id), id) { - (Some(index), Ok(_)) => Some(ErrRow::Error { - white: *white, - index, - }), - (Some(index), Err(_)) => Some(ErrRow::Repeated { - white: *white, - index, - }), - (None, _) => None, - }; - } else if matches!(self.err_cursor, Some(ErrRow::RepeatedGame { .. })) { - self.err_cursor = None; - } - self.open_repeated = open - .into_iter() - .filter_map(|(w, (key, uci))| { - let i = report - .color(w) - .repeated - .iter() - .position(|x| x.key == key && x.uci == uci)?; - Some((w, i)) - }) - .collect(); - self.rebuild_marks(); - } - - /// The errors by node, for the tree and the hover texts. - fn rebuild_marks(&mut self) { - let Some(report) = &self.report else { return }; - for (i, cr) in [&report.white, &report.black].into_iter().enumerate() { - let mut map: HashMap<(u64, String), Mark> = HashMap::new(); - for e in &cr.errors { - let m = map.entry((e.key, e.uci.clone())).or_insert_with(|| Mark { - judgement: e.judgement, - best_san: e.best_san.clone(), - before: e.before, - after: e.after, - games: 0, - }); - m.games += 1; - } - self.marks[i] = map; - } - } - - fn mark_of(&self, white: bool, key: u64, uci: &str) -> Option<&Mark> { - self.marks[usize::from(!white)].get(&(key, uci.to_owned())) - } - - // ----- the background work ----------------------------------------------------- - - fn poll(&mut self, ctx: &egui::Context, settings: &Settings, actions: &mut Vec) { - if let Some(job) = &self.build - && let Some(r) = job.poll() - { - self.build = None; - match r { - Some(report) => { - self.take_report(report); - // A saved preparation follows its new games and depth; the first - // report of a just started one is written at once, not on quitting. - self.dirty |= self.saved; - self.save(); - } - None => self.error = Some(tr("The games could not be read").to_owned()), - } - } - self.show_inaccuracies = settings.prep.inaccuracies; - self.poll_engine(ctx, actions); - // The one automatic engine run of this report, once it is built; a manual - // Stop forbids it. Without an engine there is no offer by itself: the Errors - // tab says so and offers the download. - if !self.auto_done && self.build.is_none() { - self.auto_done = true; - let start = self - .report - .as_ref() - .is_some_and(|r| !r.engine_stopped && !r.targets_for(self.color.side()).is_empty()); - if start { - if crate::review_engine::engine().is_some() { - self.start_engine(ctx, actions); - } else { - self.tab = Tab::Errors; - } - } - } - if self.build.is_some() || self.job.is_some() { - ctx.request_repaint_after(std::time::Duration::from_millis(100)); - } - } - - // ----- the engine ---------------------------------------------------------------- - - /// Positions the next run has to evaluate, and how long it takes. - fn estimate(&self) -> (usize, f64) { - let Some(report) = &self.report else { - return (0, 0.0); - }; - let missing = report.missing_for(self.color.side()); - (missing, self.secs_for(missing, review::processes())) - } - - /// Seconds `positions` take in `processes` engine processes. - fn secs_for(&self, positions: usize, processes: usize) -> f64 { - let nps = self.nps_per_thread.unwrap_or(review::DEFAULT_NPS); - game_review::estimate_secs(positions, nps, processes) - } - - /// The button: the search at once, no dialog; the options are only the «▾» dialog. - fn engine_asked(&mut self, ctx: &egui::Context, actions: &mut Vec) { - // Nothing to evaluate: no engine offer, just the state (an empty report too). - if self - .report - .as_ref() - .is_some_and(|r| r.targets_for(self.color.side()).is_empty()) - { - self.tab = Tab::Errors; - actions.push(PrepAction::Toast( - tr("Every position is already evaluated").to_owned(), - )); - return; - } - if crate::review_engine::engine().is_none() { - actions.push(PrepAction::NeedEngine); - return; - } - self.start_engine(ctx, actions); - } - - /// Starts the search for opening errors: Stockfish 19 (`review_engine`) with the fixed - /// search of the game analysis (`game_review::run`), the same on every computer. - fn start_engine(&mut self, ctx: &egui::Context, actions: &mut Vec) { - // A running search is not restarted (e.g. «Find errors» in the options dialog). - if self.job.is_some() { - return; - } - if let Some(why) = &self.engine_blocked { - self.error = Some(why.clone()); - return; - } - self.error = None; - // A start by hand (or by the new report) clears the manual Stop of this one. - if let Some(report) = self.report.as_mut() - && report.engine_stopped - { - report.engine_stopped = false; - self.dirty = true; - } - let Some(path) = crate::review_engine::engine() else { - actions.push(PrepAction::NeedEngine); - return; - }; - let cache = std::mem::take(&mut self.cache); - let mut taken = 0; - self.rejudge(|r| taken = r.take_cached(&cache)); - self.cache = cache; - self.dirty |= taken > 0; - let Some(report) = self.report.as_ref() else { - return; - }; - let targets = report.targets_for(self.color.side()); - if targets.is_empty() { - actions.push(PrepAction::Toast( - tr("Every position is already evaluated").to_owned(), - )); - self.tab = Tab::Errors; - return; - } - let (tx, rx) = channel(); - let cancel = Arc::new(AtomicBool::new(false)); - let total = targets.len(); - let job_settings = JobSettings::new(review::processes(), None); - let processes = job_settings.processes; - let spawned = review::spawn_job( - "prep-engine", - path, - job_settings, - targets, - cancel.clone(), - tx, - ctx.clone(), - ); - let runner = match spawned { - Ok(r) => r, - Err(e) => { - self.error = Some(e.to_string()); - return; - } - }; - self.job = Some(EngineJob { - runner, - rx, - cancel, - total, - done: 0, - processes, - unsaved: 0, - }); - self.tab = Tab::Errors; - actions.push(PrepAction::EngineStarted); - } - - fn poll_engine(&mut self, ctx: &egui::Context, actions: &mut Vec) { - let Some(job) = self.job.as_mut() else { return }; - let Some(report) = self.report.as_mut() else { - return; - }; - let mut ended = false; - let mut got = false; - job.runner.pump(); - while let Ok(msg) = job.rx.try_recv() { - match msg { - JobMsg::Event(e) => { - if let JobEvent::Eval { nps, .. } = &e { - job.done += 1; - // One engine thread per process. - if *nps > 0 { - self.nps_per_thread = Some(*nps as f64); - } - } - if let Some((k, eval)) = report.apply(&e) { - self.cache.insert(k, eval); - job.unsaved += 1; - got = true; - } - } - JobMsg::Done => ended = true, - JobMsg::Failed(e) => { - self.error = Some(e); - ended = true; - } - } - } - if got { - self.pending_refresh = true; - self.dirty = true; - } - if job.unsaved >= 200 - && let Some(dir) = cache_dir() - { - let _ = self.cache.save(&dir); - job.unsaved = 0; - } - let now = ctx.input(|i| i.time); - if self.pending_refresh && (ended || now - self.last_refresh > 1.0) { - self.pending_refresh = false; - self.last_refresh = now; - self.rejudge(PrepReport::refresh); - } - if ended { - self.job = None; - self.save(); - actions.push(PrepAction::EngineEnded); - } - } - - /// Stops the engine run (quitting): what was evaluated is kept. - pub fn stop(&mut self) { - self.stop_engine(&mut Vec::new()); - } - - /// «Stop»: what was evaluated stays, including what is already in the channel. - fn stop_engine(&mut self, actions: &mut Vec) { - if let Some(mut job) = self.job.take() { - if let Some(report) = self.report.as_mut() { - job.runner.pump(); - while let Ok(msg) = job.rx.try_recv() { - if let JobMsg::Event(e) = msg - && let Some((k, eval)) = report.apply(&e) - { - self.cache.insert(k, eval); - // The drained evaluations belong in the saved report too. - self.dirty = true; - } - } - } - self.rejudge(PrepReport::refresh); - self.pending_refresh = false; - self.save(); - actions.push(PrepAction::EngineEnded); - } - } - - /// «Stop» pressed by the user: the evaluations stay, and this report is not run - /// automatically again (a new depth/period or «Continue» clears that). - fn stop_engine_by_user(&mut self, actions: &mut Vec) { - if self.job.is_some() - && let Some(report) = self.report.as_mut() - { - report.engine_stopped = true; - // Even before the first evaluation the stop is written, not lost on exit. - self.dirty = true; - } - self.stop_engine(actions); - } - - /// Writes the report and the evaluations to the cache, and to «Preparations» when - /// the preparation is kept there. - pub fn save(&mut self) { - let Some(dir) = cache_dir() else { return }; - if let Err(e) = self.cache.save(&dir) { - eprintln!("prep cache: {}: {e}", dir.display()); - } - if self.dirty - && let Some(r) = &self.report - { - let mut ok = true; - if let Err(e) = r.save(&dir) { - ok = false; - eprintln!("prep report: {}: {e}", dir.display()); - } - // Deleted from «Preparations» meanwhile: not written back. - self.saved &= crate::prep_saved::dir().is_some_and(|d| { - crate::prep_saved::get(&d, &crate::prep_saved::id(&self.path, &self.names)) - .is_some() - }); - if self.saved - && let Err(e) = self.keep() - { - ok = false; - eprintln!("prep saved: {e}"); - } - if ok { - self.dirty = false; - } - } - } - - /// Writes the preparation to «Preparations» (its name in the list kept). - fn keep(&self) -> std::io::Result<()> { - let dir = - crate::prep_saved::dir().ok_or_else(|| std::io::Error::other("no data folder"))?; - let Some(report) = &self.report else { - return Ok(()); - }; - crate::prep_saved::save(&dir, &self.saved_meta(), report) - } - - /// Writes only the list entry: a preparation just started, its report not built yet. - fn keep_meta(&self) -> std::io::Result<()> { - let dir = - crate::prep_saved::dir().ok_or_else(|| std::io::Error::other("no data folder"))?; - crate::prep_saved::save_meta(&dir, &self.saved_meta()) - } - - /// The list entry as it is now; the counts of the report, when there is one. - fn saved_meta(&self) -> crate::prep_saved::SavedPrep { - let id = crate::prep_saved::id(&self.path, &self.names); - let previous = crate::prep_saved::dir().and_then(|d| crate::prep_saved::get(&d, &id)); - let title = previous - .as_ref() - .map(|m| m.title.clone()) - .unwrap_or_else(|| self.names.first().cloned().unwrap_or_default()); - let book = previous.map_or_else(PathBuf::new, |m| m.book); - let mut errors = ErrorCounts::default(); - let mut games = 0; - let mut evaluated = false; - if let Some(report) = &self.report { - for c in [&report.white, &report.black] { - errors.inaccuracies += c.counts.inaccuracies; - errors.mistakes += c.counts.mistakes; - errors.blunders += c.counts.blunders; - } - games = report.games.len() as u32; - evaluated = report.evaluated(); - } - crate::prep_saved::SavedPrep { - title, - path: self.path.clone(), - player: self.player.clone(), - names: self.names.clone(), - plies: self.plies, - period: self.period, - color: self.color, - book, - saved: crate::prep_saved::now(), - games, - errors, - evaluated, - error_selection_version: crate::prep_saved::ERROR_SELECTION_VERSION, - } - } - - /// The options dialog (§4.2), only by the explicit «▾». - fn engine_dialog( - &mut self, - ctx: &egui::Context, - _settings: &mut Settings, - actions: &mut Vec, - ) { - if !self.dialog_open { - return; - } - let mut start = false; - let moves = self.plies.div_ceil(2); - let (white_n, black_n) = self - .report - .as_ref() - .map_or((0, 0), |r| (r.white.games.len(), r.black.games.len())); - let modal = egui::Modal::new(egui::Id::new("prep_engine_dialog")).show(ctx, |ui| { - let screen = ctx.content_rect(); - ui.set_width((screen.width() - 40.0).min(460.0)); - ui.heading(tr("Opening errors")); - ui.label( - RichText::new(trf( - "The engine evaluates the first {n} moves of every game of the opponent. The games are not changed.", - &[("n", &moves)], - )) - .weak(), - ); - ui.add_space(8.0); - egui::ScrollArea::vertical() - .max_height((screen.height() - 160.0).max(100.0)) - .auto_shrink([false, true]) - .show(ui, |ui| { - ui.horizontal_wrapped(|ui| { - ui.label(tr("Colour")); - for (choice, n) in [ - (ColorChoice::White, white_n), - (ColorChoice::Black, black_n), - (ColorChoice::Both, white_n + black_n), - ] { - let label = format!("{} — {}", choice.label(), crate::i18n::games(n)); - ui.radio_value(&mut self.color, choice, label); - } - }); - ui.add_space(6.0); - let (missing, secs) = self.estimate(); - let all = self - .report - .as_ref() - .map_or(0, |r| r.distinct_positions_for(self.color.side())); - ui.label(trf( - "{n} positions, about {time}", - &[("n", &grouped(missing)), ("time", &review::format_duration(secs))], - )); - let cached = all.saturating_sub(missing); - let note = if cached > 0 { - trf( - "identical positions are counted once; {n} already evaluated earlier", - &[("n", &grouped(cached))], - ) - } else { - tr("identical positions are counted once").to_owned() - }; - ui.label(RichText::new(note).weak().small()); - }); - ui.add_space(10.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui - .button(RichText::new(tr("Find errors")).strong().size(16.0)) - .clicked() - { - start = true; - } - if ui.button(tr("Cancel")).clicked() { - self.dialog_open = false; - } - }); - }); - if modal.should_close() { - self.dialog_open = false; - } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Enter)) { - start = true; - } - if start { - self.dialog_open = false; - self.engine_asked(ctx, actions); - } - } - - // ----- the selection and the board --------------------------------------------- - - fn select(&mut self, sel: Selection) { - if self.selection == sel { - return; - } - self.selection = sel; - self.games_cursor = None; - self.shown_pos = self.shown_for(&self.selection); - self.board_state.clear(); - } - - /// The position of a selection and the way to it. - fn shown_for(&self, sel: &Selection) -> Option { - let report = self.report.as_ref()?; - let from_game = |g: &GameInfo, ply: usize, white: bool| -> Shown { - let ucis: Vec = g.ucis[..ply.min(g.ucis.len())].to_vec(); - let sans: Vec = g.sans[..ucis.len()].to_vec(); - let positions = replay(&ucis); - Shown { - ply: positions.len() - 1, - sans, - ucis, - positions, - arrows: Vec::new(), - note: None, - opening: None, - white, - } - }; - match sel { - Selection::None => None, - Selection::Node { white, node } => { - let cr = report.color(*white); - let n = cr.tree.nodes.get(*node as usize)?; - let g = &report.games[*n.games.first()? as usize]; - let mut s = from_game(g, usize::from(n.ply), *white); - s.opening = n.opening; - Some(s) - } - Selection::Opening { - white, - family, - variation, - } => { - let cr = report.color(*white); - let fam = cr.families.get(*family)?; - let var = match variation { - Some(v) => fam.variations.get(*v)?, - None => fam.variations.first()?, - }; - // The named position: a game of the variation at its named ply; the - // family's: the shallowest of its variations' names. - let (g, ply) = match variation { - Some(_) => { - let g = var - .games - .iter() - .map(|&g| &report.games[g as usize]) - .find(|g| g.opening == var.opening)?; - (g, g.named.unwrap_or(0) as usize) - } - None if fam.name.is_empty() => { - // No name: the start position. - let g = var.games.first().map(|&g| &report.games[g as usize])?; - (g, 0) - } - None => { - // The family's own position: where its name first appears in - // a line (the shallowest among the games). - let mut best: Option<(&GameInfo, usize)> = None; - for v in &fam.variations { - for &gi in &v.games { - let g = &report.games[gi as usize]; - if g.opening.is_none() { - continue; - } - let ply = family_ply(g, &fam.name) - .unwrap_or(g.named.unwrap_or(0) as usize); - if best.is_none_or(|(_, p)| ply < p) { - best = Some((g, ply)); - } - } - } - best? - } - }; - let mut s = from_game(g, ply, *white); - s.opening = var.opening; - Some(s) - } - Selection::Repeated { white, index } => { - let cr = report.color(*white); - let r = cr.repeated.get(*index)?; - let g = &report.games[*r.games.first()? as usize]; - let mut s = from_game(g, r.ply as usize, *white); - s.arrows = error_arrows( - &s.positions[s.ply], - &r.uci, - cr.errors - .iter() - .find(|e| e.key == r.key && e.uci == r.uci) - .map(|e| e.best_uci.as_str()), - r.judgement, - ); - s.note = cr - .errors - .iter() - .find(|e| e.key == r.key && e.uci == r.uci) - .map(error_note); - s.opening = r.opening; - Some(s) - } - Selection::Error { white, index } => { - let cr = report.color(*white); - let e = cr.errors.get(*index)?; - let g = &report.games[e.game as usize]; - let mut s = from_game(g, e.ply as usize, *white); - s.arrows = - error_arrows(&s.positions[s.ply], &e.uci, Some(&e.best_uci), e.judgement); - s.note = Some(error_note(e)); - s.opening = e.opening; - Some(s) - } - } - } - - /// The games of the selection (indices into the report), newest first. - fn games_of(&self) -> Vec { - let Some(report) = &self.report else { - return Vec::new(); - }; - let list: Vec = match &self.selection { - Selection::None => self - .color - .colours() - .iter() - .flat_map(|&w| report.color(w).games.iter().copied()) - .collect(), - // The games of the position, by any move order. - Selection::Node { white, node } => { - let tree = &report.color(*white).tree; - tree.nodes - .get(*node as usize) - .map(|n| tree.position_games(n.key)) - .unwrap_or_default() - } - Selection::Opening { - white, - family, - variation, - } => report - .color(*white) - .families - .get(*family) - .map(|f| match variation { - Some(v) => f - .variations - .get(*v) - .map(|v| v.games.clone()) - .unwrap_or_default(), - None => f - .variations - .iter() - .flat_map(|v| v.games.iter().copied()) - .collect(), - }) - .unwrap_or_default(), - Selection::Repeated { white, index } => report - .color(*white) - .repeated - .get(*index) - .map(|r| r.games.clone()) - .unwrap_or_default(), - Selection::Error { white, index } => report - .color(*white) - .errors - .get(*index) - .map(|e| vec![e.game]) - .unwrap_or_default(), - }; - let sort = self.sorts.games; - let val = |gi: u32| -> SortVal { - let g = &report.games[gi as usize]; - let r = &self.rows[gi as usize]; - match sort.key { - GameSort::White => SortVal::Text(fold(&r.white)), - GameSort::Black => SortVal::Text(fold(&r.black)), - GameSort::WhiteElo => num(r.white_elo), - GameSort::BlackElo => num(r.black_elo), - GameSort::Result => SortVal::Text(r.result.to_owned()), - GameSort::Date => num(g.date_number()), - GameSort::Then => SortVal::Text( - g.sans - .iter() - .skip(self.game_ply(gi)) - .take(3) - .cloned() - .collect::>() - .join(" "), - ), - GameSort::Event => SortVal::Text(fold(&r.event)), - GameSort::Errors => num(report - .color(g.white) - .errors - .iter() - .filter(|e| e.game == gi && self.visible(e.judgement)) - .map(|e| judgement_weight(e.judgement)) - .sum::()), - } - }; - let mut keyed: Vec<(SortVal, u32)> = list.into_iter().map(|g| (val(g), g)).collect(); - keyed.sort_by(|a, b| sort.apply(cmp_val(&a.0, &b.0))); - keyed.into_iter().map(|(_, g)| g).collect() - } - - /// The move of the selection to open a game at. - fn selection_ply(&self) -> usize { - self.shown_pos.as_ref().map_or(0, |s| s.ucis.len()) - } - - /// Where game `gi` reaches the chosen position: a node's position may come by - /// another move order (another ply) in some of its games. - fn game_ply(&self, gi: u32) -> usize { - if let (Selection::Node { white, node }, Some(report)) = (&self.selection, &self.report) - && let Some(n) = report.color(*white).tree.nodes.get(*node as usize) - && let Some(p) = report.games[gi as usize] - .keys - .iter() - .position(|k| *k == n.key) - { - return p; - } - self.selection_ply() - } - - /// The move to open game `gi` at: the chosen position, or after the error. - fn open_ply(&self, gi: u32) -> usize { - let after = matches!( - self.selection, - Selection::Error { .. } | Selection::Repeated { .. } - ); - self.game_ply(gi) + usize::from(after) - } - - /// The player's colour the board is seen from. - fn board_white(&self) -> bool { - let base = self - .shown_pos - .as_ref() - .map_or(self.color != ColorChoice::Black, |s| s.white); - match self.flipped { - Some(f) => f == base, - None => base, - } - } - - // ----- the frame ----------------------------------------------------------------- - - /// Draws the screen; what the application has to do. - pub fn show(&mut self, ui: &mut Ui, settings: &mut Settings) -> Vec { - let mut actions = Vec::new(); - let ctx = ui.ctx().clone(); - self.poll(&ctx, settings, &mut actions); - self.hover_arrow = None; - let typing = ctx.egui_wants_keyboard_input(); - let overlay = crate::app::overlay_open(&ctx) || self.dialog_open; - - egui::Panel::top("prep_header").show(ui, |ui| { - ui.add_space(4.0); - self.header(ui, &mut actions); - ui.add_space(4.0); - }); - let content = ctx.content_rect(); - let (w, h) = (content.width(), content.height() - 44.0); - let stacked = w < BOARD_MIN + 24.0 + RIGHT_MIN || h < 600.0; - let low = stacked && h < 720.0; - self.stacked = stacked; - self.low_window = h < 600.0; - egui::Panel::top("prep_controls").show(ui, |ui| { - ui.add_space(4.0); - self.controls(ui, settings, low, &mut actions); - ui.add_space(2.0); - self.summary(ui, stacked); - ui.add_space(4.0); - }); - if self.report.is_none() { - egui::CentralPanel::default().show(ui, |ui| self.building(ui, &mut actions)); - } else if stacked { - if !low { - egui::Panel::top("prep_board_stack").show(ui, |ui| { - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.allocate_ui(vec2(240.0, 240.0), |ui| self.board(ui, settings, 240.0)); - ui.vertical(|ui| { - self.board_caption(ui); - self.board_info(ui, &mut actions); - }); - }); - ui.add_space(4.0); - }); - } - egui::CentralPanel::default() - .show(ui, |ui| self.right_column(ui, settings, &mut actions)); - if low && self.board_popup { - self.board_overlay(&ctx, settings, &mut actions); - } - } else { - let board_side = (h - 120.0) - .min(420.0) - .min(w - BOARD_MIN - 24.0 - RIGHT_MIN + BOARD_MIN) - .max(BOARD_MIN) - .floor(); - egui::Panel::left("prep_board") - .exact_size(board_side + 24.0) - .resizable(false) - .show(ui, |ui| { - ui.add_space(6.0); - ui.vertical(|ui| { - self.board_caption(ui); - self.board(ui, settings, board_side); - self.board_info(ui, &mut actions); - }); - }); - egui::CentralPanel::default() - .show(ui, |ui| self.right_column(ui, settings, &mut actions)); - } - self.engine_dialog(&ctx, settings, &mut actions); - if let Some(p) = self.want_period.take() { - self.set_period(p, settings, &ctx); - actions.push(PrepAction::SettingsChanged); - } - if !typing && !overlay { - self.keyboard(&ctx, settings, &mut actions); - } - if settings.prep.sorts != self.sorts { - settings.prep.sorts = self.sorts.clone(); - actions.push(PrepAction::SettingsChanged); - } - actions - } - - fn header(&mut self, ui: &mut Ui, actions: &mut Vec) { - let gap = ui.spacing().item_spacing.x; - let button_w = |ui: &Ui, text: &str| { - text_width(ui, text, egui::TextStyle::Button) - + 2.0 * ui.spacing().button_padding.x - + gap - }; - let row = ui.available_width(); - let compact = row < 700.0; - let left = button_w(ui, if compact { "⬅" } else { tr("⬅ Library") }) + 2.0 * gap; - let right = button_w(ui, if compact { "⚙" } else { tr("⚙ Settings") }); - let title_room = (row - left - right).max(80.0); - ui.horizontal(|ui| { - if ui - .button(if compact { "⬅" } else { tr("⬅ Library") }) - .on_hover_text(tr("Back to the game list (Esc, Ctrl+W)")) - .clicked() - { - actions.push(PrepAction::Back); - } - ui.separator(); - let name = self.names.first().cloned().unwrap_or_default(); - let more = self.names.len().saturating_sub(1); - let mut parts = Vec::new(); - if let Some(r) = &self.report { - parts.push(crate::i18n::games(self.shown_games())); - let p = period(&r.games); - if !p.is_empty() { - parts.push(p); - } - } - parts.push(self.db_name.clone()); - let title = if compact { - name.clone() - } else { - trf("Preparing against {name}", &[("name", &name)]) - }; - ui.allocate_ui(vec2(title_room, 24.0), |ui| { - ui.horizontal(|ui| { - ui.set_max_width(title_room); - ui.add(egui::Label::new(RichText::new(title).strong().size(15.0)).truncate()); - if more > 0 { - ui.label(RichText::new(trf("+{n} spelling", &[("n", &more)])).weak()) - .on_hover_text(self.names.join("\n")); - } - let skipped = self.report.as_ref().map_or(0, |r| r.skipped); - let r = ui.add( - egui::Label::new(RichText::new(format!("· {}", parts.join(" · "))).weak()) - .truncate(), - ); - if skipped > 0 { - r.on_hover_text(trf( - "not counted: from a set position — {n}", - &[("n", &skipped)], - )); - } - }); - }); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui - .button(if compact { "⚙" } else { tr("⚙ Settings") }) - .on_hover_text(tr("Settings (Ctrl+,)")) - .clicked() - { - actions.push(PrepAction::OpenSettings); - } - }); - }); - } - - /// The colour switch, the depth and the engine button or its progress. - fn controls( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - low: bool, - actions: &mut Vec, - ) { - let width = ui.available_width(); - let gap = ui.spacing().item_spacing.x; - let pad = 2.0 * ui.spacing().button_padding.x; - let state = self.engine_state(); - // The engine part on the right is measured first: the rest gets what it leaves. - let engine = self.engine_texts(state, width); - let engine_w = match &engine { - EngineTexts::Running => { - (width * 0.35).clamp(90.0, 360.0) - + text_width(ui, tr("Stop"), egui::TextStyle::Button) - + pad - + 2.0 * gap - } - EngineTexts::Button { label, note } | EngineTexts::Done { label, note } => { - text_width(ui, label, egui::TextStyle::Button) - + pad - + note - .as_deref() - .map_or(0.0, |n| text_width(ui, n, egui::TextStyle::Body) + gap) - + gap - } - } + 26.0 - + gap; - ui.horizontal(|ui| { - for choice in [ColorChoice::White, ColorChoice::Black, ColorChoice::Both] { - if ui - .selectable_label(self.color == choice, choice.label()) - .clicked() - { - self.set_color(choice); - } - } - ui.separator(); - let moves = self.plies.div_ceil(2); - let board_w = if low { - text_width(ui, "♙", egui::TextStyle::Button) + pad + 2.0 * gap - } else { - 0.0 - }; - // The period's and the depth's captions by the room left, shortened in one - // order at every width: the depth first, then the period, then both. - let depths = [ - trf("Opening: {n} moves", &[("n", &moves)]), - trf("{n} moves", &[("n", &moves)]), - trf("{n} m.", &[("n", &moves)]), - ]; - let periods = self.period_captions(); - let combo = |t: &str| text_width(ui, t, egui::TextStyle::Button) + pad + 20.0 + gap; - let room = - ui.available_width() - engine_w - board_w - ui.spacing().item_spacing.x * 2.0; - let (p, d) = [(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)] - .into_iter() - .find(|&(p, d)| combo(&periods[p]) + combo(&depths[d]) <= room) - .unwrap_or((2, 2)); - let [p0, p1, p2] = periods; - let period_label_now = [p0, p1, p2].into_iter().nth(p).unwrap_or_default(); - self.period_picker(ui, settings, period_label_now, actions); - ui.separator(); - let depth_label = depths[d].clone(); - let mut new_plies = None; - let depth_w = text_width(ui, &depth_label, egui::TextStyle::Button) + 8.0; - egui::ComboBox::from_id_salt("prep_plies") - .width(depth_w) - .selected_text(depth_label) - .show_ui(ui, |ui| { - for m in [6usize, 10, 15] { - if ui - .selectable_label( - self.plies == m * 2, - trf("Opening: {n} moves", &[("n", &m)]), - ) - .clicked() - { - new_plies = Some(m * 2); - } - } - }) - .response - .on_hover_text(tr("How deep the tree and the engine look")); - if let Some(p) = new_plies { - self.set_plies(p, settings, ui.ctx()); - actions.push(PrepAction::SettingsChanged); - } - if low { - ui.separator(); - if ui - .selectable_label(self.board_popup, "♙") - .on_hover_text(tr("The board of the chosen position")) - .clicked() - { - self.board_popup = !self.board_popup; - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - self.engine_control(ui, settings, engine, width, actions); - }); - }); - } - - /// The period shown: a period by months over games without dates takes all. - fn period_shown(&self) -> Period { - let dated = self - .report - .as_ref() - .is_some_and(|r| r.pool.iter().any(|g| g.date != 0)); - match self.period { - Period::Months(_) if self.report.is_some() && !dated => Period::All, - p => p, - } - } - - /// How many games `p` takes of the colour(s) shown: «80», «100 + 100». - fn period_number(&self, p: Period) -> String { - let Some(r) = &self.report else { - return "…".to_owned(); - }; - let side = self.color.side(); - match (p, side) { - // The last N of each colour, not N in all. - (Period::Last(_), Side::Any) => format!( - "{} + {}", - grouped(r.count(p, Side::White).games), - grouped(r.count(p, Side::Black).games) - ), - _ => grouped(r.count(p, side).games), - } - } - - /// The period's captions, longest first: «Last 2 years · 80», «2 yrs · 80», «80». - fn period_captions(&self) -> [String; 3] { - let p = self.period_shown(); - let n = self.period_number(p); - [ - format!("{} · {n}", period_label(p)), - format!("{} · {n}", period_short(p)), - n, - ] - } - - /// «Last 2 years · 80 ▾»: which of the player's games, with how many each takes of - /// the colour(s) shown; `selected` is the caption the row has room for. - fn period_picker( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - selected: String, - actions: &mut Vec, - ) { - let side = self.color.side(); - let report = self.report.as_ref(); - let dated = report.is_some_and(|r| r.pool.iter().any(|g| g.date != 0)); - let shown = self.period_shown(); - let number = |p: Period| self.period_number(p); - let mut picked = None; - // As wide as its text: the room is the row's. - let width = text_width(ui, &selected, egui::TextStyle::Button) + 8.0; - let r = egui::ComboBox::from_id_salt("prep_period") - .width(width) - .selected_text(selected) - .show_ui(ui, |ui| { - for p in PERIODS { - // Without dates: by number only. - if matches!(p, Period::Months(_)) && !dated { - continue; - } - let text = format!("{} · {}", period_label(p), number(p)); - if ui.selectable_label(shown == p, text).clicked() { - picked = Some(p); - } - } - let note = |ui: &mut Ui, text: String| { - ui.label(RichText::new(text).weak().small()); - }; - if !dated { - note(ui, tr("The games have no dates: by number only").to_owned()); - } else if let Some(r) = report { - let newest = prep::period_newest(&r.pool); - note( - ui, - trf( - "Counted back from his newest game — {date}", - &[("date", &shown_date(newest))], - ), - ); - let out = r.count(Period::Months(12), side).undated_out; - if out > 0 { - note( - ui, - trf( - "Without a date: {n} — taken only with all games", - &[("n", &grouped(out))], - ), - ); - } - } - }) - .response; - r.on_hover_text(tr( - "Which of his games: by date — counted back from his newest game; by number — the newest of each colour", - )); - if let Some(p) = picked { - self.set_period(p, settings, ui.ctx()); - actions.push(PrepAction::SettingsChanged); - } - } - - /// What the engine part of the controls says, by the room there is. - fn engine_texts(&self, state: EngineState, width: f32) -> EngineTexts { - let (missing, secs) = self.estimate(); - let time = review::format_duration(secs); - match state { - EngineState::Running => EngineTexts::Running, - EngineState::NotRun => EngineTexts::Button { - label: if width < 700.0 { - format!("▶ ≈ {time}") - } else if width < 900.0 { - trf("▶ Errors ≈ {time}", &[("time", &time)]) - } else { - trf("▶ Find opening errors ≈ {time}", &[("time", &time)]) - }, - note: None, - }, - EngineState::Partial { done, total } => EngineTexts::Button { - label: if width < 700.0 { - format!("▶ ≈ {time}") - } else { - trf("Continue ≈ {time}", &[("time", &time)]) - }, - note: (width >= 900.0).then(|| { - trf( - "Checked {done} of {total} positions", - &[("done", &grouped(done)), ("total", &grouped(total))], - ) - }), - }, - EngineState::Complete { .. } => { - let _ = missing; - EngineTexts::Done { - label: tr("Errors found").to_owned(), - note: None, - } - } - } - } - - /// The engine button, the progress while it runs, the state after; «▾» (the - /// options) at the right end. - fn engine_control( - &mut self, - ui: &mut Ui, - _settings: &Settings, - texts: EngineTexts, - width: f32, - actions: &mut Vec, - ) { - if ui.button("▾").on_hover_text(tr("Options…")).clicked() { - self.dialog_open = true; - } - if let Some(job) = &self.job { - let (done, total) = (job.done, job.total); - if ui.button(tr("Stop")).on_hover_text("Shift+A").clicked() { - self.stop_engine_by_user(actions); - return; - } - let secs = self.secs_for(total.saturating_sub(done), job.processes); - let text = if width < 760.0 { - format!("{}/{}", grouped(done), grouped(total)) - } else { - trf( - "Finding errors: {done} of {total} positions · ≈ {time}", - &[ - ("done", &grouped(done)), - ("total", &grouped(total)), - ("time", &review::format_duration(secs)), - ], - ) - }; - ui.add( - egui::ProgressBar::new(done as f32 / total.max(1) as f32) - .desired_width((width * 0.35).clamp(90.0, 360.0)) - .text(text), - ); - return; - } - let Some(report) = &self.report else { return }; - let hint = self.engine_status().unwrap_or_else(|| { - tr("The engine finds the opening errors in his games (Shift+A)").to_owned() - }); - let _ = report; - match texts { - EngineTexts::Done { label, .. } => { - ui.label(RichText::new(label).weak()).on_hover_text(hint); - } - EngineTexts::Button { label, note } => { - // Nothing to search in no games. - let some = self.shown_games() > 0; - if ui - .add_enabled_ui(some, |ui| crate::widgets::primary(ui, &label)) - .inner - .on_hover_text(hint) - .clicked() - { - self.engine_asked(ui.ctx(), actions); - } - if let Some(n) = note { - ui.label(RichText::new(n).weak()); - } - } - EngineTexts::Running => {} - } - if let Some(e) = &self.error { - ui.label(RichText::new("⚠").color(ui.visuals().error_fg_color)) - .on_hover_text(e); - } - } - - /// «Errors found · Stockfish 19 · 2 947 positions», once evaluated. - fn engine_status(&self) -> Option { - let report = self.report.as_ref()?; - if !report.evaluated() { - return None; - } - let n = grouped(report.distinct_positions_for(self.color.side())); - Some( - match report.engine.as_ref().filter(|e| !e.name.is_empty()) { - Some(e) => trf( - "Errors found · {engine} · {n} positions", - &[("engine", &e.name), ("n", &n)], - ), - None => trf("Errors found · {n} positions", &[("n", &n)]), - }, - ) - } - - /// The summary: a row per colour in columns — colour, games, score, opponents, - /// the last game, then separate error counts and percentages. Secondary columns - /// give way from the right (the last game, then the opponents) instead of wrapping. - fn summary(&self, ui: &mut Ui, stacked: bool) { - let Some(report) = &self.report else { return }; - let colours = if stacked { - self.color.colours() - } else { - vec![true, false] - }; - let evaluated = report.evaluated() && !stacked; - // Texts per colour: [colour, games, score, opponents, last]. - let mut rows: Vec<(bool, [String; 5], String, ErrorCounts, usize)> = Vec::new(); - for &white in &colours { - let cr = report.color(white); - let root = &cr.tree.nodes[0]; - let tally = &root.tally; - let title = if white { - tr("As White") - } else { - tr("As Black") - } - .to_owned(); - let score = if tally.games > 0 { - format!("{} ({})", score_text(tally), tally_hint(tally)) - } else { - String::new() - }; - let compact_score = if tally.games > 0 { - score_text(tally) - } else { - String::new() - }; - let opponents = root - .average_elo() - .map(|elo| trf("opponents ≈ {elo}", &[("elo", &elo)])) - .unwrap_or_default(); - let last = crate::library::display_date(&root.last_date); - let last = if last.is_empty() { - String::new() - } else { - trf("last {date}", &[("date", &last)]) - }; - let with_errors: HashSet = cr - .errors - .iter() - .filter(|e| self.visible(e.judgement)) - .map(|e| e.game) - .collect(); - let p = 100 * with_errors.len() / cr.games.len().max(1); - rows.push(( - white, - [title, tally.games.to_string(), score, opponents, last], - compact_score, - self.shown_counts(&cr.counts), - p, - )); - } - // The colour, games and score percentage stay; secondary columns give way. - let gap = 14.0; - let col_w = |k: usize, compact_score: bool| -> f32 { - rows.iter() - .map(|r| { - let text = if k == 2 && compact_score { - &r.2 - } else { - &r.1[k] - }; - text_width(ui, text, egui::TextStyle::Body) - }) - .fold(0.0, f32::max) - }; - let no_errors_w = text_width(ui, tr("no errors"), egui::TextStyle::Body); - let counts_w = if evaluated { - rows.iter() - .map(|(_, _, _, counts, _)| { - if counts.total() > 0 { - errors_text_width(ui, counts) - } else { - no_errors_w - } - }) - .fold(0.0, f32::max) - } else { - 0.0 - }; - let percent_w = if evaluated { - rows.iter() - .filter(|(_, _, _, counts, _)| counts.total() > 0) - .map(|(_, _, _, _, p)| { - text_width( - ui, - &trf("in {p} % of games", &[("p", p)]), - egui::TextStyle::Body, - ) - }) - .fold(0.0, f32::max) - } else { - 0.0 - }; - let has_percent = percent_w > 0.0; - let width = ui.available_width(); - let mut shown = [true; 5]; - if stacked { - shown[3] = false; - shown[4] = false; - } - let used = |shown: &[bool; 5], compact_score: bool| -> f32 { - let base_cells = shown.iter().filter(|&&show| show).count(); - let cells = base_cells + usize::from(evaluated) + usize::from(has_percent); - let base_w = (0..5) - .filter(|&k| shown[k]) - .map(|k| col_w(k, compact_score)) - .sum::(); - base_w + counts_w + percent_w + cells.saturating_sub(1) as f32 * gap - }; - for k in [4, 3] { - if used(&shown, stacked) <= width { - break; - } - shown[k] = false; - } - let compact_score = stacked || used(&shown, false) > width; - let grid_columns = shown.iter().filter(|&&show| show).count() - + usize::from(evaluated) - + usize::from(has_percent); - egui::Grid::new("prep_summary") - .num_columns(grid_columns) - .spacing(vec2(gap, 2.0)) - .show(ui, |ui| { - for (white, texts, short_score, counts, p) in &rows { - let weak = !self.color.colours().contains(white); - for k in 0..5 { - if !shown[k] { - continue; - } - let text = if k == 2 && compact_score { - short_score - } else { - &texts[k] - }; - let rt = RichText::new(text); - let rt = if k <= 1 { rt.strong() } else { rt }; - if k == 1 { - ui.with_layout( - egui::Layout::right_to_left(egui::Align::Center), - |ui| { - ui.label(if weak { rt.weak() } else { rt }); - }, - ); - } else { - ui.label(if weak { rt.weak() } else { rt }); - } - } - if evaluated { - ui.horizontal(|ui| { - if counts.total() > 0 { - counts_text(ui, counts); - } else { - ui.label(RichText::new(tr("no errors")).weak()); - } - }); - } - if has_percent { - if counts.total() > 0 { - ui.label(RichText::new(trf("in {p} % of games", &[("p", p)])).weak()); - } else { - ui.label(""); - } - } - ui.end_row(); - } - }); - let n: usize = self - .color - .colours() - .iter() - .map(|&w| report.color(w).games.len()) - .sum(); - if let Period::Months(_) = report.period { - let out = report.count(report.period, self.color.side()).undated_out; - if out > 0 { - ui.label( - RichText::new(trf( - "Without a date, not counted: {n} (only with all games)", - &[("n", &grouped(out))], - )) - .weak(), - ); - } - } - if n > 0 && n < 10 { - ui.label( - RichText::new(trf( - "Few games ({n}): percentages and scores are unreliable", - &[("n", &n)], - )) - .color(ui.visuals().warn_fg_color), - ); - } - } - - /// The report is being built: its progress. - fn building(&mut self, ui: &mut Ui, actions: &mut Vec) { - ui.add_space(40.0); - ui.vertical_centered(|ui| { - if let Some(e) = &self.error { - ui.label(RichText::new(e).color(ui.visuals().error_fg_color)); - if ui.button(tr("Try again")).clicked() { - self.error = None; - self.rebuild(ui.ctx()); - } - return; - } - let Some(job) = &self.build else { return }; - let done = job.progress(); - let total = self.build_total.max(done).max(1); - ui.add(egui::Spinner::new().size(18.0)); - let p = 100 * done / total; - ui.label(trf("Collecting games… {p} %", &[("p", &p.min(99))])); - if ui.button(tr("Cancel")).clicked() { - actions.push(PrepAction::Back); - } - }); - } - - // ----- the board ----------------------------------------------------------------- - - /// «Black to move · after 3.Bb5» over the board. - fn board_caption(&self, ui: &mut Ui) { - let text = match &self.shown_pos { - Some(s) => { - let pos = &s.positions[s.ply]; - let side = if pos.turn() == Color::White { - tr("White to move") - } else { - tr("Black to move") - }; - match s - .ply - .checked_sub(1) - .and_then(|p| s.sans.get(p).map(|san| short_label(p, san))) - { - Some(m) => format!("{side} · {}", trf("after {move}", &[("move", &m)])), - None => side.to_owned(), - } - } - None => tr("Start position").to_owned(), - }; - ui.label(RichText::new(text).weak()); - } - - fn board(&mut self, ui: &mut Ui, settings: &Settings, side: f32) { - let start = Chess::default(); - let (pos, last_move, arrows): (&Chess, Option<(Square, Square)>, Vec) = - match &self.shown_pos { - Some(s) => { - let pos = &s.positions[s.ply]; - let last = s - .ply - .checked_sub(1) - .and_then(|p| s.ucis.get(p)) - .and_then(|u| u.parse::().ok()) - .and_then(|u| u.to_move(&s.positions[s.ply - 1]).ok()) - .and_then(|m| Some((m.from()?, crate::board::ui_target(&m)))); - let mut arrows = if s.ply + 1 == s.positions.len() { - s.arrows.clone() - } else { - Vec::new() - }; - if let Some((from, to)) = self.hover_arrow { - arrows.push(Arrow { - from, - to, - color: PREVIEW_ARROW, - weight: 1.0, - }); - } - (pos, last, arrows) - } - None => { - let mut arrows = Vec::new(); - if let Some((from, to)) = self.hover_arrow { - arrows.push(Arrow { - from, - to, - color: PREVIEW_ARROW, - weight: 1.0, - }); - } - (&start, None, arrows) - } - }; - let view = BoardView { - pos, - orientation: if self.board_white() { - Color::White - } else { - Color::Black - }, - last_move, - arrows: &arrows, - circles: &[], - badge: None, - interactive: false, - temporary_shapes: false, - show_coords: settings.show_coords, - theme: settings.board_theme.theme(), - pieces: settings.piece_set, - animation: settings.animation.seconds(), - premove: None, - auto_queen: settings.auto_queen, - alert: None, - }; - ui.allocate_ui(vec2(side, side), |ui| { - view.show(ui, &mut self.board_state); - }); - } - - /// Under the board: the line (a click takes the board along it), the opening, the - /// note of an error, «Open as a game» and the menu. - fn board_info(&mut self, ui: &mut Ui, actions: &mut Vec) { - ui.add_space(4.0); - let Some(report) = &self.report else { return }; - let Some(s) = &self.shown_pos else { - ui.label( - RichText::new(tr( - "Choose a move in the tree, an opening or an error: its position is shown here", - )) - .weak(), - ); - return; - }; - let mut goto = None; - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - if s.sans.is_empty() { - ui.label(RichText::new(tr("Start position")).weak()); - } - for (i, san) in s.sans.iter().enumerate() { - // Numbers at White's moves only: «1.e4 c5 2.Nf3 d6». - let label = if i.is_multiple_of(2) { - short_label(i, san) - } else { - crate::san::show(san).into_owned() - }; - let current = i + 1 == s.ply; - let text = if current { - RichText::new(label).strong() - } else { - RichText::new(label) - }; - if ui - .add(egui::Label::new(text).sense(Sense::click())) - .clicked() - { - goto = Some(i + 1); - } - } - }); - if let Some(o) = s.opening.and_then(|o| report.openings.get(o)) { - ui.label( - RichText::new(format!("{} · {}", o.name, o.eco)) - .weak() - .small(), - ); - } - if let Some(note) = &s.note { - ui.label(RichText::new(note).small()); - } - let (sans, ucis, pos, white, ply) = ( - s.sans.clone(), - s.ucis.clone(), - s.positions[s.ply].clone(), - s.white, - s.ply, - ); - ui.horizontal(|ui| { - if ui - .button(tr("Open as a game")) - .on_hover_text(tr("The line as a new game, to add moves and comments")) - .clicked() - { - actions.push(PrepAction::OpenPgn(self.line_pgn(&sans[..ply], white))); - } - ui.menu_button("⋯", |ui| { - if ui.button(tr("Play on from here…")).clicked() { - let moves: Vec = { - let mut p = Chess::default(); - ucis[..ply] - .iter() - .filter_map(|u| { - let m = u.parse::().ok()?.to_move(&p).ok()?; - p.play_unchecked(m); - Some(m) - }) - .collect() - }; - let last = moves - .last() - .and_then(|m| Some((m.from()?, crate::board::ui_target(m)))); - let after = ply.checked_sub(1).map(|p| prep::move_label(p, &sans[p])); - actions.push(PrepAction::PlayFrom(Box::new(crate::play::StartFrom { - start_fen: None, - moves, - position: pos.clone(), - last, - after: after.clone(), - after_shown: after.map(|a| crate::san::show(&a).into_owned()), - game: Some(self.title()), - null_dropped: false, - }))); - ui.close(); - } - if ui - .button(tr("Find this position in a database (Ctrl+Shift+F)")) - .clicked() - { - let mut p = Chess::default(); - let moves: Vec = ucis[..ply] - .iter() - .filter_map(|u| { - let m = u.parse::().ok()?.to_move(&p).ok()?; - p.play_unchecked(m); - Some(m) - }) - .collect(); - actions.push(PrepAction::FindPosition( - self.path.clone(), - Chess::default(), - moves, - !self.board_white(), - )); - ui.close(); - } - if ui.button(tr("Copy FEN")).clicked() { - let fen = - shakmaty::fen::Fen::from_position(&pos, shakmaty::EnPassantMode::Legal) - .to_string(); - actions.push(PrepAction::CopyText(fen, tr("FEN copied"))); - ui.close(); - } - if ui.button(tr("Copy moves (PGN)")).clicked() { - actions.push(PrepAction::CopyText( - self.line_pgn(&sans[..ply], white), - tr("PGN copied"), - )); - ui.close(); - } - }); - }); - if let Some(p) = goto - && let Some(s) = self.shown_pos.as_mut() - { - s.ply = p; - self.board_state.clear(); - } - } - - /// The line as a PGN game: the player on his side, the opponent unnamed. - fn line_pgn(&self, sans: &[String], white: bool) -> String { - let name = self.names.first().cloned().unwrap_or_default(); - let (w, b) = if white { - (name, "?".to_owned()) - } else { - ("?".to_owned(), name) - }; - let mut moves = String::new(); - for (i, san) in sans.iter().enumerate() { - if i.is_multiple_of(2) { - moves.push_str(&format!("{}. ", i / 2 + 1)); - } - moves.push_str(san); - moves.push(' '); - } - format!( - "[Event \"{}\"]\n[White \"{w}\"]\n[Black \"{b}\"]\n[Result \"*\"]\n\n{moves}*\n", - self.title() - ) - } - - /// In a low window: the board over the right bottom of the screen. - fn board_overlay( - &mut self, - ctx: &egui::Context, - settings: &Settings, - actions: &mut Vec, - ) { - let screen = ctx.content_rect(); - let size = vec2(264.0, 300.0); - let rect = egui::Rect::from_min_size(screen.right_bottom() - size, size); - let area = egui::Area::new(egui::Id::new("prep_board_overlay")) - .order(egui::Order::Middle) - .fixed_pos(rect.min) - .show(ctx, |ui| { - let frame = egui::Frame::side_top_panel(ui.style()) - .stroke(ui.visuals().window_stroke) - .shadow(egui::Shadow { - offset: [-6, -6], - blur: 16, - spread: 0, - color: Color32::from_black_alpha(110), - }); - frame.show(ui, |ui| { - ui.set_min_size(size - vec2(16.0, 16.0)); - ui.set_max_size(size - vec2(16.0, 16.0)); - self.board_caption(ui); - self.board(ui, settings, 240.0); - ui.horizontal(|ui| { - if ui.button(tr("Open as a game")).clicked() - && let Some(s) = &self.shown_pos - { - actions.push(PrepAction::OpenPgn( - self.line_pgn(&s.sans[..s.ply], s.white), - )); - } - }); - }); - }); - if area.response.clicked_elsewhere() { - self.board_popup = false; - } - } - - // ----- the right column --------------------------------------------------------- - - /// The tabs over the games list, the border between them draggable. (A nested - /// bottom panel would not do: in a top-down `Ui` egui's available rect ignores - /// the cursor's bottom, so the content above overlaps it.) - fn right_column( - &mut self, - ui: &mut Ui, - settings: &mut Settings, - actions: &mut Vec, - ) { - let height = ui.available_height(); - let width = ui.available_width(); - // In a low window the tabs keep the most: two rows of games at least, a quarter. - let (rows, share) = if self.low_window { - (2.0, 0.25) - } else { - (4.0, 0.35) - }; - let least = rows * ROW_H + 60.0; - let most = (height - 160.0).max(least); - let games_h = self - .games_height - .unwrap_or(height * share) - .clamp(least, most) - .floor(); - let tabs_h = (height - games_h - 10.0).max(0.0); - ui.allocate_ui_with_layout( - vec2(width, tabs_h), - egui::Layout::top_down(egui::Align::Min), - |ui| { - ui.set_min_height(tabs_h); - ui.set_max_height(tabs_h); - self.tabs(ui, settings, actions); - }, - ); - // The border: dragged, it gives the games list more or less. - let (rect, resp) = ui.allocate_exact_size(vec2(width, 10.0), Sense::drag()); - if resp.hovered() || resp.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); - } - if resp.dragged() { - self.games_height = Some((games_h - resp.drag_delta().y).clamp(least, most)); - } - let stroke = if resp.hovered() || resp.dragged() { - ui.visuals().widgets.hovered.fg_stroke - } else { - ui.visuals().widgets.noninteractive.bg_stroke - }; - ui.painter().hline(rect.x_range(), rect.center().y, stroke); - ui.allocate_ui_with_layout( - vec2(width, games_h), - egui::Layout::top_down(egui::Align::Min), - |ui| { - ui.set_min_height(games_h); - ui.set_max_height(games_h); - self.games_list(ui, actions); - }, - ); - } - - fn tabs(&mut self, ui: &mut Ui, settings: &mut Settings, actions: &mut Vec) { - { - ui.horizontal(|ui| { - for (tab, label, key) in [ - (Tab::Repertoire, tr("Repertoire"), "Ctrl+1"), - (Tab::Openings, tr("Openings"), "Ctrl+2"), - (Tab::Errors, tr("Errors"), "Ctrl+3"), - ] { - ui.selectable_value(&mut self.tab, tab, label) - .on_hover_text(key); - } - if self.tab == Tab::Repertoire { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.small_button(tr("Collapse")).clicked() { - self.collapse_selected(); - } - if ui.small_button(tr("Expand all")).clicked() { - self.expand_selected(); - } - let mut n = self.branches_from; - egui::ComboBox::from_id_salt("prep_branches") - .selected_text(trf("Branches from {n} games", &[("n", &n)])) - .show_ui(ui, |ui| { - for k in [2u32, 3, 5] { - ui.selectable_value( - &mut n, - k, - trf("Branches from {n} games", &[("n", &k)]), - ); - } - }) - .response - .on_hover_text(tr("Moves with fewer games fold into «other moves»")); - if n != self.branches_from { - self.branches_from = n; - settings.prep.branches_from = n; - actions.push(PrepAction::SettingsChanged); - } - }); - } - }); - ui.add_space(2.0); - match self.tab { - Tab::Repertoire => self.tree_table(ui), - Tab::Openings => self.openings_table(ui), - Tab::Errors => self.errors_tab(ui, settings, actions), - } - } - } - - fn expand_selected(&mut self) { - let Some(report) = &self.report else { return }; - let roots: Vec<(bool, u32)> = match &self.selection { - Selection::Node { white, node } => vec![(*white, *node)], - _ => self.color.colours().iter().map(|&w| (w, 0)).collect(), - }; - for (white, root) in roots { - let tree = &report.color(white).tree; - let mut stack = vec![root]; - while let Some(n) = stack.pop() { - self.expanded.insert((white, n)); - self.others_open.insert((white, n)); - stack.extend(tree.nodes[n as usize].children.iter().copied()); - } - } - } - - fn collapse_selected(&mut self) { - let Some(report) = &self.report else { return }; - match &self.selection { - Selection::Node { white, node } => { - let tree = &report.color(*white).tree; - let mut stack = vec![*node]; - while let Some(n) = stack.pop() { - self.expanded.remove(&(*white, n)); - self.others_open.remove(&(*white, n)); - stack.extend(tree.nodes[n as usize].children.iter().copied()); - } - } - _ => { - self.expanded.retain(|(_, n)| *n == 0); - self.others_open.clear(); - } - } - } - - /// The rows of the tree as laid out for the colour switch and the expansion. - fn tree_rows(&self) -> Vec { - let Some(report) = &self.report else { - return Vec::new(); - }; - let mut rows = Vec::new(); - for white in self.color.colours() { - let tree = &report.color(white).tree; - if tree.nodes.is_empty() { - continue; - } - // (node, depth, after the main children: the others) - let mut stack: Vec = vec![TreeRow::Node { - white, - node: 0, - depth: 0, - }]; - while let Some(row) = stack.pop() { - rows.push(row); - let (node, depth, listed) = match row { - TreeRow::Node { node, depth, .. } => { - if !self.expanded.contains(&(white, node)) { - continue; - } - (node, depth, false) - } - TreeRow::Others { parent, depth, .. } => { - if !self.others_open.contains(&(white, parent)) { - continue; - } - // The folded moves go under the «other moves» row. - (parent, depth, true) - } - }; - let n = &tree.nodes[node as usize]; - let mut children = n.children.clone(); - let sort = self.sorts.tree; - let val = |c: u32| -> SortVal { - let m = &tree.nodes[c as usize]; - match sort.key { - TreeSort::Games => num(tree.position_tally(m.key).games), - TreeSort::Share => num(m.tally.games), - TreeSort::Score => score_val(&tree.position_tally(m.key)), - TreeSort::Last => num(chess_import::pgn_catalog::date_number( - tree.position_last_date(m.key), - )), - } - }; - // Ties: most played first, as the tree has them. - children.sort_by(|&a, &b| sort.apply(cmp_val(&val(a), &val(b)))); - let (main, rest): (Vec, Vec) = children - .into_iter() - .partition(|&c| tree.nodes[c as usize].tally.games >= self.branches_from); - // Pushed in reverse: the stack pops the first child first. - if listed { - for &c in rest.iter().rev() { - stack.push(TreeRow::Node { - white, - node: c, - depth: depth + 1, - }); - } - } else { - if !rest.is_empty() { - stack.push(TreeRow::Others { - white, - parent: node, - depth: depth + 1, - count: rest.len(), - }); - } - for &c in main.iter().rev() { - stack.push(TreeRow::Node { - white, - node: c, - depth: depth + 1, - }); - } - } - } - } - rows - } - - fn tree_table(&mut self, ui: &mut Ui) { - let rows = self.tree_rows(); - if rows.len() <= 1 { - self.no_games_note(ui); - } - let Some(report) = self.report.as_ref() else { - return; - }; - let width = ui.available_width(); - let gap = ui.spacing().item_spacing.x; - let mut used = 180.0 + 76.0 + 48.0 + 50.0 + 4.0 * gap; - let mut fits = |w: f32, wanted: bool| { - let ok = wanted && used + w + gap <= width; - if ok { - used += w + gap; - } - ok - }; - let show_opening = fits(160.0, true); - let show_bar = fits(64.0, true); - let show_last = fits(84.0, true); - ui.style_mut().interaction.selectable_labels = false; - let mut table = TableBuilder::new(ui) - .id_salt("prep_tree") - .striped(true) - .sense(Sense::click()) - .auto_shrink([false, false]) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::remainder().at_least(180.0).clip(true)); - if show_opening { - table = table.column(Column::remainder().at_least(160.0).clip(true)); - } - table = table - .column(Column::exact(76.0)) - .column(Column::exact(48.0)); - table = table.column(Column::exact(if show_bar { 110.0 } else { 50.0 })); - if show_last { - table = table.column(Column::exact(84.0)); - } - let selected_row = rows.iter().position(|r| match (r, &self.selection) { - ( - TreeRow::Node { white, node, .. }, - Selection::Node { - white: sw, - node: sn, - }, - ) => white == sw && node == sn, - _ => false, - }); - if self.scroll_to_selected - && let Some(i) = selected_row - { - table = table.scroll_to_row(i, None); - } - self.scroll_to_selected = false; - let mut clicked: Option = None; - let mut toggled: Option = None; - let mut hovered: Option<(bool, u32)> = None; - let mut tree_click = None; - table - .header(ROW_H, |mut h| { - head_col(&mut h, tr("Move"), tr("His moves plain, the opponents' weak; ⇄ — the position is reached by another move order too")); - if show_opening { - head_col(&mut h, tr("Opening"), ""); - } - let sort = self.sorts.tree; - sort_col(&mut h, tr("Games"), "", TreeSort::Games, sort, &mut tree_click); - sort_col(&mut h, "%", tr("Share of the games of the move above"), TreeSort::Share, sort, &mut tree_click); - sort_col(&mut h, tr("Score"), tr("The opponent's points in these games"), TreeSort::Score, sort, &mut tree_click); - if show_last { - sort_col(&mut h, tr("Last"), "", TreeSort::Last, sort, &mut tree_click); - } - }) - .body(|body| { - body.rows(ROW_H, rows.len(), |mut row| { - let r = rows[row.index()]; - row.set_selected(Some(row.index()) == selected_row); - match r { - TreeRow::Others { white, parent, depth, count } => { - let open = self.others_open.contains(&(white, parent)); - row.col(|ui| { - ui.add_space(depth as f32 * 14.0); - let glyph = if open { "▾" } else { "▸" }; - if ui.add(egui::Label::new(RichText::new(glyph).weak()).sense(Sense::click())).clicked() { - toggled = Some(r); - } - // Short when the column is narrow at this depth. - let full = trf("other moves ({n})", &[("n", &count)]); - let text = if text_width(ui, &full, egui::TextStyle::Body) > ui.available_width() { - trf("others ({n})", &[("n", &count)]) - } else { - full - }; - ui.label(RichText::new(text).weak()); - }); - let rest = 2 + usize::from(show_opening) + 1 + usize::from(show_last); - for _ in 0..rest { - row.col(|_| {}); - } - } - TreeRow::Node { white, node, depth } => { - let cr = report.color(white); - let n = &cr.tree.nodes[node as usize]; - let parent = n.parent.map(|p| &cr.tree.nodes[p as usize]); - let has_children = !n.children.is_empty(); - let open = self.expanded.contains(&(white, node)); - // The statistics are the position's, whatever the move order. - let tally = cr.tree.position_tally(n.key); - let few = tally.games < FEW_GAMES; - row.col(|ui| { - ui.add_space(depth as f32 * 14.0); - let glyph = if !has_children { " " } else if open { "▾" } else { "▸" }; - let g = ui.add(egui::Label::new(RichText::new(glyph).weak()).sense(Sense::click())); - if g.clicked() && has_children { - toggled = Some(r); - } - if n.parent.is_none() { - let title = if white { tr("As White") } else { tr("As Black") }; - ui.label(RichText::new(format!("{title} · {}", n.tally.games)).strong()); - return; - } - let ply = usize::from(n.ply) - 1; - let players = ply.is_multiple_of(2) == white; - let label = short_label(ply, &n.san); - let text = if players { RichText::new(label) } else { RichText::new(label).weak() }; - let l = ui.add(egui::Label::new(text).truncate()); - if !show_opening - && let Some(o) = n.opening.filter(|_| n.named).and_then(|o| report.openings.get(o)) - { - l.on_hover_text(format!("{} · {}", o.name, o.eco)); - } - if n.transposition { - let others: Vec = cr - .tree - .nodes - .iter() - .enumerate() - .filter(|(i, m)| m.key == n.key && *i != node as usize) - .map(|(i, _)| line_text(&cr.tree.path(i).iter().map(|s| (*s).to_owned()).collect::>())) - .collect(); - ui.label(RichText::new("⇄").weak()).on_hover_text(trf( - "Reached by another move order too: {orders}", - &[("orders", &others.join("; "))], - )); - } - if let Some(p) = parent - && let Some(m) = self.mark_of(white, p.key, &n.uci) - && self.visible(m.judgement) - { - let best = crate::san::show(&m.best_san).into_owned(); - pill(ui, m.judgement).on_hover_text(trf( - "{judgement}: better {best} ({before} → {after}) · in {n} games", - &[ - ("judgement", &review::judgement_name(m.judgement)), - ("best", &best), - ("before", &m.before.format()), - ("after", &m.after.format()), - ("n", &m.games), - ], - )); - if m.games > 1 { - ui.label(RichText::new(format!("×{}", m.games)).weak().small()); - } - } - }); - if show_opening { - row.col(|ui| { - // The name where it changes (`named`); the ECO keeps - // its place at the right, the name takes the rest. - if n.named && let Some(o) = n.opening.and_then(|o| report.openings.get(o)) { - let eco = RichText::new(&o.eco).weak().small(); - let eco_w = text_width(ui, &o.eco, egui::TextStyle::Small) + ui.spacing().item_spacing.x; - let name_w = (ui.available_width() - eco_w).max(0.0); - ui.allocate_ui(vec2(name_w, ROW_H), |ui| { - ui.add(egui::Label::new(RichText::new(&o.name).weak()).truncate()) - .on_hover_text(format!("{} · {}", o.name, o.eco)); - }); - ui.label(eco); - } - }); - } - row.col(|ui| { - ui.label(tally.games.to_string()); - }); - row.col(|ui| { - // The move's share where the games were (this order). - if let Some(p) = parent { - let pct = 100 * n.tally.games / p.tally.games.max(1); - let t = RichText::new(format!("{pct}")); - let l = ui.label(if few { t.weak() } else { t }); - if few { - l.on_hover_text(tr("Few games: percentages are unreliable")); - } - } - }); - row.col(|ui| { - let t = RichText::new(score_text(&tally)); - let l = ui.label(if few { t.weak() } else { t }); - l.on_hover_text(tally_hint(&tally)); - if show_bar { - score_bar(ui, &tally, white, few); - } - }); - if show_last { - row.col(|ui| { - let d = crate::library::display_date(cr.tree.position_last_date(n.key)); - ui.label(RichText::new(if d.is_empty() { "—".to_owned() } else { d }).weak()); - }); - } - let resp = row.response(); - if resp.hovered() { - hovered = Some((white, node)); - } - if resp.double_clicked() && has_children { - toggled = Some(r); - } else if resp.clicked() { - clicked = Some(r); - } - } - } - }); - }); - if let Some(k) = tree_click { - self.sorts.tree.click(k, false); - } - // A child of the chosen node under the pointer: its move as an arrow. - if let ( - Some((white, node)), - Selection::Node { - white: sw, - node: sn, - }, - ) = (hovered, &self.selection) - && white == *sw - { - let cr = report.color(white); - let n = &cr.tree.nodes[node as usize]; - if n.parent == Some(*sn) - && let Some(s) = &self.shown_pos - && s.ply + 1 == s.positions.len() - && let Some(m) = n - .uci - .parse::() - .ok() - .and_then(|u| u.to_move(&s.positions[s.ply]).ok()) - { - self.hover_arrow = m.from().map(|f| (f, crate::board::ui_target(&m))); - } - } - if let Some(t) = toggled { - match t { - TreeRow::Node { white, node, .. } => { - if !self.expanded.remove(&(white, node)) { - self.expanded.insert((white, node)); - } - } - TreeRow::Others { white, parent, .. } => { - if !self.others_open.remove(&(white, parent)) { - self.others_open.insert((white, parent)); - } - } - } - } else if let Some(TreeRow::Node { white, node, .. }) = clicked { - self.focus_games = false; - self.select(Selection::Node { white, node }); - } else if let Some(TreeRow::Others { white, parent, .. }) = clicked - && !self.others_open.remove(&(white, parent)) - { - self.others_open.insert((white, parent)); - } - } - - /// «No games as Black. As White — 138 · Show White» when the colour has none. - fn no_games_note(&mut self, ui: &mut Ui) { - let Some(report) = &self.report else { return }; - // No game in the period at all: the way back to all of them. - let side = self.color.side(); - if report.period != Period::All && report.count(report.period, side).games == 0 { - let all = report.count(Period::All, side).games; - ui.add_space(12.0); - ui.label(match self.color { - ColorChoice::White => tr("No games as White in this period"), - ColorChoice::Black => tr("No games as Black in this period"), - ColorChoice::Both => tr("No games in this period"), - }); - if all > 0 - && ui - .button(format!("{} · {}", period_label(Period::All), grouped(all))) - .clicked() - { - self.want_period = Some(Period::All); - } - return; - } - let (shown, other) = match self.color { - ColorChoice::White => (true, false), - ColorChoice::Black => (false, true), - ColorChoice::Both => return, - }; - if !report.color(shown).games.is_empty() { - return; - } - let other_n = report.color(other).games.len(); - let (colour, other_name) = if shown { - (tr("White"), tr("Black")) - } else { - (tr("Black"), tr("White")) - }; - ui.add_space(12.0); - ui.horizontal_wrapped(|ui| { - ui.label(trf( - "No games as {colour}. As {other} — {n}", - &[("colour", &colour), ("other", &other_name), ("n", &other_n)], - )); - if other_n > 0 - && ui - .link(trf("Show {other}", &[("other", &other_name)])) - .clicked() - { - self.set_color(ColorChoice::from_side(if other { - Side::White - } else { - Side::Black - })); - } - }); - } - - // ----- the openings -------------------------------------------------------------- - - /// The value of a family (`v` None) or a variation for the openings' order. - fn opening_val(&self, white: bool, f: usize, v: Option, key: OpeningSort) -> SortVal { - let Some(report) = &self.report else { - return num(0); - }; - let cr = report.color(white); - let fam = &cr.families[f]; - let vars: Vec<&prep::Variation> = match v { - Some(v) => vec![&fam.variations[v]], - None => fam.variations.iter().collect(), - }; - let tally = match v { - Some(v) => fam.variations[v].tally, - None => fam.tally, - }; - let opening = |var: &prep::Variation| var.opening.and_then(|o| report.openings.get(o)); - match key { - OpeningSort::Name => SortVal::Text(match v { - Some(_) => vars[0] - .opening - .map_or_else(String::new, |o| report.openings[o].name.clone()), - None => fam.name.clone(), - }), - OpeningSort::Eco => SortVal::Text( - vars.iter() - .filter_map(|x| opening(x)) - .map(|o| o.eco.clone()) - .min() - .unwrap_or_default(), - ), - OpeningSort::Games | OpeningSort::Share => num(tally.games), - OpeningSort::Score => score_val(&tally), - OpeningSort::Last => num(vars - .iter() - .flat_map(|x| x.games.iter()) - .map(|&g| report.games[g as usize].date_number()) - .max() - .unwrap_or(0)), - OpeningSort::Errors => num(vars - .iter() - .flat_map(|x| x.error_list.iter()) - .map(|&e| cr.errors[e as usize].judgement) - .filter(|j| self.visible(*j)) - .map(judgement_weight) - .sum::()), - } - } - - /// The rows of the openings table: (white, family, variation) — families in the - /// chosen order, the variations of an open one under it in the same order. - fn opening_rows(&self) -> Vec<(bool, usize, Option)> { - let Some(report) = &self.report else { - return Vec::new(); - }; - let sort = self.sorts.openings; - let mut rows = Vec::new(); - for white in self.color.colours() { - let cr = report.color(white); - let mut fams: Vec = (0..cr.families.len()).collect(); - fams.sort_by(|&a, &b| { - sort.apply(cmp_val( - &self.opening_val(white, a, None, sort.key), - &self.opening_val(white, b, None, sort.key), - )) - }); - for f in fams { - rows.push((white, f, None)); - if self.open_families.contains(&(white, f)) { - let mut vars: Vec = (0..cr.families[f].variations.len()).collect(); - vars.sort_by(|&a, &b| { - sort.apply(cmp_val( - &self.opening_val(white, f, Some(a), sort.key), - &self.opening_val(white, f, Some(b), sort.key), - )) - }); - rows.extend(vars.into_iter().map(|v| (white, f, Some(v)))); - } - } - } - rows - } - - fn openings_table(&mut self, ui: &mut Ui) { - let rows = self.opening_rows(); - let Some(report) = self.report.as_ref() else { - return; - }; - if rows.is_empty() { - self.no_games_note(ui); - return; - } - let both = self.color == ColorChoice::Both; - let width = ui.available_width(); - let gap = ui.spacing().item_spacing.x; - let mut used = 180.0 + 76.0 + 48.0 + 50.0 + 4.0 * gap + if both { 24.0 + gap } else { 0.0 }; - let mut fits = |w: f32, wanted: bool| { - let ok = wanted && used + w + gap <= width; - if ok { - used += w + gap; - } - ok - }; - // The errors stay as long as possible; the first moves give way first. - let show_errors = fits(90.0, report.evaluated()); - let show_bar = fits(64.0, true); - let show_eco = fits(64.0, true); - let show_last = fits(84.0, true); - let show_moves = fits(140.0, true); - ui.style_mut().interaction.selectable_labels = false; - let mut table = TableBuilder::new(ui) - .id_salt("prep_openings") - .striped(true) - .sense(Sense::click()) - .auto_shrink([false, false]) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)); - if both { - table = table.column(Column::exact(24.0)); - } - table = table.column(Column::remainder().at_least(180.0).clip(true)); - if show_eco { - table = table.column(Column::exact(64.0)); - } - if show_moves { - table = table.column(Column::remainder().at_least(140.0).clip(true)); - } - table = table - .column(Column::exact(76.0)) - .column(Column::exact(48.0)); - table = table.column(Column::exact(if show_bar { 110.0 } else { 50.0 })); - if show_last { - table = table.column(Column::exact(84.0)); - } - if show_errors { - table = table.column(Column::exact(90.0)); - } - let selected_row = rows.iter().position(|&(w, f, v)| { - self.selection - == Selection::Opening { - white: w, - family: f, - variation: v, - } - }); - if self.scroll_to_selected - && let Some(i) = selected_row - { - table = table.scroll_to_row(i, None); - } - self.scroll_to_selected = false; - let mut clicked = None; - let mut opening_click = None; - let mut toggled = None; - table - .header(ROW_H, |mut h| { - if both { - head_col(&mut h, "", ""); - } - let sort = self.sorts.openings; - let c = &mut opening_click; - sort_col(&mut h, tr("Opening"), "", OpeningSort::Name, sort, c); - if show_eco { - sort_col(&mut h, "ECO", "", OpeningSort::Eco, sort, c); - } - if show_moves { - head_col(&mut h, tr("First moves"), ""); - } - sort_col(&mut h, tr("Games"), "", OpeningSort::Games, sort, c); - sort_col( - &mut h, - "%", - tr("Share of the colour's games; a variation's — of its family's"), - OpeningSort::Share, - sort, - c, - ); - sort_col( - &mut h, - tr("Score"), - tr("The opponent's points in these games"), - OpeningSort::Score, - sort, - c, - ); - if show_last { - sort_col(&mut h, tr("Last"), "", OpeningSort::Last, sort, c); - } - if show_errors { - sort_col(&mut h, tr("Errors"), "", OpeningSort::Errors, sort, c); - } - }) - .body(|body| { - body.rows(ROW_H, rows.len(), |mut row| { - let (white, f, v) = rows[row.index()]; - row.set_selected(Some(row.index()) == selected_row); - let cr = report.color(white); - let fam = &cr.families[f]; - let colour_games = cr.games.len() as u32; - let (tally, errors, games): (&Tally, &ErrorCounts, Vec) = match v { - Some(v) => { - let var = &fam.variations[v]; - (&var.tally, &var.errors, var.games.clone()) - } - None => ( - &fam.tally, - &fam.errors, - fam.variations - .iter() - .flat_map(|v| v.games.iter().copied()) - .collect(), - ), - }; - let few = tally.games < FEW_GAMES; - if both { - row.col(|ui| { - if v.is_none() { - ui.label(RichText::new(if white { "♙" } else { "♟" }).weak()) - .on_hover_text(if white { - tr("As White") - } else { - tr("As Black") - }); - } - }); - } - row.col(|ui| match v { - None => { - let open = self.open_families.contains(&(white, f)); - let glyph = if open { "▾" } else { "▸" }; - if ui - .add( - egui::Label::new(RichText::new(glyph).weak()) - .sense(Sense::click()), - ) - .clicked() - { - toggled = Some((white, f)); - } - let name = if fam.name.is_empty() { - tr("no name").to_owned() - } else { - fam.name.clone() - }; - ui.add(egui::Label::new(RichText::new(name).strong()).truncate()); - } - Some(v) => { - ui.add_space(18.0); - let name = fam.variations[v] - .opening - .and_then(|o| report.openings.get(o)) - .map(|o| { - o.variation().map_or_else(|| o.name.clone(), str::to_owned) - }); - match name { - Some(n) => { - ui.add(egui::Label::new(n).truncate()); - } - None => { - ui.label(RichText::new(tr("no deeper name")).weak()); - } - } - } - }); - if show_eco { - row.col(|ui| { - let eco = match v { - Some(v) => fam.variations[v] - .opening - .and_then(|o| report.openings.get(o)) - .map(|o| o.eco.clone()), - None => { - let mut ecos: Vec<&str> = fam - .variations - .iter() - .filter_map(|v| { - v.opening.and_then(|o| report.openings.get(o)) - }) - .map(|o| o.eco.as_str()) - .collect(); - ecos.sort_unstable(); - ecos.dedup(); - match (ecos.first(), ecos.last()) { - (Some(a), Some(b)) if a != b => Some(format!("{a}–{b}")), - (Some(a), _) => Some((*a).to_owned()), - _ => None, - } - } - }; - if let Some(e) = eco { - ui.label(RichText::new(e).weak()); - } - }); - } - if show_moves { - row.col(|ui| { - let line = match v { - Some(v) => fam.variations[v] - .opening - .and_then(|o| report.openings.get(o)) - .map(|o| o.line.clone()), - None => family_line(report, fam), - }; - if let Some(l) = line { - let tokens = table_line(&l); - let full = crate::san::show_line(&tokens.join(" ")); - let shown = fit_line(ui, &tokens, ui.available_width()); - ui.label(RichText::new(shown).weak()).on_hover_text(full); - } - }); - } - row.col(|ui| { - ui.label(tally.games.to_string()); - }); - row.col(|ui| { - let of = match v { - Some(_) => fam.tally.games, - None => colour_games, - }; - let pct = 100 * tally.games / of.max(1); - let t = RichText::new(format!("{pct}")); - ui.label(if few { t.weak() } else { t }); - }); - row.col(|ui| { - let t = RichText::new(score_text(tally)); - ui.label(if few { t.weak() } else { t }) - .on_hover_text(tally_hint(tally)); - if show_bar { - score_bar(ui, tally, white, few); - } - }); - if show_last { - row.col(|ui| { - let last = games - .iter() - .map(|&g| &report.games[g as usize]) - .max_by_key(|g| g.date_number()) - .map(|g| crate::library::display_date(&g.date)) - .unwrap_or_default(); - ui.label( - RichText::new(if last.is_empty() { - "—".to_owned() - } else { - last - }) - .weak(), - ); - }); - } - if show_errors { - row.col(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - counts_text(ui, &self.shown_counts(errors)); - }); - } - let resp = row.response(); - if resp.double_clicked() && v.is_none() { - toggled = Some((white, f)); - } else if resp.clicked() { - clicked = Some((white, f, v)); - } - }); - }); - if let Some(k) = opening_click { - self.sorts - .openings - .click(k, matches!(k, OpeningSort::Name | OpeningSort::Eco)); - } - if let Some(key) = toggled { - if !self.open_families.remove(&key) { - self.open_families.insert(key); - } - } else if let Some((white, family, variation)) = clicked { - self.focus_games = false; - self.select(Selection::Opening { - white, - family, - variation, - }); - } - } - - // ----- the errors ---------------------------------------------------------------- - - fn errors_tab(&mut self, ui: &mut Ui, settings: &mut Settings, actions: &mut Vec) { - let Some(report) = self.report.as_ref() else { - return; - }; - let moves = self.plies.div_ceil(2); - let state = self.engine_state(); - if state == EngineState::NotRun { - // The download is offered only when there is something to evaluate. - if crate::review_engine::engine().is_none() - && !report.targets_for(self.color.side()).is_empty() - { - // No offer by itself on the automatic run: told here, downloaded by hand. - ui.add_space(40.0); - ui.vertical_centered(|ui| { - ui.set_max_width(520.0); - ui.label(tr( - "No engine yet. Stockfish finds the opening errors in his games; add it to start the search.", - )); - ui.add_space(12.0); - if crate::widgets::primary(ui, tr("Download Stockfish")).clicked() { - actions.push(PrepAction::NeedEngine); - } - }); - return; - } - // The invitation (§5). - let (positions, secs) = self.estimate(); - let games: usize = self - .color - .colours() - .iter() - .map(|&w| report.color(w).games.len()) - .sum(); - let colour = match self.color { - ColorChoice::White => tr("as White"), - ColorChoice::Black => tr("as Black"), - ColorChoice::Both => tr("in both colours"), - }; - ui.add_space(40.0); - ui.vertical_centered(|ui| { - ui.set_max_width(520.0); - ui.label(trf( - "The engine has not searched for errors yet. It will check the first {n} moves of {games} games {colour} — {positions} positions, about {time}.", - &[ - ("n", &moves), - ("games", &games), - ("colour", &colour), - ("positions", &grouped(positions)), - ("time", &review::format_duration(secs)), - ], - )); - ui.add_space(12.0); - if crate::widgets::primary(ui, tr("▶ Find opening errors")).clicked() { - self.engine_asked(ui.ctx(), actions); - } - }); - return; - } - let mut ask_engine = false; - let mut inaccuracies = settings.prep.inaccuracies; - // The state line: how far the engine got; the switch of the inaccuracies. - ui.horizontal_wrapped(|ui| { - match state { - EngineState::Running => { - let mut stop = false; - if let Some(job) = &self.job { - let secs = self.secs_for(job.total.saturating_sub(job.done), job.processes); - ui.label( - RichText::new(trf( - "Checked {done} of {total} positions", - &[("done", &grouped(job.done)), ("total", &grouped(job.total))], - )) - .weak(), - ); - ui.label( - RichText::new(format!("· ≈ {}", review::format_duration(secs))).weak(), - ); - if ui.button(tr("Stop")).clicked() { - stop = true; - } - } - if stop { - self.stop_engine_by_user(actions); - } - } - EngineState::Partial { done, total } => { - let (_, secs) = self.estimate(); - ui.label( - RichText::new(trf( - "Checked {done} of {total} positions", - &[("done", &grouped(done)), ("total", &grouped(total))], - )) - .weak(), - ) - .on_hover_text(tr("The counts are of the checked positions")); - ui.label(RichText::new("·").weak()); - if ui - .link(trf( - "Continue ≈ {time}", - &[("time", &review::format_duration(secs))], - )) - .clicked() - { - ask_engine = true; - } - } - EngineState::Complete { .. } => { - if let Some(status) = self.engine_status() { - ui.label(RichText::new(status).weak()); - } - } - EngineState::NotRun => {} - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.checkbox(&mut inaccuracies, tr("Inaccuracies")) - .on_hover_text(tr( - "Show the inaccuracies (?!) with the mistakes and blunders", - )); - }); - }); - if inaccuracies != settings.prep.inaccuracies { - settings.prep.inaccuracies = inaccuracies; - self.show_inaccuracies = inaccuracies; - self.rebuild_marks(); - actions.push(PrepAction::SettingsChanged); - } - if ask_engine { - self.engine_asked(ui.ctx(), actions); - return; - } - let Some(report) = self.report.as_ref() else { - return; - }; - // The lines per colour: in the stack only (beside the board the summary has them). - if self.stacked { - for white in self.color.colours() { - let cr = report.color(white); - let with: HashSet = cr - .errors - .iter() - .filter(|e| self.visible(e.judgement)) - .map(|e| e.game) - .collect(); - let p = 100 * with.len() / cr.games.len().max(1); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.label( - RichText::new(if white { - tr("As White") - } else { - tr("As Black") - }) - .strong(), - ); - counts_text(ui, &self.shown_counts(&cr.counts)); - ui.label(RichText::new(trf("in {p} % of games", &[("p", &p)])).weak()); - }); - } - } - let serious: u32 = self - .color - .colours() - .iter() - .map(|&w| { - let c = &report.color(w).counts; - c.mistakes + c.blunders - }) - .sum(); - let inacc: u32 = self - .color - .colours() - .iter() - .map(|&w| report.color(w).counts.inaccuracies) - .sum(); - if matches!(state, EngineState::Complete { .. }) && serious == 0 { - let mut deeper = false; - ui.add_space(8.0); - ui.horizontal_wrapped(|ui| { - ui.label(trf( - "No errors in the first {n} moves ({i} inaccuracies).", - &[("n", &moves), ("i", &inacc)], - )); - if self.plies < 30 && ui.link(trf("Deeper: {n} moves", &[("n", &15)])).clicked() { - deeper = true; - } - }); - if deeper { - // As if chosen in the depth list. - self.set_plies(30, settings, ui.ctx()); - actions.push(PrepAction::SettingsChanged); - return; - } - } - ui.add_space(4.0); - self.errors_table(ui, actions); - } - - /// The repeated errors (the same position and move in several games) and the - /// errors by opening (the variations, the worst first), the inaccuracies left out - /// when they are hidden. - fn repeated_shown(&self) -> Vec<(bool, usize)> { - let Some(report) = &self.report else { - return Vec::new(); - }; - let mut list: Vec<(bool, usize)> = self - .color - .colours() - .into_iter() - .flat_map(|w| { - report - .color(w) - .repeated - .iter() - .enumerate() - .filter(|(_, r)| self.visible(r.judgement)) - .map(move |(i, _)| (w, i)) - }) - .collect(); - let sort = self.sorts.repeated; - let val = |&(w, i): &(bool, usize)| -> SortVal { - let r = &report.color(w).repeated[i]; - match sort.key { - RepeatedSort::Move => num(r.ply), - RepeatedSort::Times => num(r.games.len() as u32), - RepeatedSort::Score => score_val(&r.tally), - RepeatedSort::Opening => SortVal::Text( - r.opening - .map_or_else(String::new, |o| report.openings[o].name.clone()), - ), - } - }; - // Ties: the worst first. - list.sort_by(|a, b| { - let (ra, rb) = ( - &report.color(a.0).repeated[a.1], - &report.color(b.0).repeated[b.1], - ); - sort.apply(cmp_val(&val(a), &val(b))) - .then(judgement_weight(rb.judgement).cmp(&judgement_weight(ra.judgement))) - }); - list - } - - /// The games of a repeated error, the newest first. - fn repeated_games(&self, white: bool, index: usize) -> Vec { - let Some(report) = &self.report else { - return Vec::new(); - }; - let mut games = report.color(white).repeated[index].games.clone(); - games.sort_by_key(|&g| std::cmp::Reverse(report.games[g as usize].date_number())); - games - } - - fn err_rows(&self) -> Vec { - let Some(report) = &self.report else { - return Vec::new(); - }; - let mut rows = vec![ErrRow::RepeatedTitle]; - for (white, index) in self.repeated_shown() { - rows.push(ErrRow::Repeated { white, index }); - if self.open_repeated.contains(&(white, index)) { - for game in self.repeated_games(white, index) { - rows.push(ErrRow::RepeatedGame { white, index, game }); - } - } - } - rows.push(ErrRow::OpeningsTitle); - // (white, family, variation, weight) - let mut vars: Vec<(bool, usize, usize, u32)> = Vec::new(); - for white in self.color.colours() { - let cr = report.color(white); - for (f, fam) in cr.families.iter().enumerate() { - for (v, var) in fam.variations.iter().enumerate() { - let weight: u32 = var - .error_list - .iter() - .map(|&e| cr.errors[e as usize].judgement) - .filter(|j| self.visible(*j)) - .map(judgement_weight) - .sum(); - if weight > 0 { - vars.push((white, f, v, weight)); - } - } - } - } - let sort = self.sorts.variations; - let val = |v: &(bool, usize, usize, u32)| -> u32 { - match sort.key { - VariationSort::Games => { - report.color(v.0).families[v.1].variations[v.2].games.len() as u32 - } - VariationSort::Errors => v.3, - } - }; - vars.sort_by(|a, b| sort.apply(val(a).cmp(&val(b))).then(b.3.cmp(&a.3))); - for (white, family, variation, _) in vars { - rows.push(ErrRow::Variation { - white, - family, - variation, - }); - if self.open_variations.contains(&(white, family, variation)) { - let cr = report.color(white); - for &e in &cr.families[family].variations[variation].error_list { - if self.visible(cr.errors[e as usize].judgement) { - rows.push(ErrRow::Error { - white, - index: e as usize, - }); - } - } - } - } - rows - } - - /// The error of a repeated error in one of its games. - fn error_in(&self, white: bool, index: usize, game: u32) -> Option { - let cr = self.report.as_ref()?.color(white); - let r = cr.repeated.get(index)?; - cr.errors - .iter() - .position(|e| e.game == game && e.key == r.key && e.uci == r.uci) - } - - /// What a row of the errors tab chooses. - fn err_select(&mut self, row: ErrRow) { - self.err_cursor = Some(row); - self.focus_games = false; - let sel = match row { - ErrRow::Repeated { white, index } => Selection::Repeated { white, index }, - ErrRow::RepeatedGame { white, index, game } => { - match self.error_in(white, index, game) { - Some(e) => Selection::Error { white, index: e }, - None => return, - } - } - ErrRow::Variation { - white, - family, - variation, - } => Selection::Opening { - white, - family, - variation: Some(variation), - }, - ErrRow::Error { white, index } => Selection::Error { white, index }, - ErrRow::RepeatedTitle | ErrRow::OpeningsTitle => return, - }; - self.select(sel); - } - - /// The game a row opens, at the move after the error: (record, ply). A repeated - /// error opens its newest game. - fn err_open(&self, row: ErrRow) -> Option<(usize, usize)> { - let report = self.report.as_ref()?; - let (white, e) = match row { - ErrRow::Repeated { white, index } => { - let game = *self.repeated_games(white, index).first()?; - (white, self.error_in(white, index, game)?) - } - ErrRow::RepeatedGame { white, index, game } => { - (white, self.error_in(white, index, game)?) - } - ErrRow::Error { white, index } => (white, index), - _ => return None, - }; - let e = report.color(white).errors.get(e)?; - Some(( - report.games[e.game as usize].index as usize, - e.ply as usize + 1, - )) - } - - fn err_toggle(&mut self, row: ErrRow) { - match row { - ErrRow::Repeated { white, index } => { - if !self.open_repeated.remove(&(white, index)) { - self.open_repeated.insert((white, index)); - } - } - ErrRow::Variation { - white, - family, - variation, - } => { - let k = (white, family, variation); - if !self.open_variations.remove(&k) { - self.open_variations.insert(k); - } - } - _ => {} - } - } - - /// The errors tab as one table: the repeated errors, then by opening; a click - /// chooses, a double click (Enter) opens the game at the error. - fn errors_table(&mut self, ui: &mut Ui, actions: &mut Vec) { - let rows = self.err_rows(); - let Some(report) = self.report.as_ref() else { - return; - }; - let both = self.color == ColorChoice::Both; - let width = ui.available_width(); - let show_last = width > 640.0; - let cursor = self - .err_cursor - .and_then(|c| rows.iter().position(|r| *r == c)); - ui.style_mut().interaction.selectable_labels = false; - let mut table = TableBuilder::new(ui) - .id_salt("prep_errors") - .striped(true) - .sense(Sense::click()) - .auto_shrink([false, false]) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::remainder().at_least(180.0).clip(true)) - .column(Column::exact(110.0)) - .column(Column::exact(80.0)) - .column(Column::exact(70.0)) - .column(Column::exact(120.0).clip(true)); - if show_last { - table = table.column(Column::exact((width * 0.24).clamp(120.0, 260.0)).clip(true)); - } - if self.scroll_to_selected - && let Some(i) = cursor - { - table = table.scroll_to_row(i, None); - } - self.scroll_to_selected = false; - let mut clicked = None; - let mut toggled = None; - let mut opened = None; - let colour_icon = |ui: &mut Ui, white: bool| { - if both { - ui.label(RichText::new(if white { "♙" } else { "♟" }).weak()) - .on_hover_text(if white { - tr("As White") - } else { - tr("As Black") - }); - } - }; - let repeated_n = rows - .iter() - .filter(|r| matches!(r, ErrRow::Repeated { .. })) - .count(); - let sorts = self.sorts.clone(); - let mut sort_click: Option = None; - let openings_n = rows - .iter() - .filter(|r| matches!(r, ErrRow::Variation { .. })) - .count(); - table.body(|body| { - body.rows(ROW_H, rows.len(), |mut row| { - let r = rows[row.index()]; - row.set_selected(Some(row.index()) == cursor); - let weak = |t: &str| RichText::new(t).weak(); - match r { - ErrRow::RepeatedTitle | ErrRow::OpeningsTitle => { - let repeated = r == ErrRow::RepeatedTitle; - let (title, empty) = if repeated { - ( - tr("Repeated errors — the same position, the same move"), - repeated_n == 0, - ) - } else { - (tr("By opening"), openings_n == 0) - }; - row.col(|ui| { - ui.label(RichText::new(title).strong()); - if empty { - ui.label(weak(tr("none"))); - } - }); - // The captions of the part's columns; those it can be ordered by - // are sort buttons. - let captions: [(&str, Option); 5] = if repeated { - [ - (tr("Played"), Some(SortKeyOf::Repeated(RepeatedSort::Move))), - (tr("Better"), None), - ("×", Some(SortKeyOf::Repeated(RepeatedSort::Times))), - (tr("Score"), Some(SortKeyOf::Repeated(RepeatedSort::Score))), - ( - tr("Opening"), - Some(SortKeyOf::Repeated(RepeatedSort::Opening)), - ), - ] - } else { - [ - (tr("Played"), None), - (tr("Better"), None), - ( - tr("Games"), - Some(SortKeyOf::Variation(VariationSort::Games)), - ), - ( - tr("Errors"), - Some(SortKeyOf::Variation(VariationSort::Errors)), - ), - (tr("Date"), None), - ] - }; - for (k, (c, key)) in captions.iter().enumerate() { - if k < 4 || show_last { - row.col(|ui| match key { - Some(key) => { - let active = match key { - SortKeyOf::Repeated(k) => (sorts.repeated.key == *k) - .then_some(sorts.repeated.ascending), - SortKeyOf::Variation(k) => (sorts.variations.key == *k) - .then_some(sorts.variations.ascending), - }; - if crate::widgets::sort_header(ui, c, active).clicked() { - sort_click = Some(*key); - } - } - None => { - ui.label(weak(c)); - } - }); - } - } - } - ErrRow::Repeated { white, index } => { - let cr = report.color(white); - let rep = &cr.repeated[index]; - let g = &report.games[rep.games[0] as usize]; - let open = self.open_repeated.contains(&(white, index)); - row.col(|ui| { - if ui - .add( - egui::Label::new(weak(if open { "▾" } else { "▸" })) - .sense(Sense::click()), - ) - .clicked() - { - toggled = Some(r); - } - colour_icon(ui, white); - let before = (rep.ply as usize) - .checked_sub(1) - .map(|p| short_label(p, &g.sans[p])) - .map_or_else( - || tr("start").to_owned(), - |m| trf("after {move}", &[("move", &m)]), - ); - let side = if rep.ply.is_multiple_of(2) { - tr("White to move") - } else { - tr("Black to move") - }; - ui.add(egui::Label::new(format!("{before} · {side}")).truncate()); - }); - row.col(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.label(short_label(rep.ply as usize, &rep.san)); - pill(ui, rep.judgement) - .on_hover_text(review::judgement_name(rep.judgement)); - }); - row.col(|ui| { - ui.label(short_label(rep.ply as usize, &rep.best_san)); - }); - row.col(|ui| { - ui.label(rep.times().to_string()); - }); - row.col(|ui| { - ui.label(weak(&tally_hint(&rep.tally))); - }); - if show_last { - row.col(|ui| { - let name = rep - .opening - .and_then(|o| report.openings.get(o)) - .map(|o| format!("{} · {}", o.name, o.eco)) - .unwrap_or_default(); - ui.add(egui::Label::new(weak(&name)).truncate()) - .on_hover_text(name); - }); - } - } - ErrRow::RepeatedGame { white, index, game } => { - let g = &report.games[game as usize]; - let lr = &self.rows[game as usize]; - let _ = (white, index); - row.col(|ui| { - ui.add_space(28.0); - ui.add( - egui::Label::new(format!("{} — {}", lr.white, lr.black)).truncate(), - ); - }); - row.col(|_| {}); - row.col(|_| {}); - row.col(|_| {}); - row.col(|ui| { - ui.label(result_text(lr.result)); - }); - if show_last { - row.col(|ui| { - ui.label(weak(&crate::library::display_date(&g.date))); - }); - } - } - ErrRow::Variation { - white, - family, - variation, - } => { - let cr = report.color(white); - let var = &cr.families[family].variations[variation]; - let open = self.open_variations.contains(&(white, family, variation)); - let mut counts = ErrorCounts::default(); - for &e in &var.error_list { - counts.add(cr.errors[e as usize].judgement); - } - row.col(|ui| { - if ui - .add( - egui::Label::new(weak(if open { "▾" } else { "▸" })) - .sense(Sense::click()), - ) - .clicked() - { - toggled = Some(r); - } - colour_icon(ui, white); - let name = var - .opening - .and_then(|o| report.openings.get(o)) - .map_or_else( - || tr("no name").to_owned(), - |o| format!("{} · {}", o.name, o.eco), - ); - ui.add(egui::Label::new(name.as_str()).truncate()) - .on_hover_text(name); - }); - row.col(|_| {}); - row.col(|_| {}); - row.col(|ui| { - ui.label(weak(&var.games.len().to_string())); - }); - row.col(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - counts_text(ui, &self.shown_counts(&counts)); - }); - if show_last { - row.col(|_| {}); - } - } - ErrRow::Error { white, index } => { - let e = &report.color(white).errors[index]; - let g = &report.games[e.game as usize]; - let lr = &self.rows[e.game as usize]; - row.col(|ui| { - ui.add_space(28.0); - ui.add( - egui::Label::new(format!("{} — {}", lr.white, lr.black)).truncate(), - ); - }); - row.col(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - ui.label(short_label(e.ply as usize, &e.san)); - pill(ui, e.judgement).on_hover_text(format!( - "{} · {} → {}", - review::judgement_name(e.judgement), - e.before.format(), - e.after.format() - )); - }); - row.col(|ui| { - ui.label(short_label(e.ply as usize, &e.best_san)); - }); - row.col(|_| {}); - row.col(|ui| { - ui.label(result_text(lr.result)); - }); - if show_last { - row.col(|ui| { - ui.label(weak(&crate::library::display_date(&g.date))); - }); - } - } - } - if !r.is_title() { - let resp = row.response(); - if resp.double_clicked() { - match r { - ErrRow::Repeated { .. } | ErrRow::Variation { .. } => toggled = Some(r), - _ => opened = Some(r), - } - clicked = Some(r); - } else if resp.clicked() { - clicked = Some(r); - } - } - }); - }); - match sort_click { - Some(SortKeyOf::Repeated(k)) => { - // Indices into the lists do not change: the rows only reorder. - self.sorts - .repeated - .click(k, matches!(k, RepeatedSort::Move | RepeatedSort::Opening)) - } - Some(SortKeyOf::Variation(k)) => self.sorts.variations.click(k, false), - None => {} - } - if let Some(r) = toggled { - self.err_toggle(r); - } - if let Some(r) = clicked { - self.err_select(r); - } - if let Some((index, ply)) = opened.and_then(|r| self.err_open(r)) { - actions.push(PrepAction::OpenGame { - path: self.path.clone(), - index, - ply, - }); - } - } - - /// The keyboard in the errors tab: ↑/↓ the rows, →/← open and close, Enter the game. - #[allow(clippy::too_many_arguments)] - fn errors_keys( - &mut self, - up: bool, - down: bool, - left: bool, - right: bool, - enter: bool, - space: bool, - home: bool, - end: bool, - actions: &mut Vec, - ) { - let rows: Vec = self - .err_rows() - .into_iter() - .filter(|r| !r.is_title()) - .collect(); - if rows.is_empty() { - return; - } - let at = self - .err_cursor - .and_then(|c| rows.iter().position(|r| *r == c)); - let Some(at) = at else { - if up || down || home || end { - self.err_select(rows[0]); - self.scroll_to_selected = true; - } - return; - }; - let r = rows[at]; - let next = if down { - Some((at + 1).min(rows.len() - 1)) - } else if up { - Some(at.saturating_sub(1)) - } else if home { - Some(0) - } else if end { - Some(rows.len() - 1) - } else { - None - }; - if let Some(i) = next { - self.err_select(rows[i]); - self.scroll_to_selected = true; - return; - } - let open = match r { - ErrRow::Repeated { white, index } => Some(self.open_repeated.contains(&(white, index))), - ErrRow::Variation { - white, - family, - variation, - } => Some(self.open_variations.contains(&(white, family, variation))), - _ => None, - }; - if (right && open == Some(false)) - || (left && open == Some(true)) - || (space && open.is_some()) - { - self.err_toggle(r); - } else if left { - // A game or an error row: to the row it is under. - if let Some(parent) = rows[..at] - .iter() - .rev() - .find(|p| matches!(p, ErrRow::Repeated { .. } | ErrRow::Variation { .. })) - { - self.err_select(*parent); - self.scroll_to_selected = true; - } - } else if enter { - match self.err_open(r) { - Some((index, ply)) => actions.push(PrepAction::OpenGame { - path: self.path.clone(), - index, - ply, - }), - None => { - self.focus_games = true; - self.games_cursor = Some(0); - } - } - } - } - - // ----- the games list ------------------------------------------------------------ - - fn games_list(&mut self, ui: &mut Ui, actions: &mut Vec) { - let Some(report) = self.report.as_ref() else { - return; - }; - let list = self.games_of(); - let title = match &self.selection { - Selection::None => trf("Games · {n}", &[("n", &list.len())]), - Selection::Node { white, node } => { - let n = &report.color(*white).tree.nodes[*node as usize]; - match n.ply { - 0 => trf("Games · {n}", &[("n", &list.len())]), - p => trf( - "Games · after {move} · {n}", - &[ - ("move", &short_label(usize::from(p) - 1, &n.san)), - ("n", &list.len()), - ], - ), - } - } - Selection::Opening { - white, - family, - variation, - } => { - let fam = &report.color(*white).families[*family]; - let name = match variation { - Some(v) => fam.variations[*v] - .opening - .and_then(|o| report.openings.get(o)) - .map(|o| o.name.clone()) - .unwrap_or_else(|| fam.name.clone()), - None => fam.name.clone(), - }; - trf( - "Games · {opening} · {n}", - &[("opening", &name), ("n", &list.len())], - ) - } - Selection::Repeated { white, index } => { - let r = &report.color(*white).repeated[*index]; - trf( - "Games · {move} · {n}", - &[ - ( - "move", - &format!( - "{} {}", - short_label(r.ply as usize, &r.san), - review::judgement_symbol(r.judgement) - ), - ), - ("n", &list.len()), - ], - ) - } - Selection::Error { white, index } => { - let e = &report.color(*white).errors[*index]; - trf( - "Games · {move} · {n}", - &[ - ( - "move", - &format!( - "{} {}", - short_label(e.ply as usize, &e.san), - review::judgement_symbol(e.judgement) - ), - ), - ("n", &list.len()), - ], - ) - } - }; - let mut clear = false; - ui.horizontal(|ui| { - ui.label(RichText::new(title).strong()); - if self.selection != Selection::None - && crate::widgets::small_close_button(ui) - .on_hover_text(tr("All games")) - .clicked() - { - clear = true; - } - }); - if clear { - self.select(Selection::None); - return; - } - if list.is_empty() { - return; - } - let width = ui.available_width(); - // The names first (at least 110 each): the event, «Then», the ratings (they go - // into the name cell), the errors and the date give way in turn. - let mut show_event = true; - let mut show_then = true; - let mut show_elo = true; - let mut show_errors = report.evaluated(); - let mut show_date = true; - let gap = ui.spacing().item_spacing.x; - let player_w_of = |event: bool, then: bool, elo: bool, errors: bool, date: bool| -> f32 { - let columns = 3 - + 2 * usize::from(elo) - + usize::from(date) - + usize::from(then) - + usize::from(event) - + usize::from(errors); - let fixed = 44.0 - + if elo { 88.0 } else { 0.0 } - + if date { 84.0 } else { 0.0 } - + if errors { 80.0 } else { 0.0 } - + match (then, event) { - (true, true) => 150.0, - (true, false) => 100.0, - _ => 0.0, - } - + if event { 100.0 } else { 0.0 } - + gap * columns as f32; - (width - fixed) / 2.0 - }; - for drop in 0..5 { - if player_w_of(show_event, show_then, show_elo, show_errors, show_date) >= 110.0 { - break; - } - match drop { - 0 => show_event = false, - 1 => show_then = false, - 2 => show_elo = false, - 3 => show_errors = false, - _ => show_date = false, - } - } - let player_w = - player_w_of(show_event, show_then, show_elo, show_errors, show_date).clamp(60.0, 170.0); - let plies: HashMap = list.iter().map(|&g| (g, self.game_ply(g))).collect(); - ui.style_mut().interaction.selectable_labels = false; - let mut table = TableBuilder::new(ui) - .id_salt("prep_games_table") - .striped(true) - .sense(Sense::click()) - .auto_shrink([false, false]) - .cell_layout(egui::Layout::left_to_right(egui::Align::Center)) - .column(Column::exact(player_w).clip(true)); - if show_elo { - table = table.column(Column::exact(44.0)); - } - table = table.column(Column::exact(player_w).clip(true)); - if show_elo { - table = table.column(Column::exact(44.0)); - } - table = table.column(Column::exact(44.0)); - if show_date { - table = table.column(Column::exact(84.0)); - } - if show_then && show_event { - table = table.column(Column::exact(150.0).clip(true)); - } else if show_then { - table = table.column(Column::remainder().at_least(100.0).clip(true)); - } - if show_event { - table = table.column(Column::remainder().at_least(100.0).clip(true)); - } - if show_errors { - table = table.column(Column::exact(80.0).clip(true)); - } - if self.scroll_to_selected - && let Some(c) = self.games_cursor - { - table = table.scroll_to_row(c, None); - self.scroll_to_selected = false; - } - let mut hovered = None; - let mut clicked = None; - let mut opened = None; - let mut game_click = None; - let sort = self.sorts.games; - let player_names: HashSet<&str> = self.names.iter().map(String::as_str).collect(); - table - .header(ROW_H, |mut h| { - let c = &mut game_click; - sort_col(&mut h, tr("White"), "", GameSort::White, sort, c); - if show_elo { - sort_col(&mut h, "Elo", "", GameSort::WhiteElo, sort, c); - } - sort_col(&mut h, tr("Black"), "", GameSort::Black, sort, c); - if show_elo { - sort_col(&mut h, "Elo", "", GameSort::BlackElo, sort, c); - } - sort_col(&mut h, tr("Res."), "", GameSort::Result, sort, c); - if show_date { - sort_col(&mut h, tr("Date"), "", GameSort::Date, sort, c); - } - if show_then { - sort_col( - &mut h, - tr("Then"), - tr("How the game went on from this position"), - GameSort::Then, - sort, - c, - ); - } - if show_event { - sort_col(&mut h, tr("Event"), "", GameSort::Event, sort, c); - } - if show_errors { - sort_col( - &mut h, - tr("Errors"), - tr("His marked moves in the opening of this game"), - GameSort::Errors, - sort, - c, - ); - } - }) - .body(|body| { - body.rows(ROW_H, list.len(), |mut row| { - let gi = list[row.index()]; - let g = &report.games[gi as usize]; - let r = &self.rows[gi as usize]; - row.set_selected(self.games_cursor == Some(row.index())); - let name = |ui: &mut Ui, n: &str| { - let t = RichText::new(n); - ui.add( - egui::Label::new(if player_names.contains(n) { - t.strong() - } else { - t - }) - .truncate(), - ); - }; - let elo = |e: u16| if e > 0 { e.to_string() } else { String::new() }; - let ply = plies.get(&gi).copied().unwrap_or(0); - // Without their column the ratings go after the names, weak. - let name = |ui: &mut Ui, n: &str, e: u16| { - name(ui, n); - if !show_elo && e > 0 { - ui.label(RichText::new(e.to_string()).weak().small()); - } - }; - row.col(|ui| name(ui, &r.white, r.white_elo)); - if show_elo { - row.col(|ui| { - ui.label(RichText::new(elo(r.white_elo)).weak()); - }); - } - row.col(|ui| name(ui, &r.black, r.black_elo)); - if show_elo { - row.col(|ui| { - ui.label(RichText::new(elo(r.black_elo)).weak()); - }); - } - row.col(|ui| { - ui.label(result_text(r.result)); - }); - if show_date { - row.col(|ui| { - ui.label(RichText::new(crate::library::display_date(&g.date)).weak()); - }); - } - if show_then { - row.col(|ui| { - let then: Vec = - g.sans.iter().skip(ply).take(3).cloned().collect(); - let mut text = String::new(); - for (k, san) in then.iter().enumerate() { - let p = ply + k; - if k == 0 || p.is_multiple_of(2) { - text.push_str(&short_label(p, san)); - } else { - text.push_str(san); - } - text.push(' '); - } - ui.add( - egui::Label::new(crate::san::show_line(text.trim_end())).truncate(), - ); - }); - } - if show_event { - row.col(|ui| { - ui.add( - egui::Label::new(RichText::new(&r.event).italics().weak()) - .truncate(), - ); - }); - } - if show_errors { - row.col(|ui| { - ui.spacing_mut().item_spacing.x = 3.0; - let cr = report.color(g.white); - for e in cr - .errors - .iter() - .filter(|e| e.game == gi && self.visible(e.judgement)) - { - let number = e.ply as usize / 2 + 1; - ui.label(RichText::new(format!("{number}.")).small()); - pill(ui, e.judgement).on_hover_text(format!( - "{} {} — {}", - short_label(e.ply as usize, &e.san), - review::judgement_name(e.judgement), - trf( - "better {best}", - &[("best", &crate::san::show(&e.best_san))] - ) - )); - } - }); - } - let resp = row - .response() - .on_hover_text(tr("Double click: open this game at this position")); - if resp.hovered() { - hovered = Some(gi); - } - if resp.double_clicked() { - opened = Some(gi); - } else if resp.clicked() { - clicked = Some(row.index()); - } - }); - }); - if let Some(k) = game_click { - let names = matches!( - k, - GameSort::White - | GameSort::Black - | GameSort::Result - | GameSort::Then - | GameSort::Event - ); - self.sorts.games.click(k, names); - // The keyboard's row is a place in the list: it goes back to the top. - self.games_cursor = None; - } - // The game's move from the shown position, as an arrow. - if let Some(gi) = hovered - && let Some(s) = &self.shown_pos - && s.ply + 1 == s.positions.len() - { - let g = &report.games[gi as usize]; - let ply = plies.get(&gi).copied().unwrap_or(0); - if let Some(m) = g - .ucis - .get(ply) - .and_then(|u| u.parse::().ok()) - .and_then(|u| u.to_move(&s.positions[s.ply]).ok()) - { - self.hover_arrow = m.from().map(|f| (f, crate::board::ui_target(&m))); - } - } - if let Some(i) = clicked { - self.games_cursor = Some(i); - self.focus_games = true; - } - if let Some(gi) = opened { - actions.push(PrepAction::OpenGame { - path: self.path.clone(), - index: report.games[gi as usize].index as usize, - ply: self.open_ply(gi), - }); - } - } - - // ----- the keyboard -------------------------------------------------------------- - - fn keyboard( - &mut self, - ctx: &egui::Context, - _settings: &Settings, - actions: &mut Vec, - ) { - let ctrl = |k| KeyboardShortcut::new(Modifiers::COMMAND, k); - let alt = |k| KeyboardShortcut::new(Modifiers::ALT, k); - if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Num1))) { - self.tab = Tab::Repertoire; - } - if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Num2))) { - self.tab = Tab::Openings; - } - if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::Num3))) { - self.tab = Tab::Errors; - } - if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num1))) { - self.set_color(ColorChoice::White); - } - if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num2))) { - self.set_color(ColorChoice::Black); - } - if ctx.input_mut(|i| i.consume_shortcut(&alt(Key::Num3))) { - self.set_color(ColorChoice::Both); - } - if ctx.input_mut(|i| i.consume_shortcut(&ctrl(Key::W))) { - actions.push(PrepAction::Back); - } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::F)) { - let base = self - .shown_pos - .as_ref() - .map_or(self.color != ColorChoice::Black, |s| s.white); - self.flipped = Some(!self.board_white() == base); - } - if ctx.input_mut(|i| i.consume_key(Modifiers::SHIFT, Key::A)) { - if self.job.is_some() { - self.stop_engine_by_user(actions); - } else if self.report.is_some() { - self.engine_asked(ctx, actions); - } - } - if ctx.input_mut(|i| { - i.consume_shortcut(&KeyboardShortcut::new( - Modifiers::COMMAND | Modifiers::SHIFT, - Key::F, - )) - }) && let Some(s) = &self.shown_pos - { - let mut p = Chess::default(); - let moves: Vec = s.ucis[..s.ply] - .iter() - .filter_map(|u| { - let m = u.parse::().ok()?.to_move(&p).ok()?; - p.play_unchecked(m); - Some(m) - }) - .collect(); - actions.push(PrepAction::FindPosition( - self.path.clone(), - Chess::default(), - moves, - !self.board_white(), - )); - } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { - if self.board_popup { - self.board_popup = false; - } else if self.selection != Selection::None { - self.select(Selection::None); - } else { - actions.push(PrepAction::Back); - } - } - if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) { - self.focus_games = !self.focus_games; - if self.focus_games && self.games_cursor.is_none() { - self.games_cursor = Some(0); - } - } - let (up, down, left, right, enter, space, home, end) = ctx.input_mut(|i| { - ( - i.consume_key(Modifiers::NONE, Key::ArrowUp), - i.consume_key(Modifiers::NONE, Key::ArrowDown), - i.consume_key(Modifiers::NONE, Key::ArrowLeft), - i.consume_key(Modifiers::NONE, Key::ArrowRight), - i.consume_key(Modifiers::NONE, Key::Enter), - i.consume_key(Modifiers::NONE, Key::Space), - i.consume_key(Modifiers::NONE, Key::Home), - i.consume_key(Modifiers::NONE, Key::End), - ) - }); - if !(up || down || left || right || enter || space || home || end) { - return; - } - if self.focus_games { - let list = self.games_of(); - if list.is_empty() { - return; - } - let cur = self.games_cursor.unwrap_or(0); - let next = if up { - cur.saturating_sub(1) - } else if down { - (cur + 1).min(list.len() - 1) - } else if home { - 0 - } else if end { - list.len() - 1 - } else { - cur - }; - if next != cur || self.games_cursor.is_none() { - self.games_cursor = Some(next); - self.scroll_to_selected = true; - } - if enter && let Some(r) = &self.report { - actions.push(PrepAction::OpenGame { - path: self.path.clone(), - index: r.games[list[next] as usize].index as usize, - ply: self.open_ply(list[next]), - }); - } - return; - } - match self.tab { - Tab::Repertoire => self.tree_keys(up, down, left, right, enter, space, home, end), - Tab::Openings => self.openings_keys(up, down, left, right, enter, space, home, end), - Tab::Errors => { - self.errors_keys(up, down, left, right, enter, space, home, end, actions) - } - } - } - - #[allow(clippy::too_many_arguments)] - fn tree_keys( - &mut self, - up: bool, - down: bool, - left: bool, - right: bool, - enter: bool, - space: bool, - home: bool, - end: bool, - ) { - let rows = self.tree_rows(); - if rows.is_empty() { - return; - } - let at = rows.iter().position(|r| match (r, &self.selection) { - ( - TreeRow::Node { white, node, .. }, - Selection::Node { - white: sw, - node: sn, - }, - ) => white == sw && node == sn, - _ => false, - }); - let go = |screen: &mut Self, i: usize| { - if let Some(TreeRow::Node { white, node, .. }) = rows.get(i).copied() { - screen.select(Selection::Node { white, node }); - screen.scroll_to_selected = true; - } - }; - let Some(at) = at else { - if up || down || home || end || right { - go(self, 0); - } - return; - }; - let Some(TreeRow::Node { white, node, .. }) = rows.get(at).copied() else { - return; - }; - let has_children = self - .report - .as_ref() - .is_some_and(|r| !r.color(white).tree.nodes[node as usize].children.is_empty()); - let open = self.expanded.contains(&(white, node)); - if down { - let mut next = at + 1; - while next < rows.len() && matches!(rows[next], TreeRow::Others { .. }) { - next += 1; - } - if next < rows.len() { - go(self, next); - } - } else if up { - let mut prev = at; - while prev > 0 { - prev -= 1; - if matches!(rows[prev], TreeRow::Node { .. }) { - go(self, prev); - break; - } - } - } else if home { - go(self, 0); - } else if end { - let last = rows - .iter() - .rposition(|r| matches!(r, TreeRow::Node { .. })) - .unwrap_or(0); - go(self, last); - } else if right { - if has_children && !open { - self.expanded.insert((white, node)); - } else if has_children { - go(self, at + 1); - } - } else if left { - if open { - self.expanded.remove(&(white, node)); - } else if let Some(p) = self - .report - .as_ref() - .and_then(|r| r.color(white).tree.nodes[node as usize].parent) - { - self.select(Selection::Node { white, node: p }); - self.scroll_to_selected = true; - } - } else if space { - if has_children && !self.expanded.remove(&(white, node)) { - self.expanded.insert((white, node)); - } - } else if enter { - self.focus_games = true; - self.games_cursor = Some(0); - } - } - - #[allow(clippy::too_many_arguments)] - fn openings_keys( - &mut self, - up: bool, - down: bool, - left: bool, - right: bool, - enter: bool, - space: bool, - home: bool, - end: bool, - ) { - let rows = self.opening_rows(); - if rows.is_empty() { - return; - } - let at = rows.iter().position(|&(w, f, v)| { - self.selection - == Selection::Opening { - white: w, - family: f, - variation: v, - } - }); - let go = |screen: &mut Self, i: usize| { - if let Some(&(white, family, variation)) = rows.get(i) { - screen.select(Selection::Opening { - white, - family, - variation, - }); - screen.scroll_to_selected = true; - } - }; - let Some(at) = at else { - if up || down || home || end || right { - go(self, 0); - } - return; - }; - let (white, f, v) = rows[at]; - if down { - go(self, (at + 1).min(rows.len() - 1)); - } else if up { - go(self, at.saturating_sub(1)); - } else if home { - go(self, 0); - } else if end { - go(self, rows.len() - 1); - } else if right || space { - if v.is_none() && !self.open_families.remove(&(white, f)) { - self.open_families.insert((white, f)); - } - } else if left { - if v.is_some() { - go( - self, - rows.iter() - .position(|&(w, ff, vv)| w == white && ff == f && vv.is_none()) - .unwrap_or(at), - ); - } else { - self.open_families.remove(&(white, f)); - } - } else if enter { - self.focus_games = true; - self.games_cursor = Some(0); - } - } -} - -/// The arrows of an error: the move played in the colour of its sign, the better move -/// in green. -fn error_arrows(pos: &Chess, played: &str, best: Option<&str>, j: Judgement) -> Vec { - let mut out = Vec::new(); - let to_arrow = |u: &str, color: Color32| -> Option { - let m = u.parse::().ok()?.to_move(pos).ok()?; - Some(Arrow { - from: m.from()?, - to: crate::board::ui_target(&m), - color, - weight: 1.0, - }) - }; - if let Some(a) = to_arrow(played, review::judgement_color(j).gamma_multiply(0.85)) { - out.push(a); - } - if let Some(a) = best.and_then(|b| { - to_arrow( - b, - crate::board::shape_preview_color(chess_core::ShapeColor::Green), - ) - }) { - out.push(a); - } - out -} - -/// «6…Nb6 ? — better 6…e6 · 0.0 → −1.2». -fn error_note(e: &prep::OpeningError) -> String { - let played = format!( - "{} {}", - short_label(e.ply as usize, &e.san), - review::judgement_symbol(e.judgement) - ); - trf( - "{played} — better {best} · {before} → {after}", - &[ - ("played", &played), - ("best", &short_label(e.ply as usize, &e.best_san)), - ("before", &e.before.format()), - ("after", &e.after.format()), - ], - ) -} - -/// The table's line to the family's own position: the shallowest position of the -/// family's games whose name is of the family ("1. e4 c5" for the Sicilian, whatever -/// the variations); the shortest variation's line when there is none. -fn family_line(report: &PrepReport, fam: &prep::Family) -> Option { - let mut best: Option<&'static prep::Opening> = None; - for v in &fam.variations { - for &gi in &v.games { - let g = &report.games[gi as usize]; - for &k in &g.keys { - let Some(o) = prep::openings::by_position(k).map(prep::openings::get) else { - continue; - }; - if o.family() == fam.name && best.is_none_or(|b| o.plies < b.plies) { - best = Some(o); - } - } - } - } - best.map(|o| o.line.clone()).or_else(|| { - fam.variations - .iter() - .filter_map(|v| v.opening.and_then(|o| report.openings.get(o))) - .min_by_key(|o| o.plies) - .map(|o| o.line.clone()) - }) -} - -/// The ply of the first position of a game's line named with `family`. -fn family_ply(g: &GameInfo, family: &str) -> Option { - (0..g.keys.len()).find(|&i| { - prep::openings::by_position(g.keys[i]) - .map(prep::openings::get) - .is_some_and(|o| o.family() == family) - }) -} - -/// A header cell: the title in bold, a tooltip when there is one. -fn head_col(h: &mut egui_extras::TableRow<'_, '_>, text: &str, hint: &str) { - h.col(|ui| { - let l = ui.label(RichText::new(text).strong()); - if !hint.is_empty() { - l.on_hover_text(hint); - } - }); -} - -fn result_text(r: &str) -> &str { - if r == "1/2-1/2" { "½-½" } else { r } -} - -fn text_width(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { - let font = style.resolve(ui.style()); - ui.painter() - .layout_no_wrap(text.to_owned(), font, Color32::WHITE) - .size() - .x -} - -#[cfg(test)] -mod tests { - use super::*; - - fn c(id: u32, name: &str) -> Candidate { - Candidate { - id, - name: name.to_owned(), - games: 1, - } - } - - #[test] - fn candidates_split_into_whole_words_and_similar_names() { - let list = vec![ - c(1, "Вафин Радель"), - c(2, "Vafin, Radel"), - c(3, "Вафина Раяна"), - c(4, "Вафин Р."), - ]; - let (exact, similar) = split_candidates("Вафин", list.clone()); - assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![1, 4]); - assert_eq!(similar.iter().map(|c| c.id).collect::>(), vec![2, 3]); - // An initial matches the beginning of a word; the full stop is ignored. - let (exact, _) = split_candidates("Вафин Р.", list.clone()); - assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![1, 4]); - let (exact, similar) = split_candidates("вафин радель", list.clone()); - assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![1]); - assert_eq!(similar.len(), 3); - // Commas and case do not matter. - let (exact, _) = split_candidates("radel vafin", list); - assert_eq!(exact.iter().map(|c| c.id).collect::>(), vec![2]); - } - - #[test] - fn a_header_click_sorts_then_turns_the_order_round() { - let mut s = PrepSorts::default().games; - assert_eq!( - (s.key, s.ascending), - (GameSort::Date, false), - "newest first" - ); - s.click(GameSort::Date, false); - assert!(s.ascending, "the same column again: the other way"); - s.click(GameSort::White, true); - assert_eq!( - (s.key, s.ascending), - (GameSort::White, true), - "a name column starts A–Z" - ); - assert_eq!(s.apply(std::cmp::Ordering::Less), std::cmp::Ordering::Less); - s.click(GameSort::White, true); - assert_eq!( - s.apply(std::cmp::Ordering::Less), - std::cmp::Ordering::Greater - ); - assert_eq!(cmp_val(&num(2), &num(10)), std::cmp::Ordering::Less); - assert_eq!( - cmp_val(&SortVal::Text("b".into()), &SortVal::Text("a".into())), - std::cmp::Ordering::Greater - ); - // Kept in the settings as they are. - let json = serde_json::to_string(&PrepSorts::default()).unwrap(); - assert_eq!( - serde_json::from_str::(&json).unwrap(), - PrepSorts::default() - ); - } - - #[test] - fn labels_and_lines() { - assert_eq!(short_label(0, "e4"), "1.e4"); - assert_eq!(short_label(1, "c5"), "1…c5"); - assert_eq!(short_label(4, "Bb5"), "3.Bb5"); - let sans: Vec = ["e4", "c5", "Nf3"] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - assert_eq!(line_text(&sans), "1.e4 c5 2.Nf3"); - assert_eq!( - table_line("1. e4 c5 2. Nf3 Nc6 3. Bb5"), - vec!["1.e4", "c5", "2.Nf3", "Nc6", "3.Bb5"] - ); - assert_eq!(table_line("1... e5"), vec!["1…e5"]); - let ucis: Vec = ["e2e4", "c7c5", "g1f3"] - .iter() - .map(|s| (*s).to_owned()) - .collect(); - assert_eq!(replay(&ucis).len(), 4); - assert_eq!(replay(&["zz".to_owned()]).len(), 1); - } - - #[test] - fn the_period_of_the_games() { - use prep::Outcome; - let game = |date: &str| GameInfo { - index: 0, - white: true, - opponent: String::new(), - opponent_elo: 0, - date: date.to_owned(), - outcome: Outcome::Unknown, - ucis: Vec::new(), - sans: Vec::new(), - keys: Vec::new(), - opening: None, - named: None, - book: None, - }; - assert_eq!( - period(&[game("2026.10.18"), game("2026.01.03"), game("")]), - "01.2026 – 10.2026" - ); - assert_eq!(period(&[game("2026.10.18")]), "10.2026"); - assert_eq!(period(&[game("")]), ""); - } - - #[test] - fn error_count_parts_skip_zeroes_and_keep_the_order() { - let counts = ErrorCounts { - inaccuracies: 30, - mistakes: 0, - blunders: 13, - }; - assert_eq!( - count_parts(&counts), - vec![(30, Judgement::Inaccuracy), (13, Judgement::Blunder)] - ); - assert!(count_parts(&ErrorCounts::default()).is_empty()); - } -} diff --git a/apps/desktop/src/reference.rs b/apps/desktop/src/reference.rs index 84326ca..fd57fda 100644 --- a/apps/desktop/src/reference.rs +++ b/apps/desktop/src/reference.rs @@ -15,7 +15,7 @@ use std::sync::atomic::AtomicBool; use chess_core::{Game, NodeId}; use chess_import::Database; -use chess_import::position::{Match, MoveStat, PositionOutcome, PositionQuery, Tally, theory_end}; +use chess_import::position::{Match, MoveStat, PositionOutcome, PositionQuery, Tally}; use egui::{RichText, Sense, Ui, vec2}; use egui_extras::{Column, TableBuilder}; use shakmaty::uci::UciMove; @@ -147,6 +147,8 @@ const MOVES_WITH_GAMES: usize = 12; const PGN_TREE_MATCHES: usize = 5_000; /// Results bigger than the cache kept apart (the start position, 1.e4). const BIG_KEPT: usize = 2; +/// Plies of the theory checked one by one before it is found by halving. +const BOOK_LINEAR: usize = 12; /// Sort of the games table. #[derive(Clone, Copy, Default, PartialEq, Eq)] @@ -652,12 +654,62 @@ fn book_end( ) }; // The first plies one by one (the opening index answers them at once), then by - // doubling and halving (`theory_end`). `from`: the plies before it are known - // already (the game grew past a theory that reached its end). - let end = theory_end(nodes.len(), from, known)?; + // doubling and halving: a position is nearly always in the database when a later + // one of the same line is. + // `from`: the plies before it are known already (the game grew past a theory that + // reached its end). + let total = nodes.len(); + let from = from.min(total); + let linear_end = if from > 0 { + from + } else { + total.min(BOOK_LINEAR) + }; + let mut last_known: Option = from.checked_sub(1); + let mut first_unknown = None; + for ply in from..linear_end { + if known(ply)? { + last_known = Some(ply); + } else { + first_unknown = Some(ply); + break; + } + } + if first_unknown.is_none() && total > linear_end { + let mut lo = linear_end - 1; + let mut step = 2; + let mut hi = total; + while lo + step < total { + if known(lo + step)? { + lo += step; + step *= 2; + } else { + hi = lo + step; + break; + } + } + if hi == total && lo + 1 < total { + // Past the last doubling: the end of the line itself. + if known(total - 1)? { + lo = total - 1; + } + } + while hi - lo > 1 { + let mid = (lo + hi) / 2; + if known(mid)? { + lo = mid; + } else { + hi = mid; + } + } + last_known = Some(lo); + if hi < total { + first_unknown = Some(hi); + } + } Some(BookEnd { - last: end.last_known.map(|p| nodes[p]), - to_the_end: nodes.len() > 1 && end.first_unknown.is_none(), + last: last_known.map(|p| nodes[p]), + to_the_end: total > 1 && first_unknown.is_none(), copies, }) } diff --git a/apps/desktop/src/repertoire_ui.rs b/apps/desktop/src/repertoire_ui.rs deleted file mode 100644 index ff6dac8..0000000 --- a/apps/desktop/src/repertoire_ui.rs +++ /dev/null @@ -1,3349 +0,0 @@ -//! 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, AtomicU64, Ordering}, - mpsc::{self, Receiver, Sender}, -}; -use std::time::Duration; - -use chess_core::shakmaty::{Chess, Color, Position, Square}; -use chess_core::{Game, NodeId, PgnDatabase, Severity}; -use egui::{Color32, Key, Modifiers, RichText, Ui, vec2}; -use trainer::repertoire::{ - LearningData, LearningItemKey, LearningSide, LearningStore, LearningStoreData, Library, - LibraryStore, MergeReport, RepertoireId, ResetImpactProjection, SrsSettings, StatsScope, - StoreError, active_learning_keys, aggregate_scope, fen4, reset_impact, -}; -use web_time::Instant; - -use crate::board::BoardState; -use crate::i18n::{tr, trf}; -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 { - id: RepertoireId, - name: String, - report: MergeReport, - }, -} - -const CARD_H: f32 = 168.0; -const BUTTON_ROW_H: f32 = 30.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; -/// The bar in the «Passed» column, left of «A/Y». -const MINI_BAR_W: f32 = 44.0; -/// The bar of a narrow panel (under `NARROW_TABLE`) whose name would keep under -/// `NAME_WANTED`. -const MINI_BAR_NARROW: f32 = 28.0; -const NARROW_TABLE: f32 = 420.0 - 16.0; -const NAME_WANTED: f32 = 60.0; -/// The room kept for the number of «Passed». -const NUMBER_SAMPLE: &str = "00/000"; -const MINI_BAR_GAP: f32 = 6.0; -/// The name keeps up to this much; only it is ever cut, down to `NAME_FLOOR`. -const NAME_LEAST: f32 = 120.0; -const NAME_FLOOR: f32 = 30.0; -/// Space from «Today» to the «Passed» bar, the columns' own gap included: the bar -/// never reads as part of «Today». -const PASSED_GAP: f32 = 16.0; -/// The fixed columns besides «Today» and «Passed»: the colour and `⋯`. -const KING_W: f32 = 22.0; -const MENU_W: f32 = 26.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, - /// The position a session starts from (S0 shows it, not the library's preview). - initial: Chess, - last_move: Option<(Square, Square)>, - has_moves: bool, -} - -/// 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)>, -} - -impl RowStats { - /// Moves met in training at least once: learning and learned. - fn passed(&self) -> usize { - self.learning + self.learnt - } - - fn new_today(&self) -> usize { - self.unseen.min(NEW_PER_SESSION) - } -} - -#[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, - 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, -} - -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, - preview: Option, - name: String, - side: LearningSide, - 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 MenuItem { - Train, - ReviewAll, - Lines, - Rename, - SwitchColor, - AddPgn, - Export, - Reset, - Delete, -} - -enum Event { - 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, - Result<(ResetImpactProjection, BTreeSet), String>, - ), - ResetDone(u64, Result), -} - -struct AddFromGame { - source: Game, - at: NodeId, - selected: Option, - name: String, - side: LearningSide, -} - -pub struct RepertoireUi { - library_store: LibraryStore, - learning_store: LearningStore, - library: Library, - learning: LearningStoreData, - library_error: Option, - learning_error: Option, - selected: Option, - index: HashMap, - 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>, - 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, - return_to_game: Option, - add: Option, - board: BoardState, - tx: Sender, - rx: Receiver, - initial_selection_pending: bool, - 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(); - 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 { - let (library, library_error) = match load_library(&library_store) { - Ok(data) => (data, None), - Err(error) => (Library::default(), Some(error)), - }; - let (learning, learning_error) = match learning_store.load() { - Ok(data) => (data, None), - Err(error) => (LearningStoreData::default(), Some(error.to_string())), - }; - let (tx, rx) = mpsc::channel(); - let mut this = Self { - library_store, - learning_store, - library, - learning, - library_error, - learning_error, - selected: None, - index: HashMap::new(), - index_job: 0, - stats: HashMap::new(), - stats_key: None, - stats_shown: 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, - return_to_game: None, - add: None, - board: BoardState::default(), - tx, - rx, - initial_selection_pending: true, - debug_start: None, - debug_pending_moves: None, - debug_menu: false, - starter_sides: Vec::new(), - }; - this.selected = this.sorted_ids().first().cloned(); - this.reindex(); - this - } - - pub fn has_unsaved(&self) -> bool { - match &self.screen { - Screen::Session(session) => session.has_unsaved(), - Screen::Repertoires | Screen::Lines(_) => false, - } - } - - /// 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.scroll_to_selected = true; - if !matches!(self.screen, Screen::Session(_)) { - self.screen = Screen::Repertoires; - } - } - - pub fn open_from_toast(&mut self, id: RepertoireId, title: String, _settings: &Settings) { - self.return_to_game = Some(title); - 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()); - let selected = self - .library - .repertoires - .iter() - .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 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.library.repertoire(&id).is_some() { - self.selected = Some(id); - self.scroll_to_selected = true; - } - } - - fn selected_name(&self) -> String { - self.selected - .as_ref() - .and_then(|id| self.library.repertoire(id)) - .map(|r| r.name.clone()) - .unwrap_or_default() - } - - 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 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), - initial: layout::position_of(&game, NodeId::ROOT), - last_move: layout::last_move(&game, start), - has_moves: !game.children(NodeId::ROOT).is_empty(), - }, - ) - }) - .collect(); - let _ = tx.send(Event::Indexed(job, index)); - }) { - 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() { - return false; - } - match self.library_store.save(&mut library) { - Ok(()) => { - self.library = library; - self.reindex(); - true - } - Err(error) => { - self.show_message( - trf("Could not save: {e}", &[("e", &error.to_string())]), - true, - ); - false - } - } - } - - fn checked_name(&self, name: &str, excluding: Option<&RepertoireId>) -> Result { - let name = name.split_whitespace().collect::>().join(" "); - if name.is_empty() { - return Err(tr("The repertoire name must not be empty").to_owned()); - } - if name.chars().count() > 120 { - return Err(tr("The repertoire name is longer than 120 characters").to_owned()); - } - if self.library.repertoires.iter().any(|r| { - Some(&r.id) != excluding - && r.name - .split_whitespace() - .collect::>() - .join(" ") - .to_lowercase() - == name.to_lowercase() - }) { - return Err(tr("A repertoire with this name already exists").to_owned()); - } - Ok(name) - } - - fn start(&mut self, kind: SessionKind, settings: &Settings) { - if self.preparing.is_some() || self.has_unsaved() { - return; - } - let Some(id) = self.selected.clone() else { - return; - }; - 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(); - 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); - } - 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)); - let base = self.library.clone(); - let tx = self.tx.clone(); - let ctx = ctx.clone(); - 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(); - 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.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 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 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); - } - return false; - } - let mut library = preview.library.clone(); - 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; - } - } - } - 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 - .as_ref() - .and_then(|id| self.library.repertoire(id)) - else { - return; - }; - let pgn = r.pgn.clone(); - let name = format!("{}.pgn", r.name.replace(['/', '\\'], "_")); - let tx = self.tx.clone(); - 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() - }); - 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.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; - } - while let Ok(event) = self.rx.try_recv() { - match event { - Event::Indexed(job, index) => { - if job == self.index_job { - self.index = index; - } - } - Event::Stats(key, stats) => { - if self.stats_key.as_ref() == Some(&key) { - self.stats = stats; - self.stats_shown = Some(key); - } - } - Event::Imported(job, result) => { - let Some(Dialog::Import(dialog)) = &mut self.dialog else { - continue; - }; - if dialog.job != job { - continue; - } - match result { - 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.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::LinesReady(job, lines) => { - if self.lines_job != Some(job) { - continue; - } - 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), - } - } - } - } - 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 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(); - 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) - .rect_filled(available, 0.0, background); - if self.preparing.is_some() || self.lines_job.is_some() { - ui.ctx().request_repaint_after(Duration::from_millis(50)); - } - 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.initial.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: None, - lines: preparing.kind != SessionKind::Daily, - }; - for action in show_preparing(ui, settings, &mut self.board, &view) { - match action { - SessionAction::Back => { - self.preparing = None; - self.screen_back_from_session(); - } - SessionAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), - SessionAction::Sound(_) | SessionAction::MoreNew => {} - } - } - return actions; - } - 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; - } - 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; - } - Screen::Repertoires => {} - } - self.repertoires_screen(ui, settings, &mut actions); - self.show_dialog(ui.ctx(), settings, &mut actions); - self.show_add(ui, settings, &mut actions); - actions - } - - 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; - } - LinesAction::OpenSettings => actions.push(RepertoireAction::OpenSettings), - LinesAction::Train { through, label } => { - let kind = if through.is_empty() { - SessionKind::ReviewAll - } else { - SessionKind::Branch { through, label } - }; - 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 - { - lines.refresh(&self.library, &self.learning.learning); - } - } - } - } - - 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), - ) - .wrap(), - ); - } - }, - ); - } - - fn card(&mut self, ui: &mut Ui, settings: &Settings) -> Option { - let two_rows = card_buttons_two_rows(ui, ui.available_width() - 22.0); - let card_h = if two_rows { - CARD_H + BUTTON_ROW_H + 6.0 - } else { - CARD_H - }; - 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 = 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 = 6.0; - let width = ui.available_width(); - // 1. The name and the colour. - layout::fixed_block(ui, 26.0, |ui| { - ui.horizontal(|ui| { - // The colour gives way first: down to the king, the words on - // hover; only then is the name cut. - let gap = ui.spacing().item_spacing.x; - let words = layout::you_play(side); - let name_w = style_width(ui, &name, egui::TextStyle::Heading); - let king_w = layout::KING + gap; - let full_w = king_w + style_width(ui, words, egui::TextStyle::Body) + gap; - let short = name_w + full_w > width; - let you_w = if short { king_w } else { full_w }; - ui.allocate_ui_with_layout( - vec2((width - you_w - gap).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| { - if !short { - ui.label(RichText::new(words).weak()); - } - let king = ui.add(layout::king(side).sense(egui::Sense::hover())); - if short { - king.on_hover_text(words); - } - }); - }); - }); - // 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, 30.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: one row when the widest row fits, else the main button - // on a row of its own. Which one depends on the width alone, so the - // card keeps its height whatever is selected. - let (label, enabled, item) = main_button(&state, side); - // «Review all» is there in every state with moves unless the main button - // already is it. - let third = !matches!( - state, - CardState::Empty - | CardState::Failed(_) - | CardState::Counting - | CardState::OtherColor - ) && !matches!(item, Some(MenuItem::ReviewAll)); - let gap = ui.spacing().item_spacing.x; - let mut main = |ui: &mut Ui, width: f32| { - let response = ui - .add_enabled_ui(enabled, |ui| { - crate::widgets::primary_wide(ui, &label, width) - }) - .inner; - let response = if matches!(state, CardState::Counting) { - response.on_disabled_hover_text(tr("Counting moves…")) - } else { - response - }; - if response.clicked() { - chosen = item; - } - }; - let lines_enabled = !matches!(state, CardState::Empty | CardState::Failed(_)); - let rest = |ui: &mut Ui, lines_w: f32, third_w: f32| -> Option { - let mut picked = None; - if ui - .add_enabled( - lines_enabled, - egui::Button::new(tr("Lines…")) - .truncate() - .min_size(vec2(lines_w, BUTTON_ROW_H)), - ) - .clicked() - { - picked = Some(MenuItem::Lines); - } - if third - && ui - .add( - egui::Button::new(tr("Review all")) - .truncate() - .min_size(vec2(third_w, BUTTON_ROW_H)), - ) - .on_hover_text(tr("Review all lines")) - .clicked() - { - picked = Some(MenuItem::ReviewAll); - } - picked - }; - let mut picked = None; - if two_rows { - // In a row, as in the one-row layout: the label is centred. - layout::fixed_block(ui, BUTTON_ROW_H, |ui| { - ui.horizontal(|ui| { - let width = ui.available_width(); - main(ui, width); - }); - }); - layout::fixed_block(ui, BUTTON_ROW_H, |ui| { - ui.horizontal(|ui| { - let half = ((ui.available_width() - gap) / 2.0).max(0.0); - picked = rest(ui, half, half); - }); - }); - } else { - layout::fixed_block(ui, BUTTON_ROW_H, |ui| { - ui.horizontal(|ui| { - let pad = 2.0 * ui.spacing().button_padding.x + 2.0; - let room = ui.available_width(); - let need = - |text: &str| style_width(ui, text, egui::TextStyle::Button) + pad; - let main_need = need(&label); - let lines_need = need(tr("Lines…")); - let third_need = need(tr("Review all")); - let (main_w, lines_w, third_w) = if third { - let mut 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 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 { - let lines_w = lines_need.max(LINES_W.min(room / 3.0)); - ( - (room - lines_w - gap).max(0.0).min(MAIN_W.max(main_need)), - lines_w, - 0.0, - ) - }; - main(ui, main_w); - picked = rest(ui, lines_w, third_w); - }); - }); - } - if picked.is_some() { - chosen = picked; - } - }); - }); - chosen - } - - 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(|id| Some(id) == self.selected.as_ref()) - } else { - None - }; - let mut clicked = None; - 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; - let columns = table_widths(ui, ui.available_width()); - let (today_w, passed_w) = (columns.today, columns.passed); - let bar_w = columns.bar; - let mut table = egui_extras::TableBuilder::new(ui) - .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(columns.name_least) - .clip(true), - ) - .column(egui_extras::Column::exact(KING_W)) - .column(egui_extras::Column::exact(today_w)) - .column(egui_extras::Column::exact(passed_w)) - .column(egui_extras::Column::exact(MENU_W)); - if let Some(index) = scroll_row { - table = table.scroll_to_row(index, None); - } - table - .header(HEADER_H, |mut header| { - header.col(|ui| { - ui.add(egui::Label::new(RichText::new(tr("Name")).strong()).truncate()); - }); - 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("Today")).strong()).truncate()); - }); - }); - // «Passed» heads the bar and the number together. - header.col(|ui| { - // From the left edge of the bars. - ui.add_space(columns.start); - ui.add(egui::Label::new(RichText::new(tr("Passed")).strong()).truncate()); - }); - header.col(|_| {}); - }) - .body(|body| { - 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); - let selected = self.selected.as_ref() == Some(id); - row.set_selected(selected); - row.col(|ui| { - layout::line(ui, repertoire.name.as_str()); - }); - row.col(|ui| { - ui.add(layout::king(side).sense(egui::Sense::hover())) - .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 { - Some(Ok(_)) if !has_moves => {} - 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(when_short(at, layout::now())).weak() - } else { - RichText::new("—").weak() - }; - let mut hint = trf( - "To review {n}, new in the session {m}", - &[("n", &stats.due), ("m", &stats.new_today())], - ); - if let Some((at, _)) = stats.next - && stats.due == 0 - && stats.new_today() == 0 - { - hint = format!("{}\n{hint}", layout::when(at, layout::now())); - } - ui.add(egui::Label::new(text).truncate()).on_hover_text(hint); - } - Some(Err(_)) => { - ui.label(RichText::new("—").weak()); - } - None => { - ui.label(RichText::new("…").weak()); - } - } - }); - }); - let passed = matches!(stats, Some(Ok(stats)) if has_moves && stats.total > 0); - // [bar][6][number from the left]: neither moves with the counts. - row.col(|ui| { - ui.add_space(columns.start); - match stats { - Some(Ok(stats)) if 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(bar_w, 6.0), - ); - progress_bar(ui, bar, Some(stats), selected); - ui.interact( - bar.expand2(vec2(0.0, 6.0)), - ui.id().with("bar"), - egui::Sense::hover(), - ) - .on_hover_text(passed_hint(stats)); - ui.add_space(bar_w + MINI_BAR_GAP); - ui.label(format!("{}/{}", stats.passed(), stats.total)) - .on_hover_text(passed_hint(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(_) => { - ui.label(RichText::new("—").weak()); - } - None => { - ui.label(RichText::new("…").weak()); - } - } - }); - let mut opened = false; - row.col(|ui| { - 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 let Some(item) = - popup - .show(|ui| menu_items(ui, side, stats)) - .and_then(|inner| { - opened = true; - inner.inner - }) - { - chosen = Some(item); - } - }); - 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 - }) - { - chosen = Some(item); - } - if opened && self.selected.as_ref() != Some(id) { - clicked = Some(id.clone()); - } - if response.clicked() { - clicked = Some(id.clone()); - } - if response.double_clicked() { - clicked = Some(id.clone()); - double = true; - } - }); - }); - if let Some(id) = clicked { - self.selected = Some(id); - } - if double { - chosen = Some(MenuItem::Train); - } - chosen - } - - 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, - ) { - let Some(dialog) = self.dialog.take() else { - return; - }; - let names: HashMap = self - .library - .repertoires - .iter() - .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 modal.should_close() && result.is_none() { - result = Some(false); - } - 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 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)); - 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() { - ui.add( - egui::TextEdit::singleline(&mut add.name) - .char_limit(120) - .hint_text(tr("Name")), - ); - side_choice(ui, &mut add.side); - } - ui.horizontal(|ui| { - cancel = ui.button(tr("Cancel")).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 { - let name = self.checked_name(&add.name, None)?; - library - .create(name, &Game::from_start(add.source.start().clone())) - .map_err(|e| e.to_string())? - }; - let report = library - .add_prefix(&id, &add.source, add.at) - .map_err(|e| e.to_string())?; - let name = library - .repertoire(&id) - .map(|r| r.name.clone()) - .unwrap_or_default(); - Ok::<_, String>((library, id, name, report, new)) - })(); - match result { - 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(error) => self.show_message(error, true), - } - } - if !cancel { - self.add = Some(add); - } - } - - pub fn debug_import(&mut self, path: PathBuf) { - let target = - std::env::var_os("CP_REPERTOIRE_IMPORT_INTO").and_then(|_| self.selected.clone()); - self.import_path(path, target); - } - - /// `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(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; - }; - 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 { - add.name = target; - 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 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(); - // 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, - "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 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 Screen::Session(session) = &mut self.screen { - session.debug_hint(); - } - } -} - -impl Drop for RepertoireUi { - fn drop(&mut self) { - 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("Switch colour to Black"), - LearningSide::Black => tr("Switch colour to 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. -/// «Learned 3, learning 10, 75 moves in all» and what «learned» takes. -fn passed_hint(stats: &RowStats) -> String { - trf( - "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", &stats.passed()), - ("y", &stats.total), - ("l", &stats.learnt), - ], - ) -} - -/// 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) { - 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 { - 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; - painter.rect_filled( - egui::Rect::from_min_size(bar.min, vec2(learnt, bar.height())), - 2.0, - learnt_fill, - ); - painter.rect_filled( - egui::Rect::from_min_size(bar.min + vec2(learnt, 0.0), vec2(learning, bar.height())), - 0.0, - learning_fill, - ); - } -} - -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, false); - ui.spacing_mut().item_spacing.y = 4.0; - ui.horizontal(|ui| { - ui.set_height(18.0); - 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)); - } - }); -} - -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("Switch colour to Black"), - LearningSide::Black => tr("Switch colour to 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, - (layout::king(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 -} - -/// Whether the card's buttons take two rows at this inner width of the card: the widest -/// one-row set (a main button of the states with «Review all») does not fit. -fn card_buttons_two_rows(ui: &Ui, width: f32) -> bool { - let pad = 2.0 * ui.spacing().button_padding.x + 2.0; - let need = |text: &str| style_width(ui, text, egui::TextStyle::Button) + pad; - let main = need(tr("Train")).max(need(&trf("Learn {m} new", &[("m", &NEW_PER_SESSION)]))); - let gap = ui.spacing().item_spacing.x; - main + need(tr("Lines…")) + need(tr("Review all")) + 2.0 * gap > width -} - -/// The width of `text` in the font of `style`, as a label or a button draws it. -fn style_width(ui: &Ui, text: &str, style: egui::TextStyle) -> f32 { - ui.painter() - .layout_no_wrap( - text.to_owned(), - style.resolve(ui.style()), - egui::Color32::WHITE, - ) - .size() - .x -} - -/// The widths of the table's columns. -#[derive(Clone, Copy, Debug)] -struct TableColumns { - /// What the name keeps at the least: `NAME_LEAST`, less in a narrow panel so that - /// the fixed columns always fit. - name_least: f32, - today: f32, - passed: f32, - /// The bar of «Passed». - bar: f32, - /// Where the bar and the header of «Passed» start in its column. - start: f32, -} - -impl TableColumns { - /// All columns at their least, with the spaces between them. - fn least(&self, gap: f32) -> f32 { - self.name_least + KING_W + self.today + self.passed + MENU_W + 4.0 * gap - } -} - -/// The table's columns for a table `width` wide, measured once a frame from the texts -/// they may show, never from the rows on screen: counting or scrolling moves no column. -fn table_widths(ui: &Ui, width: f32) -> TableColumns { - let body = |text: &str| style_width(ui, text, egui::TextStyle::Body); - let now = layout::now(); - let today = [ - trf("review {n}", &[("n", &99)]), - trf("new: {n}", &[("n", &10)]), - when_short(now, now), - when_short(now + 24 * 60 * 60, now), - when_short(now + 3 * 24 * 60 * 60, now), - when_short(now + 30 * 24 * 60 * 60, now), - ] - .iter() - .map(|t| body(t)) - .fold(0.0, f32::max); - // A strong header is the body font in a brighter colour: as wide. - let today = (today.max(body(tr("Today"))) + 4.0).ceil(); - // The lead keeps the bar off «Today»; the header and «no moves» may use it. - let gap = ui.spacing().item_spacing.x; - let lead = (PASSED_GAP - gap).max(0.0); - let columns = |bar: f32| { - // The group of the bar and the room of «00/000», or the header if wider; the - // lead before it unless the header needs that room. - let group = bar + MINI_BAR_GAP + body(NUMBER_SAMPLE); - let content = group.max(body(tr("Passed"))).max(body(tr("no moves"))); - let passed = ((lead + group).max(content) + 4.0).ceil(); - let start = (passed - 4.0 - content).max(0.0); - let fixed = KING_W + today + passed + MENU_W + 4.0 * gap; - TableColumns { - name_least: (width - fixed).clamp(NAME_FLOOR, NAME_LEAST), - today, - passed, - bar, - start, - } - }; - let wide = columns(MINI_BAR_W); - if width < NARROW_TABLE && width - wide.least(gap) + wide.name_least < NAME_WANTED { - columns(MINI_BAR_NARROW) - } else { - wide - } -} - -/// The date of the next review in a table cell: «12:30» today, «tomorrow», «in 3 days», -/// then «dd.mm». The card and the hint say it in full. -fn when_short(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(); - }; - match (at.date_naive() - now.date_naive()).num_days() { - ..=0 => at.format("%H:%M").to_string(), - 1..=6 => layout::when(at.timestamp(), now.timestamp()), - _ => at.format("%d.%m").to_string(), - } -} - -/// 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, - mut library: Library, - cancel: &AtomicBool, -) -> Result { - let bytes = std::fs::read(path).map_err(|e| e.to_string())?; - let db = - PgnDatabase::from_bytes(bytes, None, &mut |_| {}, cancel).map_err(|e| e.to_string())?; - 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 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(String::new()); - } - 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) - { - 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(stem.clone(), &Game::from_start(parsed.game.start().clone())) - .map_err(|e| e.to_string())?; - id = Some(new_id.clone()); - new_id - } - }; - 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; - } - Ok(ImportPreview { - lines: layout::lines(&game, |_| false).len(), - lines_before, - suggested: suggested_side(&game), - library, - id, - base_revision, - games: db.len(), - own, - default_name: name, - warnings, - report, - }) -} - -/// Stable key, name, PGN and colour of each example repertoire. -/// An example repertoire: a stable key, its name and its PGN with English comments and -/// with Russian ones (the same moves). -struct Starter { - key: &'static str, - name: &'static str, - pgn: &'static str, - pgn_ru: &'static str, - side: LearningSide, -} - -impl Starter { - /// The PGN in the interface language at the moment it is given: Russian comments - /// for Russian, English for every other language. - fn pgn(&self) -> &'static str { - match crate::i18n::current() { - crate::i18n::Lang::Ru => self.pgn_ru, - _ => self.pgn, - } - } -} - -const STARTER_REPERTOIRES: [Starter; 4] = [ - Starter { - key: "spanish-white", - name: "Spanish Opening", - pgn: include_str!("../assets/repertoires/spanish-white.pgn"), - pgn_ru: include_str!("../assets/repertoires/spanish-white.ru.pgn"), - side: LearningSide::White, - }, - Starter { - key: "sicilian-black", - name: "Sicilian Defence: Najdorf", - pgn: include_str!("../assets/repertoires/sicilian-black.pgn"), - pgn_ru: include_str!("../assets/repertoires/sicilian-black.ru.pgn"), - side: LearningSide::Black, - }, - Starter { - key: "queens-gambit-white", - name: "Queen's Gambit", - pgn: include_str!("../assets/repertoires/queens-gambit-white.pgn"), - pgn_ru: include_str!("../assets/repertoires/queens-gambit-white.ru.pgn"), - side: LearningSide::White, - }, - Starter { - key: "triangle-black", - name: "Semi-Slav: Triangle", - pgn: include_str!("../assets/repertoires/triangle-black.pgn"), - pgn_ru: include_str!("../assets/repertoires/triangle-black.ru.pgn"), - side: LearningSide::Black, - }, -]; - -const STARTER_MARKS_VERSION: u32 = 1; - -/// Keys of the example repertoires already given to the user, in a file of its own next -/// to the library: the library format read by 2.4.0 stays as it is. -#[derive(serde::Serialize, serde::Deserialize)] -struct StarterMarks { - version: u32, - given: BTreeSet, -} - -#[derive(serde::Deserialize)] -struct StarterMarksVersion { - version: u32, -} - -fn starter_marks_path(store: &LibraryStore) -> PathBuf { - store.path().with_file_name("repertoire-starters.json") -} - -/// Marks read from the file. `None`: no file yet. A file of a newer version means every -/// example was given: it is neither reissued nor overwritten. -enum StarterMarksState { - Missing, - Given(BTreeSet), - Newer, -} - -fn read_starter_marks(path: &Path) -> Result { - let damaged = - || tr("The record of example repertoires is damaged; examples were not added").to_owned(); - let bytes = match crate::platform::fs::read(path) { - Ok(bytes) => bytes, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - return Ok(StarterMarksState::Missing); - } - Err(e) => { - eprintln!("{}: {e}", path.display()); - return Err(damaged()); - } - }; - let version = serde_json::from_slice::(&bytes).map_err(|e| { - eprintln!("{}: {e}", path.display()); - damaged() - })?; - if version.version != STARTER_MARKS_VERSION { - eprintln!( - "{}: unknown version {}, examples are not added", - path.display(), - version.version - ); - return Ok(StarterMarksState::Newer); - } - let marks = serde_json::from_slice::(&bytes).map_err(|e| { - eprintln!("{}: {e}", path.display()); - damaged() - })?; - Ok(StarterMarksState::Given(marks.given)) -} - -/// Each example repertoire is given once. An example also counts as given whenever a -/// repertoire carries its name in any language: the examples of 2.4.0 had no marks, and a -/// lost write of the marks must not double them. Examples deleted after that do not come -/// back; the user's own repertoires are not touched. The library is read again right -/// before the examples are added, and a save that lost a race with another copy of the -/// program is retried on the fresh library. -fn seed_starter(store: &LibraryStore) -> Result, String> { - let marks_path = starter_marks_path(store); - let (mut given, marked) = match read_starter_marks(&marks_path)? { - StarterMarksState::Newer => return Ok(Vec::new()), - StarterMarksState::Missing => (BTreeSet::new(), false), - StarterMarksState::Given(given) => (given, true), - }; - let mut attempts = 0; - let sides = loop { - attempts += 1; - let mut library = store.load().map_err(|e| e.to_string())?; - for Starter { key, name, .. } in &STARTER_REPERTOIRES { - let names = crate::i18n::all_languages(name); - if library - .repertoires - .iter() - .any(|r| names.contains(&r.name.as_str())) - { - given.insert((*key).to_owned()); - } - } - let missing: Vec<_> = STARTER_REPERTOIRES - .iter() - .filter(|starter| !given.contains(starter.key)) - .collect(); - if missing.is_empty() { - break Vec::new(); - } - let mut sides = Vec::new(); - let cancel = AtomicBool::new(false); - for starter in &missing { - let (name, pgn, side) = (starter.name, starter.pgn(), &starter.side); - 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)); - } - } - match store.save(&mut library) { - Ok(()) => { - given.extend(missing.iter().map(|starter| starter.key.to_owned())); - break sides; - } - Err(StoreError::Conflict { .. }) if attempts < 3 => continue, - Err(e) => return Err(e.to_string()), - } - }; - if marked && sides.is_empty() { - return Ok(sides); - } - let marks = StarterMarks { - version: STARTER_MARKS_VERSION, - given, - }; - let bytes = serde_json::to_vec_pretty(&marks).map_err(|e| e.to_string())?; - // The library is already saved; without the marks the names still keep the examples - // from being added again. - if let Err(e) = crate::settings::write_atomic(&marks_path, &bytes) { - eprintln!("{}: {e}", marks_path.display()); - } - 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. - // The PGN does not change. - for repertoire in &mut library.repertoires { - repertoire.set_max_plies(u32::MAX); - } - Ok(library) -} - -fn prefix_label(game: &Game, at: NodeId) -> String { - game.path(at) - .into_iter() - .skip(1) - .filter_map(|id| game.move_label(id)) - .map(|s| crate::san::show(&s).into_owned()) - .collect::>() - .join(" ") -} - -fn stores() -> (LibraryStore, LearningStore) { - let legacy = std::env::var_os("CP_TRAINING_FILE") - .map(PathBuf::from) - .or_else(|| { - directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") - .map(|d| d.data_local_dir().join("training.json")) - }) - .unwrap_or_else(|| PathBuf::from("training.json")); - let dir = std::env::var_os("CP_REPERTOIRE_DIR") - .map(PathBuf::from) - .or_else(|| legacy.parent().map(Path::to_path_buf)) - .unwrap_or_else(|| PathBuf::from(".")); - ( - LibraryStore::new(dir.join("repertoires.json")), - LearningStore::with_legacy(dir.join("repertoire-training.json"), legacy), - ) -} - -#[cfg(test)] -#[path = "repertoire_ui_tests.rs"] -mod tests; diff --git a/apps/desktop/src/repertoire_ui_tests.rs b/apps/desktop/src/repertoire_ui_tests.rs deleted file mode 100644 index 98f35ac..0000000 --- a/apps/desktop/src/repertoire_ui_tests.rs +++ /dev/null @@ -1,911 +0,0 @@ -use std::sync::atomic::AtomicU64; - -use super::*; -use trainer::repertoire::{QueueMode, TrainingMode, active_learning_memberships}; - -static NEXT_DIR: AtomicU64 = AtomicU64::new(1); -const DAY: i64 = 24 * 60 * 60; - -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_DIR.fetch_add(1, Ordering::Relaxed) - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn stores(&self) -> (LibraryStore, LearningStore) { - ( - LibraryStore::new(self.0.join("repertoires.json")), - LearningStore::new(self.0.join("repertoire-training.json")), - ) - } - - fn ui(&self) -> RepertoireUi { - let (library, learning) = self.stores(); - RepertoireUi::with_stores(library, learning) - } -} - -impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -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 - }) - && ui.stats_shown == ui.stats_key; - 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, size)), - events, - ..Default::default() - }, - |root| actions = ui.show(root, settings), - ) - .drop_without_applying_deltas(); - actions -} - -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 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("Switch colour to 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.passed(), 3 + stats.learning); - 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), - ); - assert_eq!(layout::side_of(&settings, &id), LearningSide::Black); - settings - .repertoire_modes - .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!( - settings.repertoire_modes[id.as_str()], - (TrainingMode::Black, QueueMode::SpacedRepetition) - ); -} - -#[test] -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 *"), - ], - ); - for (size, left) in [ - (vec2(1920.0, 1080.0), 1360.0), - (vec2(1400.0, 900.0), 896.0), - (vec2(960.0, 600.0), 580.0), - ] { - let mut ui = dir.ui(); - let mut settings = Settings::default(); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - settle(&mut ui, &ctx, &mut settings, size); - let repertoires = panel_rect(&ctx); - assert!( - (repertoires.left() - left).abs() <= 1.0, - "{repertoires:?} in {size:?}" - ); - // 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 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(); - 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() - .all(|action| !matches!(action, RepertoireAction::Close)), - "Esc closes the dialog, not the screen" - ); - 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 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 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)); - // 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), (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(), 4); - assert_eq!( - sides.iter().map(|(_, side)| *side).collect::>(), - [ - LearningSide::White, - LearningSide::Black, - LearningSide::White, - LearningSide::Black - ] - ); - for (id, _) in &sides { - let repertoire = library.repertoire(id).unwrap(); - assert!(!layout::lines(&repertoire.game(), |_| false).is_empty()); - } - assert_eq!( - library - .repertoires - .iter() - .map(|r| r.name.as_str()) - .collect::>(), - [ - "Spanish Opening", - "Sicilian Defence: Najdorf", - "Queen's Gambit", - "Semi-Slav: Triangle" - ] - ); - - 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(), 4); -} - -#[test] -fn starter_repertoires_come_to_an_empty_library_of_2_3() { - let dir = TestDir::new("starter-existing"); - let (store, _) = dir.stores(); - store.save(&mut Library::default()).unwrap(); - assert_eq!(seed_starter(&store).unwrap().len(), 4); - assert_eq!(store.load().unwrap().repertoires.len(), 4); -} - -#[test] -fn starter_examples_of_2_4_0_are_not_doubled() { - let dir = TestDir::new("starter-240"); - // 2.4.0 created the examples in the interface language and kept no marks. - save_library( - &dir, - &[ - ("Испанская партия", "1. e4 e5 *"), - ("Sicilian Defence: Najdorf", "1. e4 c5 *"), - ], - ); - let (store, _) = dir.stores(); - let sides = seed_starter(&store).unwrap(); - assert_eq!( - sides.iter().map(|(_, side)| *side).collect::>(), - [LearningSide::White, LearningSide::Black] - ); - let names: Vec<_> = store - .load() - .unwrap() - .repertoires - .into_iter() - .map(|r| r.name) - .collect(); - assert_eq!( - names, - [ - "Испанская партия", - "Sicilian Defence: Najdorf", - "Queen's Gambit", - "Semi-Slav: Triangle" - ] - ); - assert!(seed_starter(&store).unwrap().is_empty()); -} - -#[test] -fn a_deleted_starter_does_not_come_back() { - let dir = TestDir::new("starter-deleted"); - let (store, _) = dir.stores(); - seed_starter(&store).unwrap(); - let mut library = store.load().unwrap(); - let id = library.repertoires[2].id.clone(); - library.delete(&id).unwrap(); - store.save(&mut library).unwrap(); - assert!(seed_starter(&store).unwrap().is_empty()); - let library = store.load().unwrap(); - assert_eq!(library.repertoires.len(), 3); - assert!( - library - .repertoires - .iter() - .all(|r| r.name != "Queen's Gambit") - ); -} - -#[test] -fn starters_leave_own_repertoires_and_progress_alone() { - let dir = TestDir::new("starter-own"); - let ids = save_library(&dir, &[("Mine", "1. d4 d5 2. c4 e6 *")]); - let (store, learning) = dir.stores(); - std::fs::write(learning.path(), b"progress bytes").unwrap(); - let before = serde_json::to_value(store.load().unwrap().repertoire(&ids[0]).unwrap()).unwrap(); - assert_eq!(seed_starter(&store).unwrap().len(), 4); - let library = store.load().unwrap(); - assert_eq!(library.repertoires.len(), 5); - assert_eq!( - serde_json::to_value(library.repertoire(&ids[0]).unwrap()).unwrap(), - before - ); - assert_eq!(std::fs::read(learning.path()).unwrap(), b"progress bytes"); -} - -#[test] -fn starters_are_not_doubled_when_their_marks_were_lost() { - let dir = TestDir::new("starter-lost-marks"); - let (store, _) = dir.stores(); - seed_starter(&store).unwrap(); - // A failed write of the marks, or marks from another copy that did not see them. - std::fs::remove_file(starter_marks_path(&store)).unwrap(); - assert!(seed_starter(&store).unwrap().is_empty()); - std::fs::write(starter_marks_path(&store), br#"{"version":1,"given":[]}"#).unwrap(); - assert!(seed_starter(&store).unwrap().is_empty()); - assert_eq!(store.load().unwrap().repertoires.len(), 4); -} - -#[test] -fn two_copies_starting_together_give_the_starters_once() { - for round in 0..20 { - let dir = TestDir::new(&format!("starter-race-{round}")); - let (store, _) = dir.stores(); - let results: Vec<_> = std::thread::scope(|s| { - let a = s.spawn(|| seed_starter(&store.clone())); - let b = s.spawn(|| seed_starter(&store.clone())); - vec![a.join().unwrap(), b.join().unwrap()] - }); - let added: usize = results.iter().map(|r| r.as_ref().unwrap().len()).sum(); - assert_eq!(added, 4); - assert_eq!(store.load().unwrap().repertoires.len(), 4); - } -} - -#[test] -fn damaged_starter_marks_give_a_short_message_and_change_nothing() { - let dir = TestDir::new("starter-damaged"); - let (store, _) = dir.stores(); - store.save(&mut Library::default()).unwrap(); - let path = starter_marks_path(&store); - std::fs::write(&path, br#"{"version":1,"given":["#).unwrap(); - let error = seed_starter(&store).unwrap_err(); - assert_eq!( - error, - "The record of example repertoires is damaged; examples were not added" - ); - assert!(!error.contains(&*dir.0.to_string_lossy())); - assert_eq!(std::fs::read(&path).unwrap(), br#"{"version":1,"given":["#); - assert!(store.load().unwrap().repertoires.is_empty()); -} - -#[test] -fn starter_marks_of_an_unknown_version_are_left_alone() { - let dir = TestDir::new("starter-newer"); - let (store, _) = dir.stores(); - store.save(&mut Library::default()).unwrap(); - let path = starter_marks_path(&store); - std::fs::write(&path, br#"{"version":99,"given":5}"#).unwrap(); - assert!(seed_starter(&store).unwrap().is_empty()); - assert_eq!( - std::fs::read(&path).unwrap(), - br#"{"version":99,"given":5}"# - ); - assert!(store.load().unwrap().repertoires.is_empty()); -} - -#[test] -fn the_panel_opens_at_the_width_the_user_dragged_it_to() { - let dir = TestDir::new("side-width"); - save_library(&dir, &[("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *")]); - let size = vec2(1920.0, 1080.0); - for (kept, width) in [ - (Some(400.0_f32), 400.0), - (Some(100.0), 360.0), - (None, 560.0), - ] { - let mut ui = dir.ui(); - let mut settings = Settings::default(); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - // As the app does: the saved width is given once the context runs. - ctx.run_ui(egui::RawInput::default(), |_| {}) - .drop_without_applying_deltas(); - if let Some(kept) = kept { - ctx.data_mut(|d| { - d.insert_temp(egui::Id::new(crate::opening_layout::SIDE_WIDTH_ID), kept) - }); - } - settle(&mut ui, &ctx, &mut settings, size); - let rect = panel_rect(&ctx); - assert!((rect.width() - width).abs() <= 1.0, "{rect:?} for {kept:?}"); - } -} - -#[test] -fn a_window_that_grows_gives_the_panel_the_width_of_its_final_size() { - let dir = TestDir::new("side-grow"); - save_library(&dir, &[("Italian", "1. e4 e5 2. Nf3 Nc6 3. Bc4 *")]); - let mut ui = dir.ui(); - let mut settings = Settings::default(); - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - settle(&mut ui, &ctx, &mut settings, vec2(960.0, 600.0)); - settle(&mut ui, &ctx, &mut settings, vec2(1920.0, 1080.0)); - let rect = panel_rect(&ctx); - assert!((rect.width() - 560.0).abs() <= 1.0, "{rect:?}"); -} - -#[test] -fn the_table_fits_the_least_panel_in_every_language() { - let ctx = egui::Context::default(); - crate::assets::install(&ctx); - for lang in crate::i18n::Lang::ALL { - crate::i18n::set_lang(lang); - ctx.run_ui(egui::RawInput::default(), |root| { - egui::CentralPanel::default().show(root, |ui| { - // The table's width in a panel at its least: its frame takes 8 on each side. - let width = crate::opening_layout::SIDE_LEAST - 16.0; - let columns = table_widths(ui, width); - let gap = ui.spacing().item_spacing.x; - assert!( - columns.least(gap) <= width, - "{lang:?}: {columns:?} + gaps > {width}" - ); - assert!(columns.name_least >= NAME_WANTED, "{lang:?}: {columns:?}"); - // The bar, 6 px and the number from the left fit for any count, the - // header from the bar's left edge too; the bar keeps off «Today». - let body = |text: &str| style_width(ui, text, egui::TextStyle::Body); - for number in ["0/22", "12/22", "00/000"] { - assert!( - columns.start + columns.bar + MINI_BAR_GAP + body(number) - <= columns.passed - 4.0 + 0.5, - "{lang:?}: {number} in {columns:?}" - ); - } - assert!(columns.start + body(tr("Passed")) <= columns.passed - 4.0 + 0.5); - assert!( - // Unless the header itself takes the whole column. - columns.start + gap >= PASSED_GAP - 0.5 || columns.start < 1.0, - "{lang:?}: {columns:?}" - ); - }); - }) - .drop_without_applying_deltas(); - } - crate::i18n::set_lang(crate::i18n::Lang::En); -} - -#[test] -fn a_review_date_is_short_in_the_table() { - use chrono::{Local, TimeZone}; - let now = Local - .with_ymd_and_hms(2026, 11, 27, 9, 0, 0) - .single() - .unwrap() - .timestamp(); - assert_eq!(when_short(now + 3 * 60 * 60 + 30 * 60, now), "12:30"); - assert_eq!(when_short(now + 40 * 24 * 60 * 60, now), "06.01"); -} - -/// The comments of a PGN text: what stands in braces. -fn pgn_comments(pgn: &str) -> String { - let mut out = String::new(); - let mut depth = 0; - for c in pgn.chars() { - match c { - '{' => depth += 1, - '}' => depth -= 1, - c if depth > 0 => out.push(c), - _ => {} - } - } - out -} - -fn cyrillic(text: &str) -> bool { - text.chars() - .any(|c| ('а'..='я').contains(&c.to_lowercase().next().unwrap_or(c))) -} - -#[test] -fn starter_comments_follow_the_interface_language() { - for (lang, russian) in [ - (crate::i18n::Lang::Ru, true), - (crate::i18n::Lang::En, false), - (crate::i18n::Lang::De, false), - ] { - crate::i18n::set_lang(lang); - let dir = TestDir::new(&format!("starter-lang-{lang:?}")); - let (store, _) = dir.stores(); - assert_eq!(seed_starter(&store).unwrap().len(), 4); - for repertoire in store.load().unwrap().repertoires { - let comments = pgn_comments(&repertoire.pgn); - assert!(!comments.trim().is_empty(), "{lang:?} {}", repertoire.name); - assert_eq!( - cyrillic(&comments), - russian, - "{lang:?} {}: {comments}", - repertoire.name - ); - } - } - crate::i18n::set_lang(crate::i18n::Lang::En); -} - -#[test] -fn a_given_starter_keeps_its_comments_when_the_language_changes() { - let dir = TestDir::new("starter-lang-kept"); - let (store, _) = dir.stores(); - crate::i18n::set_lang(crate::i18n::Lang::En); - seed_starter(&store).unwrap(); - let before = std::fs::read(store.path()).unwrap(); - crate::i18n::set_lang(crate::i18n::Lang::Ru); - assert!(seed_starter(&store).unwrap().is_empty()); - assert_eq!(std::fs::read(store.path()).unwrap(), before); - crate::i18n::set_lang(crate::i18n::Lang::En); -} - -/// Every line of moves of a PGN, as UCI paths from the start, comments aside. -fn move_tree(pgn: &str) -> Vec> { - let cancel = AtomicBool::new(false); - let db = PgnDatabase::from_bytes(pgn.as_bytes().to_vec(), None, &mut |_| {}, &cancel).unwrap(); - let mut lines = Vec::new(); - for index in 0..db.len() { - let game = db.load_game(index).unwrap().game; - let mut stack = vec![(NodeId::ROOT, Vec::new())]; - while let Some((node, path)) = stack.pop() { - let children = game.children(node); - if children.is_empty() { - lines.push(path); - continue; - } - for child in children { - let mut next = path.clone(); - next.push(game.move_label(*child).unwrap_or_default()); - stack.push((*child, next)); - } - } - } - lines.sort(); - lines -} - -#[test] -fn russian_and_english_starters_have_the_same_moves() { - for starter in &STARTER_REPERTOIRES { - assert_eq!( - move_tree(starter.pgn), - move_tree(starter.pgn_ru), - "{}", - starter.key - ); - assert!(!move_tree(starter.pgn).is_empty(), "{}", starter.key); - } -} diff --git a/apps/desktop/src/review.rs b/apps/desktop/src/review.rs index 56181ee..7927bf7 100644 --- a/apps/desktop/src/review.rs +++ b/apps/desktop/src/review.rs @@ -1,16 +1,13 @@ //! Whole-game analysis on the desktop: the background engine job over the main line, -//! the evaluation graph under the board and the report tab. The +//! the evaluation graph under the board, the report tab and the launch dialog. The //! evaluations, judgements, cache and the job itself are the `game-review` crate's, //! shared with the Android app. //! -//! The job uses engine processes of its own — Stockfish 19 (ChessPenguin's, or the user's -//! that searches the same, `review_engine`) with the fixed search of `game_review::run`, -//! the same on every computer — and -//! never touches the game; writing the results into the game is a separate, undoable -//! action ([`Review::write_to_game`]). +//! The job uses its own engine process and never touches the game; writing the results +//! into the game is a separate, undoable action ([`Review::write_to_game`]). use std::collections::HashMap; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, channel}; @@ -18,160 +15,38 @@ use std::sync::mpsc::{Receiver, channel}; use chess_core::shakmaty::{Color, Move}; use chess_core::{Game, Nag, NodeId}; use egui::{Color32, RichText, Sense, Stroke, Ui, pos2, vec2}; -use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement}; +use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, ReviewMeta}; pub use game_review::Mark; use crate::i18n::{tr, trf}; -use crate::settings::Settings; +use crate::settings::{EngineConfig, REVIEW_QUALITY, ReviewSettings, Settings}; pub enum ReportAction { Goto(NodeId), Write, - /// Evaluate what is missing (all of it for a stale analysis). Update, - /// The engine over evaluations read from the PGN. - Analyse, + Reanalyse, } -/// What an engine job sends to the screen. -pub enum JobMsg { +pub enum DialogAction { + Start, + EngineSwitch, + OpenEngines, +} + +enum JobMsg { Event(JobEvent), Done, Failed(String), } -/// An engine job under way. On a computer its thread sends everything through the -/// channel; in a browser its engines are Web Workers driven from the frames: -/// [`JobRunner::pump`] passes on what they gave. -pub struct JobRunner { - #[cfg(web)] - dispatcher: game_review::Dispatcher, - #[cfg(web)] - tx: std::sync::mpsc::Sender, - #[cfg(web)] - cancel: Arc, -} - -impl JobRunner { - /// Call every frame (nothing to do on a computer). - pub fn pump(&mut self) { - #[cfg(web)] - { - if self.cancel.load(Ordering::Relaxed) { - self.dispatcher.cancel(); - } - let (events, end) = self.dispatcher.poll(); - for e in events { - let _ = self.tx.send(JobMsg::Event(e)); - } - if let Some(end) = end { - let _ = self.tx.send(job_end(end)); - } - } - } -} - -/// The last message of a job. -fn job_end(result: Result<(), JobFailure>) -> JobMsg { - match result { - Ok(()) => JobMsg::Done, - Err(JobFailure::Start(e) | JobFailure::Engine(e)) => JobMsg::Failed(e), - Err(JobFailure::Terminated(reason)) => { - JobMsg::Failed(crate::analysis::termination_message(&reason)) - } - } -} - -/// Engines working at once for a job: one per logical CPU, as many as fit. -pub fn processes() -> usize { - #[cfg(web)] - return crate::platform::web::engine::workers(game_review::MAX_PROCESSES); - #[cfg(not(web))] - game_review::processes(game_review::MAX_PROCESSES) -} - -/// Runs the engine job over `targets` with ChessPenguin's Stockfish at `path` (in a -/// browser: the address of its worker) named `name`: its events and its end come -/// through `tx`, each waking `ctx`. -pub fn spawn_job( - name: &str, - engine: crate::engines::EngineLocation, - settings: JobSettings, - targets: Vec, - cancel: Arc, - tx: std::sync::mpsc::Sender, - ctx: egui::Context, -) -> std::io::Result { - #[cfg(not(web))] - { - let crate::engines::EngineLocation::Program(path) = engine; - std::thread::Builder::new() - .name(name.to_owned()) - .spawn(move || { - // A user's engine must still be the Stockfish 19 probed (a wrapper may - // start another program now): else the job stops at once, before any - // evaluation is taken, and the engine is probed again next time. - let mut changed = false; - let result = game_review::run( - engine_config(&path), - &settings, - targets, - &cancel, - &mut |e| { - if changed { - return; - } - if let JobEvent::Engine(name) = &e - && !crate::review_engine::name_fits(&path, name) - { - changed = true; - cancel.store(true, Ordering::Relaxed); - return; - } - let _ = tx.send(JobMsg::Event(e)); - ctx.request_repaint(); - }, - ); - let end = if changed { - JobMsg::Failed( - tr("The engine is no longer the Stockfish 19 that was checked. Start the analysis again.") - .into(), - ) - } else { - job_end(result) - }; - let _ = tx.send(end); - ctx.request_repaint(); - }) - .map(|_| JobRunner {}) - } - #[cfg(web)] - { - let _ = name; - let crate::engines::EngineLocation::Worker(script) = engine; - let wake: Arc = Arc::new(move || ctx.request_repaint()); - game_review::Dispatcher::start(&script, &settings, targets, wake) - .map(|dispatcher| JobRunner { - dispatcher, - tx, - cancel, - }) - .map_err(|e| match e { - JobFailure::Start(e) | JobFailure::Engine(e) => std::io::Error::other(e), - JobFailure::Terminated(r) => { - std::io::Error::other(crate::analysis::termination_message(&r)) - } - }) - } -} - struct Job { - runner: JobRunner, rx: Receiver, cancel: Arc, total: usize, done: usize, + threads: u32, } impl Drop for Job { @@ -187,43 +62,27 @@ pub struct Review { pub error: Option, /// Graph and report tab are shown. pub visible: bool, - /// Measured speed of one engine thread, for time estimates. + pub dialog_open: bool, + /// Measured engine speed per thread, for time estimates. nps_per_thread: Option, /// Report tab: index of the last visited error per side and kind. cycle: HashMap<(Color, Judgement), usize>, } /// The folder of the cached analyses. -pub fn cache_dir() -> Option { +fn cache_dir() -> Option { Settings::cache_dir().map(|d| d.join("analysis")) } -/// The cached analyses in the program's files (the platform's: a folder of the disk, or -/// the browser's storage). -pub struct Cache(pub PathBuf); - -impl game_review::CacheStore for Cache { - fn read(&self, name: &str) -> Option> { - crate::platform::fs::read(&self.0.join(name)).ok() - } - - fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> { - crate::platform::fs::write_atomic(&self.0.join(name), bytes) - } -} - impl Review { pub fn new(game: &Game) -> Self { - let cache = cache_dir().map(Cache); - let analysis = GameAnalysis::with_store( - game, - cache.as_ref().map(|c| c as &dyn game_review::CacheStore), - ); + let analysis = GameAnalysis::new(game, cache_dir().as_deref()); Review { visible: analysis.has_data(), analysis, job: None, error: None, + dialog_open: false, nps_per_thread: None, cycle: HashMap::new(), } @@ -251,48 +110,76 @@ impl Review { self.analysis.refresh(game); } - /// Starts the engine job with the engine at `path` (ChessPenguin's Stockfish). `full` - /// discards earlier results; otherwise only positions without an evaluation are - /// analysed (all of them for a stale analysis). Returns false if there is nothing to do. + /// Starts the engine job. `full` discards earlier results; otherwise only positions + /// without an evaluation are analysed. Returns false if there is nothing to do. pub fn start( &mut self, game: &Game, - engine: &crate::engines::EngineLocation, + engine: &EngineConfig, + rs: &ReviewSettings, full: bool, ctx: &egui::Context, ) -> bool { self.job = None; self.error = None; - let targets = self.analysis.begin(game, full); + let Some(path) = engine.executable() else { + self.error = Some(tr("The built-in engine is not part of this build").into()); + return false; + }; + let meta = ReviewMeta { + engine: engine.name.clone(), + nodes: rs.nodes(), + }; + let targets = self.analysis.begin(game, meta, full); if targets.is_empty() { return false; } let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let total = targets.len(); - let settings = JobSettings::new(processes(), None); - let spawned = spawn_job( - "game-review", - engine.clone(), - settings, - targets, - cancel.clone(), - tx, - ctx.clone(), - ); - let runner = match spawned { - Ok(r) => r, - Err(e) => { - self.error = Some(e.to_string()); - return false; - } + // Filling in keeps the quality of the earlier run (see `GameAnalysis::begin`). + let nodes = self.analysis.meta.as_ref().map_or(rs.nodes(), |m| m.nodes); + let settings = JobSettings { + threads: rs.threads.max(1), + hash_mb: rs.hash_mb, + nodes, + eval_file: None, }; + let threads = settings.threads; + let (cancel_w, ctx_w) = (cancel.clone(), ctx.clone()); + let spawned = std::thread::Builder::new() + .name("game-review".into()) + .spawn(move || { + let result = game_review::run( + uci::EngineConfig::new(&path), + &settings, + targets, + &cancel_w, + &mut |e| { + let _ = tx.send(JobMsg::Event(e)); + ctx_w.request_repaint(); + }, + ); + let msg = match result { + Ok(()) => JobMsg::Done, + Err(JobFailure::Start(e) | JobFailure::Engine(e)) => JobMsg::Failed(e), + Err(JobFailure::Terminated(reason)) => { + JobMsg::Failed(crate::analysis::termination_message(&reason)) + } + }; + let _ = tx.send(msg); + ctx_w.request_repaint(); + }); + if let Err(e) = spawned { + self.error = Some(e.to_string()); + return false; + } self.job = Some(Job { - runner, rx, cancel, total, done: 0, + threads, }); self.visible = true; true @@ -310,15 +197,13 @@ impl Review { return false; }; let mut ended = false; - job.runner.pump(); while let Ok(msg) = job.rx.try_recv() { match msg { JobMsg::Event(e) => { if let JobEvent::Eval { nps, .. } = &e { job.done += 1; - // One engine thread per process. if *nps > 0 { - self.nps_per_thread = Some(*nps as f64); + self.nps_per_thread = Some(*nps as f64 / f64::from(job.threads)); } } self.analysis.apply(e); @@ -344,22 +229,6 @@ impl Review { } } - /// "64 positions, about 20 s": what a full analysis of the game takes. - pub fn estimate(&self) -> String { - let secs = game_review::estimate_secs( - self.analysis.searches(), - self.nps_per_thread.unwrap_or(DEFAULT_NPS), - processes(), - ); - trf( - "{n} positions, about {time}", - &[ - ("n", &self.analysis.positions()), - ("time", &format_duration(secs)), - ], - ) - } - /// After an inaccuracy, mistake or blunder: how the opponent punishes it and how /// the player best answers (shown as arrows, as on Lichess). pub fn refutation(&self, node: NodeId, game: &Game) -> Vec { @@ -368,7 +237,7 @@ impl Review { fn save_cache(&self) { if let Some(dir) = cache_dir() - && let Err(e) = self.analysis.save_to(&Cache(dir.clone())) + && let Err(e) = self.analysis.save_cache(&dir) { eprintln!("review cache: {}: {e}", dir.display()); } @@ -667,34 +536,17 @@ impl Review { let missing = self.missing(); // An analysis from before !! and !: "Update" looks for them, nothing else. let seconds = self.analysis.seconds_missing(); - // An analysis of another search: "Update" makes it again. - let stale = self.analysis.stale(); - if (stale || missing > 0 || seconds > 0) && !self.running() { + if (missing > 0 || seconds > 0) && !self.running() { ui.horizontal_wrapped(|ui| { - let text = if stale { - tr("This analysis was made with other engine settings").to_string() - } else if missing > 0 { + let text = if missing > 0 { trf("Positions without evaluation: {n}", &[("n", &missing)]) } else { tr("!! and ! were not looked for in this analysis").to_string() }; ui.label(RichText::new(text).color(ui.visuals().warn_fg_color)); let can_update = self.analysis.meta.as_ref().is_some_and(|m| m.nodes > 0); - if can_update { - // Stale: everything again («Обновить»); otherwise the gaps («Дополнить»). - let mut button = ui.button(if stale { - tr("Analyse again") - } else { - tr("Update") - }); - if stale { - button = button.on_hover_text(tr( - "Every position is analysed again, the same way on every computer", - )); - } - if button.clicked() { - action = Some(ReportAction::Update); - } + if can_update && ui.button(tr("Update")).clicked() { + action = Some(ReportAction::Update); } }); } @@ -712,16 +564,11 @@ impl Review { { action = Some(ReportAction::Write); } - // Evaluations of the PGN: the engine can make its own (an engine analysis - // made again would only repeat itself). - let pgn_only = self.analysis.meta.as_ref().is_some_and(|m| m.nodes == 0); - if pgn_only - && ui - .add_enabled(!self.running(), egui::Button::new(tr("Analyse with the engine"))) - .on_hover_text(self.estimate()) - .clicked() + if ui + .add_enabled(!self.running(), egui::Button::new(tr("Analyse again…"))) + .clicked() { - action = Some(ReportAction::Analyse); + action = Some(ReportAction::Reanalyse); } }); action @@ -855,6 +702,136 @@ impl Review { *k = k.wrapping_add(1) % hits.len(); Some(hits[*k]) } + + /// Launch dialog (engine, quality, threads, memory, time estimate). + pub fn dialog(&mut self, ctx: &egui::Context, settings: &mut Settings) -> Option { + if !self.dialog_open { + return None; + } + let mut action = None; + let modal = egui::Modal::new(egui::Id::new("review_dialog")).show(ctx, |ui| { + ui.set_width(440.0); + ui.heading(tr("Game analysis")); + ui.label( + RichText::new(tr( + "The engine evaluates every position of the main line. The game itself is not changed.", + )) + .weak(), + ); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(tr("Engine")); + let current = settings + .active_engine() + .map(|e| e.name.clone()) + .unwrap_or_else(|| tr("not selected").into()); + egui::ComboBox::from_id_salt("review_engine") + .selected_text(current) + .width(ui.available_width() - 8.0) + .show_ui(ui, |ui| { + for i in 0..settings.engines.len() { + let selected = settings.active_engine == Some(i); + if ui + .selectable_label(selected, &settings.engines[i].name) + .clicked() + && !selected + { + settings.active_engine = Some(i); + action = Some(DialogAction::EngineSwitch); + } + } + ui.separator(); + if ui.button(tr("Add or edit engines…")).clicked() { + action = Some(DialogAction::OpenEngines); + } + }); + }); + ui.add_space(4.0); + let rs = &mut settings.review; + let cores = std::thread::available_parallelism() + .map(|n| n.get() as u32) + .unwrap_or(1); + let hash_steps = crate::game_view::hash_steps(); + ui.spacing_mut().slider_width = 200.0; + egui::Grid::new("review_grid") + .num_columns(3) + .spacing(vec2(12.0, 8.0)) + .show(ui, |ui| { + ui.label(tr("Quality")); + let mut q = rs.quality.min(REVIEW_QUALITY.len() - 1); + crate::game_view::index_slider(ui, &mut q, REVIEW_QUALITY.len()); + rs.quality = q; + ui.label(trf( + "{quality} · {nodes} nodes", + &[ + ("quality", &tr(REVIEW_QUALITY[q].0)), + ("nodes", &format_count(REVIEW_QUALITY[q].1)), + ], + )); + ui.end_row(); + + ui.label(tr("Threads")); + let mut th = rs.threads.clamp(1, cores) as usize - 1; + crate::game_view::index_slider(ui, &mut th, cores as usize); + rs.threads = th as u32 + 1; + ui.label(format!("{} / {cores}", rs.threads)); + ui.end_row(); + + ui.label(tr("Memory")); + let mut h = hash_steps + .iter() + .position(|m| *m >= rs.hash_mb) + .unwrap_or(hash_steps.len() - 1); + crate::game_view::index_slider(ui, &mut h, hash_steps.len()); + rs.hash_mb = hash_steps[h]; + ui.label(crate::game_view::format_mb(rs.hash_mb)); + ui.end_row(); + }); + ui.add_space(6.0); + let positions = self.analysis.positions(); + let per_thread = self.nps_per_thread.unwrap_or(700_000.0); + let searches = self.analysis.searches(); + let secs = searches as f64 * rs.nodes() as f64 / (per_thread * f64::from(rs.threads)); + ui.label(trf( + "{n} positions, about {time}", + &[("n", &positions), ("time", &format_duration(secs))], + )); + ui.add_space(10.0); + ui.horizontal(|ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let ready = settings.active_engine().is_some(); + if ui + .add_enabled( + ready, + egui::Button::new(RichText::new(tr("Analyse")).strong().size(16.0)), + ) + .clicked() + { + action = Some(DialogAction::Start); + } + if ui.button(tr("Cancel")).clicked() { + self.dialog_open = false; + } + if !ready { + ui.label( + RichText::new(tr("Add an engine first")) + .color(ui.visuals().warn_fg_color), + ); + } + }); + }); + }); + if modal.should_close() { + self.dialog_open = false; + } + if matches!( + action, + Some(DialogAction::Start | DialogAction::OpenEngines) + ) { + self.dialog_open = false; + } + action + } } impl Drop for Review { @@ -864,19 +841,6 @@ impl Drop for Review { } } -/// Nodes per second of one engine thread assumed until an engine was measured. -pub const DEFAULT_NPS: f64 = 700_000.0; - -/// ChessPenguin's Stockfish at `path` for an analysis job: below the program (nice 10), -/// so that the program stays smooth while every CPU works. -#[cfg(not(web))] -pub fn engine_config(path: &Path) -> uci::EngineConfig { - uci::EngineConfig { - nice: 10, - ..uci::EngineConfig::new(path) - } -} - /// Removes `[%eval …]` commands from a comment. fn strip_eval(c: &str) -> String { let mut out = String::new(); @@ -936,7 +900,7 @@ pub fn judgement_name(j: Judgement) -> &'static str { } } -pub fn judgement_plural(j: Judgement) -> &'static str { +fn judgement_plural(j: Judgement) -> &'static str { match j { Judgement::Inaccuracy => tr("Inaccuracies"), Judgement::Mistake => tr("Mistakes"), @@ -947,7 +911,7 @@ pub fn judgement_plural(j: Judgement) -> &'static str { } /// Accuracy in the colors of the move marks: green, blue, orange, red. -pub fn accuracy_color(a: f64, dark: bool) -> Color32 { +fn accuracy_color(a: f64, dark: bool) -> Color32 { let j = if a >= 85.0 { Judgement::Great } else if a >= 70.0 { @@ -965,7 +929,7 @@ fn percent(a: f64) -> String { } /// 250 000 → "250k", 1 000 000 → "1M". -pub fn format_count(n: u64) -> String { +fn format_count(n: u64) -> String { if n >= 1_000_000 && n.is_multiple_of(100_000) { let m = n as f64 / 1e6; if n.is_multiple_of(1_000_000) { @@ -980,7 +944,7 @@ pub fn format_count(n: u64) -> String { } } -pub fn format_duration(secs: f64) -> String { +fn format_duration(secs: f64) -> String { let s = secs.ceil().max(1.0) as u64; if s < 60 { trf("{n} s", &[("n", &s)]) diff --git a/apps/desktop/src/review_engine.rs b/apps/desktop/src/review_engine.rs deleted file mode 100644 index 6ed3d12..0000000 --- a/apps/desktop/src/review_engine.rs +++ /dev/null @@ -1,715 +0,0 @@ -//! The engine of the game analysis and the search for opening errors: ChessPenguin's -//! Stockfish 19, or else a Stockfish 19 of the user's (from the settings, or the one in -//! `PATH`) that searches exactly as ours (decision of 2026-10-31). Whether it does is -//! told by `game_review::probe` on a thread of its own: an engine not called -//! «Stockfish 19» is turned down at its `uci` answer, without a search; one that is -//! makes three short searches of the analysis's fixed mode. The verdict is remembered -//! for the real file (links followed) with its size and time, and with the probe's -//! reference: a file is probed once, again when it or the reference changes. An engine -//! that did not start is not remembered: it is tried again at the next request. - -use crate::engines::EngineLocation; - -/// Why the user's engine does not do for the analysis. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Why { - /// Another engine, or another version of Stockfish. - Other, - /// It calls itself Stockfish 19 but searches otherwise (another build or network). - Differs, - /// It did not start or did not answer. - NotStarted, - /// It calls itself Stockfish 19 but did not finish the check in time (a slow or - /// stuck machine): not remembered, checked again at the next request. - TimedOut, -} - -/// The user's engine that does not do: its name (`id name`, else what the settings -/// call it, else its file's name), where it is from, and why. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Unfit { - pub name: String, - /// From the settings (else `stockfish` found in `PATH`). - pub from_settings: bool, - pub why: Why, -} - -/// The engine to analyse with, now. -#[derive(Debug, PartialEq, Eq)] -pub enum Lookup { - Ready(EngineLocation), - /// An engine of the user's is being probed: asked again when it is done (the - /// screen is repainted then). - Checking, - /// The user's engines do not do: the first of them. - Unfit(Unfit), - /// No engine at all. - None, -} - -/// The engine to analyse with, from what is known (nothing is probed here): ours, or a -/// user's engine already found to be the same. -pub fn engine() -> Option { - #[cfg(not(web))] - return crate::engines::own_stockfish().or_else(native::verified); - #[cfg(web)] - crate::engines::own_stockfish() -} - -/// The engines of the user's to consider, in this order: the active one, the others of -/// the settings, `stockfish` from `PATH`. Called at the start, when the settings are -/// saved and when an analysis asks for an engine (not every frame). -#[cfg_attr(web, allow(unused_variables))] -pub fn set_candidates(settings: &crate::settings::Settings) { - #[cfg(not(web))] - native::set_candidates(native::candidates(settings)); -} - -/// The engine to analyse with; an engine of the user's not probed yet (or changed since) -/// is probed now, in the background. -#[cfg_attr(web, allow(unused_variables))] -pub fn lookup(ctx: &egui::Context) -> Lookup { - #[cfg(not(web))] - return native::lookup(ctx); - #[cfg(web)] - match engine() { - Some(l) => Lookup::Ready(l), - None => Lookup::None, - } -} - -/// Whether the engine at `path`, which said it is `name` at the start of a job, is the -/// one probed: ours always is; a user's one must still call itself Stockfish 19 (a -/// wrapper script may start another program than it did). One that does not is -/// forgotten, to be probed again. -#[cfg(not(web))] -pub fn name_fits(path: &std::path::Path, name: &str) -> bool { - native::name_fits(path, name) -} - -/// The program quits: the probes under way stop, their engines quit (or are killed). -pub fn shutdown() { - #[cfg(not(web))] - native::shutdown(); -} - -#[cfg(not(web))] -mod native { - use std::collections::{HashMap, HashSet}; - use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicBool, Ordering}; - use std::sync::{Mutex, OnceLock}; - use std::thread::JoinHandle; - - use game_review::probe::{ProbeLimits, STOCKFISH_19, reference_key}; - use serde::{Deserialize, Serialize}; - - use super::{Lookup, Unfit, Why}; - use crate::engines::EngineLocation; - - /// A probe's verdict on a file as it was. - #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] - pub(super) struct Verdict { - pub size: u64, - pub modified: u64, - pub same: bool, - pub name: Option, - } - - /// What is kept on the disk: the verdicts and the reference they were made with. - #[derive(Serialize, Deserialize)] - pub(super) struct Kept { - pub reference: String, - pub engines: HashMap, - } - - /// An engine of the user's: its file as given, the real file (links followed), - /// what the settings call it, and whether it is from them. - #[derive(Clone, Debug, PartialEq)] - pub(super) struct Candidate { - pub path: PathBuf, - pub real: PathBuf, - pub label: String, - pub from_settings: bool, - } - - impl Candidate { - pub(super) fn new(path: PathBuf, label: String, from_settings: bool) -> Candidate { - Candidate { - real: path.canonicalize().unwrap_or_else(|_| path.clone()), - path, - label, - from_settings, - } - } - } - - #[derive(Default)] - pub(super) struct State { - pub candidates: Vec, - /// By the real file. - pub known: HashMap, - /// Files that did not start or did not finish the check, until it is said (by - /// the real file): why, and the name the engine gave. - pub failed: HashMap)>, - pub checking: HashSet, - pub threads: Vec>, - /// How long a probe may take (shorter in the tests). - pub limits: ProbeLimits, - /// Where the verdicts are kept (`None`: nowhere). - pub file: Option, - pub loaded: bool, - } - - fn state() -> &'static Mutex { - static STATE: OnceLock> = OnceLock::new(); - STATE.get_or_init(Default::default) - } - - /// Set when the program quits: the probes give up. - static QUITTING: AtomicBool = AtomicBool::new(false); - - fn with(f: impl FnOnce(&mut State) -> T) -> T { - let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); - if !s.loaded { - s.loaded = true; - s.file = crate::settings::Settings::cache_dir().map(|d| d.join("review-engines.json")); - if let Some(bytes) = s.file.as_ref().and_then(|f| std::fs::read(f).ok()) { - s.known = read_kept(&bytes); - } - } - f(&mut s) - } - - /// The verdicts kept, if they were made with the probe of this program. - pub(super) fn read_kept(bytes: &[u8]) -> HashMap { - serde_json::from_slice::(bytes) - .ok() - .filter(|k| k.reference == reference_key()) - .map(|k| k.engines) - .unwrap_or_default() - } - - fn save(s: &State) { - let Some(f) = &s.file else { return }; - let kept = Kept { - reference: reference_key(), - engines: s.known.clone(), - }; - if let Ok(json) = serde_json::to_vec(&kept) { - let _ = crate::platform::fs::write_atomic(f, &json); - } - } - - pub(super) fn candidates(settings: &crate::settings::Settings) -> Vec { - let active = settings.active_engine.and_then(|i| settings.engines.get(i)); - let others = settings.engines.iter().filter(|e| Some(*e) != active); - let mut out: Vec = active - .into_iter() - .chain(others) - .filter(|e| !e.builtin) - .map(|e| Candidate::new(e.path.clone(), e.name.clone(), true)) - .collect(); - if let Some(p) = crate::engines::system_stockfish() { - let label = p.display().to_string(); - out.push(Candidate::new(p, label, false)); - } - // The same file twice (the system's Stockfish added in the settings): once. - let mut seen = HashSet::new(); - out.retain(|c| seen.insert(c.real.clone())); - // The engines of the games against the computer (Rodent, Maia) are never - // analysis engines, whatever the settings say: never probed. - let play = play_dirs(); - out.retain(|c| !play.iter().any(|d| c.real.starts_with(d))); - out - } - - /// The folders of the engines ChessPenguin plays with (links followed). - pub(super) fn play_dirs() -> Vec { - [ - crate::rodent_download::dir(), - crate::rodent4_download::dir(), - crate::maia_download::dir(), - ] - .into_iter() - .flatten() - .map(|d| d.canonicalize().unwrap_or(d)) - .collect() - } - - pub(super) fn set_candidates(candidates: Vec) { - with(|s| { - if s.candidates != candidates { - s.candidates = candidates; - } - }); - } - - /// The file's size and time (seconds), when it is there. - pub(super) fn stamp(path: &Path) -> Option<(u64, u64)> { - let m = std::fs::metadata(path).ok()?; - if !m.is_file() { - return None; - } - let modified = m - .modified() - .ok() - .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) - .map_or(0, |d| d.as_secs()); - Some((m.len(), modified)) - } - - /// The verdict on the real file as it is now, if there is one. - fn fresh<'a>(s: &'a State, real: &Path) -> Option<&'a Verdict> { - let (size, modified) = stamp(real)?; - s.known - .get(real) - .filter(|v| (v.size, v.modified) == (size, modified)) - } - - pub(super) fn verified() -> Option { - with(|s| { - s.candidates - .iter() - .find(|c| fresh(s, &c.real).is_some_and(|v| v.same)) - .map(|c| EngineLocation::Program(c.path.clone())) - }) - } - - pub(super) fn lookup(ctx: &egui::Context) -> Lookup { - match crate::engines::own_stockfish() { - Some(own) => Lookup::Ready(own), - None => lookup_without_own(ctx), - } - } - - /// [`lookup`] among the user's engines only. - pub(super) fn lookup_without_own(ctx: &egui::Context) -> Lookup { - match with(decide) { - Decision::Done(l) => l, - Decision::Probe(candidates) => { - for c in candidates { - spawn_probe(c, ctx.clone()); - } - Lookup::Checking - } - } - } - - pub(super) enum Decision { - Done(Lookup), - /// These candidates are to be probed (their real files are marked as being - /// probed). - Probe(Vec), - } - - /// What the verdicts say of the candidates; files without one are to be probed. - /// The files that did not start are said once (then tried again). - pub(super) fn decide(s: &mut State) -> Decision { - let mut unfit = None; - let mut checking = false; - let mut to_probe = Vec::new(); - for c in &s.candidates { - if stamp(&c.real).is_none() { - continue; - } - let said = |name: Option<&String>, why| Unfit { - name: name.cloned().unwrap_or_else(|| c.label.clone()), - from_settings: c.from_settings, - why, - }; - if s.checking.contains(&c.real) { - checking = true; - } else if let Some((why, name)) = s.failed.get(&c.real) { - unfit.get_or_insert_with(|| said(name.as_ref(), *why)); - } else { - match fresh(s, &c.real) { - Some(v) if v.same => { - let ready = EngineLocation::Program(c.path.clone()); - return Decision::Done(Lookup::Ready(ready)); - } - Some(v) => { - let why = if v.name.as_deref() == Some(STOCKFISH_19) { - Why::Differs - } else { - Why::Other - }; - unfit.get_or_insert_with(|| said(v.name.as_ref(), why)); - } - None => to_probe.push(c.clone()), - } - } - } - if !to_probe.is_empty() { - s.checking.extend(to_probe.iter().map(|c| c.real.clone())); - return Decision::Probe(to_probe); - } - if checking { - return Decision::Done(Lookup::Checking); - } - s.failed.clear(); - Decision::Done(unfit.map_or(Lookup::None, Lookup::Unfit)) - } - - /// Probes the engine on a thread of its own, started by the path it is known by - /// (a snap or a wrapper looks at the name it is started by), and keeps the verdict - /// for its real file. The engine dies with that thread (the program quitting in - /// the middle of a handshake leaves no process behind). - fn spawn_probe(c: Candidate, ctx: egui::Context) { - let real = c.real.clone(); - let limits = with(|s| s.limits); - let spawned = std::thread::Builder::new() - .name("review-engine-probe".into()) - .spawn({ - let real = real.clone(); - move || { - let stamp = stamp(&real); - let config = uci::EngineConfig { - nice: 10, - kill_with_parent: true, - ..uci::EngineConfig::new(&c.path) - }; - let quitting = || QUITTING.load(Ordering::Relaxed); - let probe = game_review::probe::probe(config, limits, &quitting); - if !quitting() { - record(&real, stamp, probe); - ctx.request_repaint(); - } - } - }); - match spawned { - Ok(t) => with(|s| { - s.threads.retain(|t| !t.is_finished()); - s.threads.push(t); - }), - Err(e) => record( - &real, - stamp(&real), - Err(game_review::JobFailure::Start(e.to_string())), - ), - } - } - - pub(super) fn record( - real: &Path, - stamp: Option<(u64, u64)>, - probe: Result, - ) { - with(|s| { - s.checking.remove(real); - let Some((size, modified)) = stamp else { - return; - }; - match probe { - // Not remembered: tried again at the next request. - Ok(p) if p.timed_out => { - s.failed.insert(real.to_path_buf(), (Why::TimedOut, p.name)); - } - Ok(p) => { - s.known.insert( - real.to_path_buf(), - Verdict { - size, - modified, - same: p.same(), - name: p.name, - }, - ); - save(s); - } - Err(_) => { - s.failed.insert(real.to_path_buf(), (Why::NotStarted, None)); - } - } - }); - } - - pub(super) fn name_fits(path: &Path, name: &str) -> bool { - let own = crate::engines::own_stockfish() - .is_some_and(|EngineLocation::Program(p)| p.as_path() == path); - if own || name == STOCKFISH_19 { - return true; - } - let real = path.canonicalize().unwrap_or_else(|_| path.to_path_buf()); - with(|s| { - if s.known.remove(&real).is_some() { - save(s); - } - }); - false - } - - /// How long the program waits for the probes when it quits. - const QUIT_WAIT: std::time::Duration = std::time::Duration::from_secs(2); - - pub(super) fn shutdown() { - QUITTING.store(true, Ordering::Relaxed); - let threads = with(|s| std::mem::take(&mut s.threads)); - // A probe in a search gives up within a tenth of a second and quits its engine; - // one in a hung handshake is not waited for: its engine dies with its thread - // when the program ends (`kill_with_parent`). - let deadline = std::time::Instant::now() + QUIT_WAIT; - for t in threads { - while !t.is_finished() && std::time::Instant::now() < deadline { - std::thread::sleep(std::time::Duration::from_millis(20)); - } - if t.is_finished() { - let _ = t.join(); - } - } - } - - #[cfg(test)] - pub(super) fn reset(candidates: Vec) { - let mut s = state().lock().unwrap_or_else(|e| e.into_inner()); - *s = State { - candidates, - loaded: true, - limits: ProbeLimits { - search: std::time::Duration::from_millis(300), - total: std::time::Duration::from_secs(2), - }, - ..State::default() - }; - } -} - -#[cfg(all(test, not(web)))] -mod tests { - use super::native::{Candidate, Kept, Verdict, lookup_without_own, read_kept, reset, verified}; - use super::{EngineLocation, Lookup, Unfit, Why, name_fits}; - use std::path::{Path, PathBuf}; - use std::time::{Duration, Instant}; - - fn fake() -> PathBuf { - let fake = PathBuf::from(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../target/debug/fake_uci" - )); - assert!( - fake.exists(), - "build the fake engine first: cargo build -p uci --bin fake_uci" - ); - fake - } - - /// A script starting the fake engine named `name` that answers the probe with the - /// reference, `nodes_delta` nodes more. - fn engine(dir: &Path, file: &str, name: &str, nodes_delta: u64) -> PathBuf { - use game_review::probe::{PROBE_POSITIONS, REFERENCE}; - let mut args = vec![format!("--name '{name}'")]; - for (fen, (best, score, nodes)) in PROBE_POSITIONS.iter().zip(REFERENCE) { - let uci::Score::Cp(cp) = score else { - unreachable!("the reference scores are in centipawns") - }; - let marker = fen.split(' ').next().unwrap_or_default(); - args.push(format!( - "--answer '{marker}' 'cp {cp} nodes {} pv {best}'", - nodes + nodes_delta - )); - } - let path = dir.join(file); - let script = format!( - "#!/bin/sh\nexec '{}' {}\n", - fake().display(), - args.join(" ") - ); - std::fs::write(&path, script).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - path - } - - fn settle(ctx: &egui::Context) -> Lookup { - let deadline = Instant::now() + Duration::from_secs(10); - loop { - let l = lookup_without_own(ctx); - if l != Lookup::Checking || Instant::now() > deadline { - return l; - } - std::thread::sleep(Duration::from_millis(20)); - } - } - - fn unfit(name: &str, from_settings: bool, why: Why) -> Lookup { - Lookup::Unfit(Unfit { - name: name.into(), - from_settings, - why, - }) - } - - /// One test: the state is global. - #[test] - fn a_users_stockfish_19_is_taken_only_when_it_searches_as_ours() { - let dir = std::env::temp_dir().join(format!("cp-review-engine-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let ctx = egui::Context::default(); - let differs = engine(&dir, "sf-other", "Stockfish 19", 1); - let same = engine(&dir, "sf-same", "Stockfish 19", 0); - let named = engine(&dir, "sf-18", "Stockfish 18", 0); - let settings = |p: &PathBuf, label: &str| Candidate::new(p.clone(), label.into(), true); - - // No engine of the user's. - reset(Vec::new()); - assert_eq!(settle(&ctx), Lookup::None); - - // A Stockfish 19 searching otherwise (one node more): not taken. - reset(vec![settings(&differs, "My engine")]); - assert_eq!(lookup_without_own(&ctx), Lookup::Checking); - assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::Differs)); - assert_eq!(verified(), None); - - // Another name: turned down (without a search); from `PATH` it says so. - reset(vec![Candidate::new( - named.clone(), - "/usr/bin/x".into(), - false, - )]); - assert_eq!(settle(&ctx), unfit("Stockfish 18", false, Why::Other)); - - // An engine that does not start: its name from the settings; not remembered, - // so the next request tries it again. - let broken = dir.join("broken"); - std::fs::write(&broken, "not a program").unwrap(); - reset(vec![settings(&broken, "Broken one")]); - assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); - assert_eq!(lookup_without_own(&ctx), Lookup::Checking); - assert_eq!(settle(&ctx), unfit("Broken one", true, Why::NotStarted)); - - // A «Stockfish 19» that does not finish in time: said once, not remembered. - let slow = dir.join("sf-slow"); - let script = format!( - "#!/bin/sh\nexec '{}' --name 'Stockfish 19' --ignore-nodes\n", - fake().display() - ); - std::fs::write(&slow, script).unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&slow, std::fs::Permissions::from_mode(0o755)).unwrap(); - } - reset(vec![settings(&slow, "Slow")]); - assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::TimedOut)); - assert_eq!(lookup_without_own(&ctx), Lookup::Checking); - assert_eq!(settle(&ctx), unfit("Stockfish 19", true, Why::TimedOut)); - - // Started by the name it is known by (a wrapper looking at its name), the - // verdict kept for the real file. - #[cfg(unix)] - { - let picky = dir.join("picky"); - let script = format!( - "#!/bin/sh\n[ \"$(basename \"$0\")\" = sf-launch ] || exit 3\nexec '{}'\n", - same.display() - ); - std::fs::write(&picky, script).unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&picky, std::fs::Permissions::from_mode(0o755)).unwrap(); - let launch = dir.join("sf-launch"); - std::os::unix::fs::symlink(&picky, &launch).unwrap(); - reset(vec![settings(&launch, "Launcher")]); - assert_eq!( - settle(&ctx), - Lookup::Ready(EngineLocation::Program(launch.clone())) - ); - } - - // The reference answers: taken, even after another engine in the list. - reset(vec![settings(&differs, "A"), settings(&same, "B")]); - let ready = Lookup::Ready(EngineLocation::Program(same.clone())); - assert_eq!(settle(&ctx), ready); - assert_eq!(verified(), Some(EngineLocation::Program(same.clone()))); - // Remembered: no second probe. - assert_eq!(lookup_without_own(&ctx), ready); - - // A link to it: the real file's verdict, nothing probed again. - #[cfg(unix)] - { - let link = dir.join("link-to-same"); - std::os::unix::fs::symlink(&same, &link).unwrap(); - super::native::set_candidates(vec![settings(&link, "Link")]); - assert_eq!( - lookup_without_own(&ctx), - Lookup::Ready(EngineLocation::Program(link.clone())) - ); - super::native::set_candidates(vec![settings(&same, "B")]); - } - - // At a job's start it says another name (a wrapper changed): forgotten. - assert!(name_fits(&same, "Stockfish 19")); - assert!(!name_fits(&same, "Stockfish 18")); - assert_eq!(verified(), None); - assert_eq!(settle(&ctx), ready); - - // The file changed: probed again (a changed size). - let text = std::fs::read_to_string(&same).unwrap(); - std::fs::write(&same, format!("{text}\n")).unwrap(); - assert_eq!(verified(), None); - assert_eq!(lookup_without_own(&ctx), Lookup::Checking); - assert_eq!(settle(&ctx), ready); - - let _ = std::fs::remove_dir_all(&dir); - } - - /// The engines of the games against the computer are never candidates, whatever - /// the settings say; the analysis engines are, the active one first. - #[test] - fn play_engines_are_never_probed() { - use crate::settings::{EngineConfig, Settings}; - let rodent = crate::rodent_download::dir() - .expect("a data folder") - .join("rodent_v"); - let rodent4 = crate::rodent4_download::dir() - .expect("a data folder") - .join("rodent4"); - let mine = PathBuf::from("/opt/engines/stockfish-19"); - let other = PathBuf::from("/opt/engines/komodo"); - let settings = Settings { - engines: vec![ - EngineConfig::new("Rodent".into(), rodent), - EngineConfig::new("Komodo".into(), other.clone()), - EngineConfig::new("Rodent IV".into(), rodent4), - EngineConfig::new("Mine".into(), mine.clone()), - ], - active_engine: Some(3), - ..Settings::default() - }; - let found: Vec<(PathBuf, bool)> = super::native::candidates(&settings) - .into_iter() - .map(|c| (c.path, c.from_settings)) - .filter(|(_, from_settings)| *from_settings) - .collect(); - assert_eq!(found, vec![(mine, true), (other, true)]); - } - - /// Verdicts kept with another reference (another probe) are not trusted. - #[test] - fn verdicts_of_another_reference_are_dropped() { - let verdict = Verdict { - size: 1, - modified: 2, - same: true, - name: Some("Stockfish 19".into()), - }; - let kept = |reference: String| { - serde_json::to_vec(&Kept { - reference, - engines: [(PathBuf::from("/x/stockfish"), verdict.clone())].into(), - }) - .unwrap() - }; - let ours = read_kept(&kept(game_review::probe::reference_key())); - assert_eq!(ours.get(Path::new("/x/stockfish")), Some(&verdict)); - assert!(read_kept(&kept("0000000000000000".into())).is_empty()); - // The first version's file (a bare map): dropped too. - assert!( - read_kept(br#"{"/x/stockfish":{"size":1,"modified":2,"same":true,"name":null}}"#) - .is_empty() - ); - } -} diff --git a/apps/desktop/src/rodent4_download.rs b/apps/desktop/src/rodent4_download.rs index 6138de4..63a104d 100644 --- a/apps/desktop/src/rodent4_download.rs +++ b/apps/desktop/src/rodent4_download.rs @@ -8,9 +8,7 @@ use std::path::PathBuf; use std::sync::atomic::AtomicBool; -#[cfg(not(web))] -use crate::engine_download::fetch; -use crate::engine_download::{Asset, Download, Failure, Stage, already, disk}; +use crate::engine_download::{Asset, Download, Failure, Stage, already, disk, fetch}; use ::play::rodent::{BOOK_NAMES, FILES, file_url}; /// This platform's build: the release of our builds it is in (the macOS build of @@ -106,18 +104,10 @@ pub fn remove() -> std::io::Result<()> { } } -#[cfg(not(web))] pub fn start(ctx: &egui::Context) -> Download { Download::spawn(ctx, total(), run) } -/// A browser downloads no engine programs. -#[cfg(web)] -pub fn start(_ctx: &egui::Context) -> Download { - Download::unsupported() -} - -#[cfg(not(web))] fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let (tag, bin) = binary().ok_or(Failure::Unsupported)?; let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; diff --git a/apps/desktop/src/rodent_download.rs b/apps/desktop/src/rodent_download.rs index 6df8893..c7a6dbc 100644 --- a/apps/desktop/src/rodent_download.rs +++ b/apps/desktop/src/rodent_download.rs @@ -7,9 +7,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::AtomicBool; -#[cfg(not(web))] -use crate::engine_download::fetch; -use crate::engine_download::{Asset, Download, Failure, Stage, disk}; +use crate::engine_download::{Asset, Download, Failure, Stage, disk, fetch}; const TAG: &str = "Rodent_v_1.2"; @@ -79,18 +77,10 @@ pub fn remove() -> std::io::Result<()> { } } -#[cfg(not(web))] pub fn start(ctx: &egui::Context) -> Download { Download::spawn(ctx, ARCHIVE.size, run) } -/// A browser downloads no engine programs. -#[cfg(web)] -pub fn start(_ctx: &egui::Context) -> Download { - Download::unsupported() -} - -#[cfg(not(web))] fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result { let bin = binary().ok_or(Failure::Unsupported)?; let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?; @@ -118,7 +108,6 @@ fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result result } -#[cfg(not(web))] /// Takes this platform's engine and the folders it reads (personalities, nets, books) /// out of the archive; the other builds and the pictures of the manual stay out. fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { @@ -163,7 +152,6 @@ fn unpack(archive: &Path, dir: &Path, bin: &str) -> Result { /// Starts the engine once from its folder and waits for its name: it runs here (the /// release needs AVX2: an older processor fails this). -#[cfg(not(web))] pub(crate) fn check_runs(exe: &Path) -> Result<(), Failure> { use std::io::Write; let mut cmd = std::process::Command::new(exe); diff --git a/apps/desktop/src/settings.rs b/apps/desktop/src/settings.rs index e35a903..40493b3 100644 --- a/apps/desktop/src/settings.rs +++ b/apps/desktop/src/settings.rs @@ -53,23 +53,13 @@ impl EngineConfig { /// Executable to start; `None` if ChessPenguin's Stockfish is neither bundled nor /// downloaded yet (it is offered for download then). - pub fn executable(&self) -> Option { + pub fn executable(&self) -> Option { if self.builtin { crate::engines::own_stockfish() } else { - // A browser runs no engine programs: there are none but its own. - #[cfg(not(web))] - return Some(crate::engines::EngineLocation::Program(self.path.clone())); - #[cfg(web)] - None + Some(self.path.clone()) } } - - /// Whether the engine can be started: ChessPenguin's Stockfish is there (in a - /// browser: downloaded into it), or the file of another engine. - pub fn present(&self) -> bool { - self.executable().is_some_and(|l| l.present()) - } } /// Piece animation, with Lichess's durations. @@ -122,18 +112,17 @@ pub struct Settings { pub sound_set: SoundSet, pub volume: f32, pub dark_mode: bool, - /// The width of the opening-training panel dragged by the user, in points; `None`: - /// the default for the window. - pub opening_side_width: Option, pub language: Lang, pub engines: Vec, pub active_engine: Option, pub show_best_arrow: bool, /// Recently opened PGN files, most recent first. pub databases: Vec, + /// Whole-game analysis options. + pub review: ReviewSettings, /// The first-start engine discovery has run (see `engines::first_run_setup`). pub engines_discovered: bool, - /// The sample databases were put on the shelf (see `examples::setup`). + /// The sample databases were put on the shelf (see `examples::first_run_setup`). pub examples_added: bool, /// Ask GitHub for a newer release at start (Settings → About). pub check_updates: bool, @@ -160,94 +149,54 @@ pub struct Settings { pub record_games: bool, /// Who played on this computer, the last first (`player_games.rs`). pub players: Vec, - /// Preparing against an opponent (docs/design/opponent-prep.md). - pub prep: PrepSettings, - pub repertoire_flow_version: u8, - /// Last training mode and queue of each opening repertoire. - pub repertoire_modes: std::collections::HashMap< - String, - ( - trainer::repertoire::TrainingMode, - trainer::repertoire::QueueMode, - ), - >, - #[serde(default)] - pub repertoire_priorities: - std::collections::HashMap, - #[serde(default)] - pub repertoire_context_policies: - std::collections::HashMap, - /// Hints shown until the user reacts (docs/design/tasks-42-43-2026-11-27.md §43.3). - pub hints: Hints, } -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +/// Options of the whole-game analysis (the engine is the active one). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] -pub struct Hints { - /// «Arrows and circles: the right mouse button on the board» above the notation. - pub board_shapes: Hint, +pub struct ReviewSettings { + /// Index into [`REVIEW_QUALITY`]. + pub quality: usize, + pub threads: u32, + pub hash_mb: u32, + /// An analysis was started from the dialog once: «Analyse» starts the next one with + /// these options at once (the dialog stays for «Analyse again…»). + pub chosen: bool, } -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct Hint { - /// Closed, or what it tells was done: never shown again. - pub done: bool, - /// Games it was shown in without a reaction. - pub shown: u32, -} - -impl Hint { - /// Shown in this many games without a reaction, the hint goes by itself. - pub const SHOWS: u32 = 3; - - /// A game opens where the hint can stand: whether it is shown there. A show counts - /// once per game (`fresh`: the game was not shown the hint before in this session); - /// such a game keeps it, the last counted one too. - pub fn offer(&mut self, fresh: bool) -> bool { - if self.done { - return false; +impl Default for ReviewSettings { + fn default() -> Self { + Self { + quality: 1, + threads: default_threads(), + hash_mb: default_hash(), + chosen: false, } - if !fresh { - return true; - } - if self.shown >= Self::SHOWS { - return false; - } - self.shown += 1; - true } } -/// Options of the opponent preparation; its engine search is the game analysis's. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct PrepSettings { - /// Unused legacy book choice, preserved when old settings are saved again. - pub book: Option, - /// Plies of the opening the report looks at. - pub plies: usize, - /// Which of the player's games. - pub period: prep::Period, - /// Moves with fewer games fold into «other moves». - pub branches_from: u32, - /// Inaccuracies (?!) are shown with the mistakes and blunders. - pub inaccuracies: bool, - /// The order of each table of the screen. - pub sorts: crate::prep_ui::PrepSorts, -} +/// Search effort per position: (label, nodes). +pub const REVIEW_QUALITY: [(&str, u64); 3] = [ + ("Fast", 250_000), + ("Normal", 1_000_000), + ("Deep", 3_000_000), +]; -impl Default for PrepSettings { - fn default() -> Self { - Self { - book: None, - plies: 20, - period: prep::Period::All, - branches_from: 3, - inaccuracies: true, - sorts: Default::default(), +impl ReviewSettings { + /// Options other than the defaults were chosen in the dialog (before `chosen` was + /// kept, 1.5): they count as chosen. + pub fn note_earlier_choice(&mut self) { + let default = ReviewSettings::default(); + if (self.quality, self.threads, self.hash_mb) + != (default.quality, default.threads, default.hash_mb) + { + self.chosen = true; } } + + pub fn nodes(&self) -> u64 { + REVIEW_QUALITY[self.quality.min(REVIEW_QUALITY.len() - 1)].1 + } } impl Default for Settings { @@ -264,12 +213,12 @@ impl Default for Settings { sound_set: SoundSet::default(), volume: 0.7, dark_mode: true, - opening_side_width: None, language: Lang::default(), engines: Vec::new(), active_engine: None, show_best_arrow: true, databases: Vec::new(), + review: ReviewSettings::default(), engines_discovered: false, examples_added: false, check_updates: true, @@ -284,40 +233,20 @@ impl Default for Settings { players: Vec::new(), rating: None, play: Default::default(), - prep: PrepSettings::default(), - repertoire_modes: Default::default(), - repertoire_priorities: Default::default(), - repertoire_context_policies: Default::default(), - repertoire_flow_version: 0, - hints: Hints::default(), } } } impl Settings { - pub fn migrate_repertoire_flow(&mut self) -> bool { - if self.repertoire_flow_version >= 1 { - return false; - } - for (_, queue) in self.repertoire_modes.values_mut() { - if matches!( - queue, - trainer::repertoire::QueueMode::Practice - | trainer::repertoire::QueueMode::SpacedRepetition - ) { - *queue = trainer::repertoire::QueueMode::SpacedRepetition; - } - } - self.repertoire_flow_version = 1; - true - } pub fn config_dir() -> Option { - crate::platform::config_dir() + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.config_dir().to_path_buf()) } /// `~/.cache/chesspenguin` (derived data that can be deleted at any time). pub fn cache_dir() -> Option { - crate::platform::cache_dir() + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.cache_dir().to_path_buf()) } fn file() -> Option { @@ -329,14 +258,18 @@ impl Settings { return Self::first_start(); }; migrate_legacy_config(&path); - match crate::platform::fs::read(&path) { - Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| { - eprintln!( - "settings: cannot parse {}: {e}; using defaults", - path.display() - ); - Self::default() - }), + match std::fs::read(&path) { + Ok(bytes) => { + let mut s: Settings = serde_json::from_slice(&bytes).unwrap_or_else(|e| { + eprintln!( + "settings: cannot parse {}: {e}; using defaults", + path.display() + ); + Self::default() + }); + s.review.note_earlier_choice(); + s + } Err(e) if e.kind() == std::io::ErrorKind::NotFound => Self::first_start(), Err(_) => Self::default(), } @@ -363,33 +296,15 @@ impl Settings { self.active_engine.and_then(|i| self.engines.get(i)) } - /// Puts the database first on the shelf; a database there already by another path - /// to the same file (a link) keeps its path. Returns the path on the shelf. - /// Puts `path` at the end of the shelf, unless it is there: a database made in the - /// background appears without moving the cards (task 42). - pub fn add_database_last(&mut self, path: &Path) { - let real = |p: &Path| std::fs::canonicalize(p).ok(); - let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path)); - if !self.databases.iter().any(same) { - self.databases.push(path.to_path_buf()); - } - } - - pub fn touch_database(&mut self, path: &Path) -> PathBuf { - let real = |p: &Path| std::fs::canonicalize(p).ok(); - let same = |p: &PathBuf| p == path || real(p).is_some_and(|r| Some(r) == real(path)); - let kept = match self.databases.iter().position(same) { - Some(i) => self.databases.remove(i), - None => path.to_path_buf(), - }; - self.databases.insert(0, kept.clone()); - kept + pub fn touch_database(&mut self, path: &Path) { + self.databases.retain(|p| p != path); + self.databases.insert(0, path.to_path_buf()); } } /// Copies settings of the pre-rename build (`chessbase-linux`) once, if the new file is absent. fn migrate_legacy_config(new_file: &Path) { - if crate::platform::fs::exists(new_file) { + if new_file.exists() { return; } let legacy = directories::ProjectDirs::from("org", "chessbase-linux", "chessbase-linux") @@ -403,200 +318,27 @@ fn migrate_legacy_config(new_file: &Path) { /// Writes via a temp file in the same directory and renames over the target. pub fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - crate::platform::fs::write_atomic(path, bytes) + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension(format!("tmp{}", std::process::id())); + std::fs::write(&tmp, bytes)?; + std::fs::rename(&tmp, path).inspect_err(|_| { + let _ = std::fs::remove_file(&tmp); + }) } #[cfg(test)] mod tests { use super::*; - /// A database made in the background goes to the end; opening it brings it first. #[test] - fn a_copied_database_goes_to_the_end_of_the_shelf() { - let mut s = Settings { - databases: vec![PathBuf::from("/a.pgn"), PathBuf::from("/b.pgn")], - ..Default::default() - }; - s.add_database_last(Path::new("/new.pgn")); - s.add_database_last(Path::new("/a.pgn")); - assert_eq!( - s.databases, - [ - PathBuf::from("/a.pgn"), - PathBuf::from("/b.pgn"), - PathBuf::from("/new.pgn") - ] - ); - s.touch_database(Path::new("/new.pgn")); - assert_eq!(s.databases[0], PathBuf::from("/new.pgn")); - } - - #[test] - fn a_hint_goes_after_three_games_without_a_reaction() { - let mut hint = Hint::default(); - assert!(hint.offer(true)); - // The same game opened again in the session: shown, not counted. - assert!(hint.offer(false)); - assert!(hint.offer(true)); - assert!(hint.offer(true)); - assert_eq!(hint.shown, 3); - // A fourth game: gone; a game already shown in the session keeps it. - assert!(!hint.offer(true)); - assert!(hint.offer(false)); - assert_eq!(hint.shown, 3); - } - - #[test] - fn a_hint_done_is_never_shown() { - let mut hint = Hint { - done: true, - shown: 0, - }; - assert!(!hint.offer(true)); - assert_eq!(hint.shown, 0); - } - - #[test] - fn hints_survive_saving_and_old_settings_have_none() { - let mut s = Settings::default(); - s.hints.board_shapes = Hint { - done: false, - shown: 2, - }; - let json = serde_json::to_string(&s).unwrap(); - let back: Settings = serde_json::from_str(&json).unwrap(); - assert_eq!(back.hints, s.hints); - let old: Settings = serde_json::from_str(r#"{"show_coords": false}"#).unwrap(); - assert_eq!(old.hints, Hints::default()); - } - - /// A database put on the shelf again by a link to its file stays itself, once. - #[cfg(unix)] - #[test] - fn a_link_to_a_database_on_the_shelf_does_not_add_it_twice() { - let dir = std::env::temp_dir().join(format!("cp-shelf-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let (base, other, link) = (dir.join("a.pgn"), dir.join("b.pgn"), dir.join("link.pgn")); - std::fs::write(&base, "").unwrap(); - std::fs::write(&other, "").unwrap(); - std::os::unix::fs::symlink(&base, &link).unwrap(); - let mut s = Settings::default(); - s.databases.clear(); - assert_eq!(s.touch_database(&base), base); - assert_eq!(s.touch_database(&other), other); - assert_eq!(s.touch_database(&link), base); - assert_eq!(s.databases, vec![base.clone(), other.clone()]); - // A database gone from the disk is still told by its path. - let gone = dir.join("gone.pgn"); - s.touch_database(&gone); - assert_eq!(s.touch_database(&gone), gone); - assert_eq!(s.databases.len(), 3); - let _ = std::fs::remove_dir_all(&dir); - } - - /// The settings of 1.x kept the engine options of the game analysis and the - /// quality of the preparation: they are read without them now. - #[test] - fn settings_with_the_old_analysis_options_are_read() { - let old = r#"{ - "language": "Ru", - "review": {"quality": 2, "threads": 12, "hash_mb": 1024, "chosen": true}, - "prep": {"quality": 1, "plies": 16, "chosen": true, "book": "/db/book.pgn"} - }"#; - let s: Settings = serde_json::from_str(old).expect("read"); - assert_eq!(s.language, Lang::Ru); - assert_eq!(s.prep.plies, 16); - assert_eq!(s.prep.book, Some(PathBuf::from("/db/book.pgn"))); - let json = serde_json::to_string(&s).expect("written"); - assert!(!json.contains("\"review\"") && !json.contains("quality")); - assert!(!json.contains("\"chosen\"")); - assert!(json.contains("\"book\":\"/db/book.pgn\"")); - } -} - -#[cfg(test)] -mod repertoire_flow_tests { - use super::*; - use trainer::repertoire::{LearningPriority, QueueMode, TrainingMode}; - #[test] - fn old_training_preferences_migrate_once_without_resetting_color_or_custom_settings() { - let mut settings = Settings::default(); - settings.repertoire_modes.insert( - "old".into(), - (TrainingMode::Black, QueueMode::SpacedRepetition), - ); - assert!(settings.migrate_repertoire_flow()); - assert_eq!( - settings.repertoire_modes["old"], - (TrainingMode::Black, QueueMode::SpacedRepetition) - ); - settings.repertoire_modes.insert( - "review".into(), - (TrainingMode::White, QueueMode::ReviewInOrder), - ); - settings.repertoire_modes.get_mut("old").unwrap().1 = QueueMode::SpacedRepetition; - assert!(!settings.migrate_repertoire_flow()); - assert_eq!( - settings.repertoire_modes["old"].1, - QueueMode::SpacedRepetition - ); - assert_eq!( - settings.repertoire_modes["review"].1, - QueueMode::ReviewInOrder - ); - } - - #[test] - fn learning_mode_and_priority_roundtrip_and_default_for_legacy_settings() { - let mut settings = Settings::default(); - settings.repertoire_modes.insert( - "opening".into(), - (TrainingMode::Black, QueueMode::LeastRecent), - ); - settings - .repertoire_priorities - .insert("opening".into(), LearningPriority::MainLinesFirst); - - let json = serde_json::to_string(&settings).unwrap(); - let restored: Settings = serde_json::from_str(&json).unwrap(); - assert_eq!( - restored.repertoire_modes["opening"], - (TrainingMode::Black, QueueMode::LeastRecent) - ); - assert_eq!( - restored.repertoire_priorities["opening"], - LearningPriority::MainLinesFirst - ); - - let legacy: Settings = serde_json::from_str("{}").unwrap(); - assert!(legacy.repertoire_priorities.is_empty()); - } - - #[test] - fn context_policies_roundtrip_and_default_for_legacy_json() { - let policy = trainer::repertoire::LearningContextPolicy { - reinforce_minimum_correct: 5, - reinforce_minimum_days: Some(14), - dont_show_start_moves_threshold: 8, - use_fixed_piece_speed: false, - move_speed_adjustment: 1.5, - consider_leadup_moves: true, - }; - let mut settings = Settings::default(); - settings - .repertoire_context_policies - .insert("opening".into(), policy); - - let json = serde_json::to_string_pretty(&settings).unwrap(); - let restored: Settings = serde_json::from_str(&json).unwrap(); - assert_eq!(restored.repertoire_context_policies["opening"], policy); - - let legacy = r#"{ - "repertoire_modes": {}, - "repertoire_priorities": {} - }"#; - let restored: Settings = serde_json::from_str(legacy).unwrap(); - assert!(restored.repertoire_context_policies.is_empty()); + fn options_chosen_before_count_as_chosen() { + let mut r = ReviewSettings::default(); + r.note_earlier_choice(); + assert!(!r.chosen, "the defaults: never chosen"); + r.quality = 2; + r.note_earlier_choice(); + assert!(r.chosen); } } diff --git a/apps/desktop/src/settings_ui.rs b/apps/desktop/src/settings_ui.rs index e6cea5f..19bf50f 100644 --- a/apps/desktop/src/settings_ui.rs +++ b/apps/desktop/src/settings_ui.rs @@ -15,20 +15,10 @@ pub enum Tab { Sound, Interface, Translation, - /// What the web version keeps in the browser. - #[cfg(web)] - BrowserData, About, } pub enum SettingsAction { - /// All of «My games» as a downloaded PGN. - #[cfg(web)] - DownloadMyGames, - /// Ask the browser to keep the site's data for good. - #[cfg(web)] - KeepData, - #[cfg(not(web))] AddEngine, /// Download the official Stockfish (decision 14). DownloadEngine, @@ -39,13 +29,10 @@ pub enum SettingsAction { /// The active engine (or its options) changed; a running analysis should restart. EngineChanged, /// Ask now whether a newer version is out. - #[cfg(not(web))] CheckUpdates, /// Choose the folder for new databases. - #[cfg(not(web))] PickBaseFolder, /// Open the update window. - #[cfg(not(web))] OpenUpdate, } @@ -86,17 +73,7 @@ impl SettingsWindow { let mut actions = Vec::new(); let mut changed = false; let mut open = self.open; - // A real, unpainted click target: the opening click belongs to its - // original widget, and the dismissing click never belongs to the board. - let backdrop = open.then(|| { - let rect = ctx.viewport_rect(); - egui::Area::new(egui::Id::new("settings_backdrop")) - .fixed_pos(rect.min) - .sense(Sense::click()) - .show(ctx, |ui| ui.set_min_size(rect.size())) - .response - }); - let window = egui::Window::new(tr("Settings")) + egui::Window::new(tr("Settings")) .open(&mut open) .default_size(vec2(560.0, 680.0)) // Open at the right edge so the board stays visible for live preview. @@ -109,11 +86,7 @@ impl SettingsWindow { ui.selectable_value(&mut self.tab, Tab::Board, tr("Board & pieces")); ui.selectable_value(&mut self.tab, Tab::Sound, tr("Sound")); ui.selectable_value(&mut self.tab, Tab::Interface, tr("Interface")); - if crate::platform::CAPS.translation { - ui.selectable_value(&mut self.tab, Tab::Translation, tr("Translation")); - } - #[cfg(web)] - ui.selectable_value(&mut self.tab, Tab::BrowserData, tr("Browser data")); + ui.selectable_value(&mut self.tab, Tab::Translation, tr("Translation")); ui.selectable_value(&mut self.tab, Tab::About, tr("About")); }); ui.separator(); @@ -121,19 +94,40 @@ impl SettingsWindow { Tab::Engines => self.engines(ui, s, &mut actions, &mut changed), Tab::Board => board_tab(ui, s, &mut changed), Tab::Translation => changed |= translation.settings_tab(ui, s), - #[cfg(web)] - Tab::BrowserData => browser_data(ui, &mut actions), Tab::Sound => sound_tab(ui, s, &mut actions, &mut changed), Tab::About => { let (status, available) = (self.update_status.clone(), self.update_available.clone()); about_tab(ui, s.language, |ui| { - // Updates, right under the version (the web version is - // always the latest: a reload brings it). - #[cfg(not(web))] - updates(ui, s, &status, &available, &mut actions, &mut changed); - #[cfg(web)] - let _ = (ui, &status, &available); + // Updates, right under the version. + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + match (&available, &status) { + (Some(v), _) => { + let label = RichText::new(trf( + "⬆ Update to {v}…", + &[("v", v)], + )) + .color(ui.visuals().hyperlink_color); + if ui.button(label).clicked() { + actions.push(SettingsAction::OpenUpdate); + } + } + (None, Some(st)) => { + ui.label(RichText::new(st).weak()); + } + (None, None) => {} + } + if ui.button(tr("Check now")).clicked() { + actions.push(SettingsAction::CheckUpdates); + } + }); + changed |= ui + .checkbox(&mut s.check_updates, tr("Check for updates at start")) + .on_hover_text(tr( + "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", + )) + .changed(); }); } Tab::Interface => { @@ -177,19 +171,16 @@ impl SettingsWindow { RichText::new(tr("Written as the annotator of the games you add")) .weak(), ); - // A browser has no folders for databases. - #[cfg(not(web))] ui.horizontal(|ui| { ui.label(tr("Folder for new databases:")); let dir = crate::own_db::default_base_dir(s.new_database_dir.as_deref()); // Short, under the home folder; the whole path on hover. - let home = - directories::UserDirs::new().map(|u| u.home_dir().to_path_buf()); - let short = match home.as_ref().and_then(|h| dir.strip_prefix(h).ok()) { - Some(rest) => { - format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()) - } + let home = directories::UserDirs::new() + .map(|u| u.home_dir().to_path_buf()); + let short = match home.as_ref().and_then(|h| dir.strip_prefix(h).ok()) + { + Some(rest) => format!("~{}{}", std::path::MAIN_SEPARATOR, rest.display()), None => dir.display().to_string(), }; ui.label(RichText::new(short).weak()) @@ -207,12 +198,6 @@ impl SettingsWindow { } }); }); - if let (Some(backdrop), Some(window)) = (backdrop, window) { - ctx.set_sublayer(backdrop.layer_id, window.response.layer_id); - if backdrop.clicked_by(egui::PointerButton::Primary) { - open = false; - } - } self.open = open; (actions, changed) } @@ -259,8 +244,6 @@ impl SettingsWindow { { actions.push(SettingsAction::DownloadEngine); } - // A browser has no engine programs. - #[cfg(not(web))] if ui.button(tr("Choose engine file…")).clicked() { actions.push(SettingsAction::AddEngine); } @@ -314,7 +297,7 @@ impl SettingsWindow { ) .on_hover_text(p.display().to_string()); } else if let Some(p) = crate::engine_download::installed() { - let mb = crate::engine_download::installed_mb(); + let mb = std::fs::metadata(&p).map_or(0, |m| m.len() / 1_000_000); ui.label( RichText::new(trf( "Downloaded by ChessPenguin · {mb} MB", @@ -323,7 +306,7 @@ impl SettingsWindow { .small() .weak(), ) - .on_hover_text(p.to_string()); + .on_hover_text(p.display().to_string()); } else { ui.horizontal(|ui| { ui.label( @@ -349,7 +332,9 @@ impl SettingsWindow { let mut answer = None; let modal = egui::Modal::new(egui::Id::new("remove_engine")).show(ui.ctx(), |ui| { ui.set_width(360.0); - let mb = crate::engine_download::installed_mb(); + let mb = crate::engine_download::installed() + .and_then(|p| std::fs::metadata(p).ok()) + .map_or(0, |m| m.len() / 1_000_000); ui.label(trf( "Remove Stockfish 19? This frees {mb} MB. You can download it again at any time.", &[("mb", &mb)], @@ -397,8 +382,9 @@ impl SettingsWindow { ui.label(RichText::new(tr("Found on this computer:")).strong()); for cfg in found { ui.horizontal(|ui| { - let path = cfg.executable().map(|l| l.to_string()).unwrap_or_default(); - ui.label(&cfg.name).on_hover_text(path); + let path = cfg.executable().unwrap_or_default(); + ui.label(&cfg.name) + .on_hover_text(path.display().to_string()); if ui.button(tr("Add")).clicked() { s.engines.push(cfg); if s.active_engine.is_none() { @@ -438,8 +424,6 @@ impl SettingsWindow { }); } ui.add_space(6.0); - // A browser has no engine programs. - #[cfg(not(web))] ui.horizontal(|ui| { if ui .add_enabled( @@ -535,13 +519,6 @@ fn board_tab(ui: &mut Ui, s: &mut Settings, changed: &mut bool) { notation_section(ui, s, changed); ui.add_space(8.0); ui.label(RichText::new(tr("Board")).strong()); - // The hint above the notation goes away; what it told stays here, in sight. - ui.label( - RichText::new(tr( - "Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]).", - )) - .weak(), - ); ui.horizontal_wrapped(|ui| { for id in BoardThemeId::ALL { let t = id.theme(); @@ -790,236 +767,3 @@ fn sound_tab(ui: &mut Ui, s: &mut Settings, actions: &mut Vec, c }); }); } - -/// Updates in the About tab: the version out, «Check now», the check at start. -#[cfg(not(web))] -fn updates( - ui: &mut Ui, - s: &mut Settings, - status: &Option, - available: &Option, - actions: &mut Vec, - changed: &mut bool, -) { - ui.add_space(4.0); - ui.horizontal_wrapped(|ui| { - match (available, status) { - (Some(v), _) => { - let label = RichText::new(trf("⬆ Update to {v}…", &[("v", v)])) - .color(ui.visuals().hyperlink_color); - if ui.button(label).clicked() { - actions.push(SettingsAction::OpenUpdate); - } - } - (None, Some(st)) => { - ui.label(RichText::new(st).weak()); - } - (None, None) => {} - } - if ui.button(tr("Check now")).clicked() { - actions.push(SettingsAction::CheckUpdates); - } - }); - *changed |= ui - .checkbox(&mut s.check_updates, tr("Check for updates at start")) - .on_hover_text(tr( - "ChessPenguin asks its site which version is the latest; the site counts installations that run: only a random number of this installation, the version and the system are sent", - )) - .changed(); -} - -/// Settings → Browser data (docs/design/web-version.md §2.3): what is kept only in this -/// browser, how much room it takes and is left, and the way to take «My games» along. -#[cfg(web)] -fn browser_data(ui: &mut Ui, actions: &mut Vec) { - use crate::platform::{size_text, web}; - ui.label(tr( - "Everything below is stored only here, on this device. Files on disk are not changed.", - )); - ui.add_space(6.0); - if let Some((used, quota)) = web::storage::usage() { - ui.label(trf( - "Used {used} · free for the site {free}", - &[ - ("used", &size_text(used)), - ("free", &size_text(quota.saturating_sub(used))), - ], - )); - } - ui.horizontal(|ui| match web::storage::persisted() { - Some(true) => { - ui.label(tr("Persistent storage: on")); - } - _ => { - ui.label( - RichText::new(tr("Persistent storage: not allowed by the browser")) - .color(ui.visuals().warn_fg_color), - ); - if ui.button(tr("Ask the browser")).clicked() { - actions.push(SettingsAction::KeepData); - } - } - }); - ui.add_space(8.0); - egui::Grid::new("browser data") - .num_columns(3) - .spacing([16.0, 6.0]) - .show(ui, |ui| { - ui.label(trf( - "My games · {n}", - &[("n", &crate::i18n::games(crate::my_games::count()))], - )); - ui.label(size_text(crate::my_games::size())); - if ui.button(tr("Download all as PGN")).clicked() { - actions.push(SettingsAction::DownloadMyGames); - } - ui.end_row(); - if web::engine::ready() { - ui.label(tr("Stockfish 19 engine")); - ui.label(size_text(web::engine::WASM_BYTES)); - if ui.button(tr("Delete")).clicked() { - actions.push(SettingsAction::RemoveDownloaded); - } - ui.end_row(); - } - }); - ui.add_space(8.0); - ui.label( - RichText::new(tr( - "If you clear the site's data in the browser, all of this is lost. Download your games as PGN to keep them.", - )) - .weak(), - ); -} - -#[cfg(test)] -mod tests { - use super::*; - use egui::{Event, Modifiers, PointerButton, Pos2, Rect}; - - struct Screen { - ctx: egui::Context, - window: SettingsWindow, - settings: Settings, - opener: Rect, - clicks: usize, - } - - impl Screen { - fn new() -> Self { - let mut screen = Self { - ctx: Default::default(), - window: SettingsWindow::new(), - settings: Settings { - language: Lang::En, - ..Default::default() - }, - opener: Rect::NOTHING, - clicks: 0, - }; - screen.window.tab = Tab::Sound; - screen.frame(vec![]); - screen.click(screen.opener.center()); - screen.frame(vec![]); - assert!(screen.window.open); - assert_eq!(screen.clicks, 1); - screen - } - - fn frame(&mut self, events: Vec) -> egui::FullOutput { - let mut output = self.ctx.run_ui( - egui::RawInput { - screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1280.0, 900.0))), - events, - ..Default::default() - }, - |ui| { - let r = ui.button("Open settings"); - self.opener = r.rect; - if r.clicked() { - self.clicks += 1; - self.window.open = true; - } - self.window - .show(ui.ctx(), &mut self.settings, &mut Default::default()); - }, - ); - output.textures_delta.clear(); - output - } - - fn pointer(&mut self, pos: Pos2, button: PointerButton, pressed: bool) { - self.frame(vec![ - Event::PointerMoved(pos), - Event::PointerButton { - pos, - button, - pressed, - modifiers: Modifiers::NONE, - }, - ]); - } - - fn click(&mut self, pos: Pos2) { - self.pointer(pos, PointerButton::Primary, true); - self.pointer(pos, PointerButton::Primary, false); - } - - fn text(&mut self, label: &str) -> Pos2 { - self.frame(vec![]) - .shapes - .iter() - .find_map(|shape| match &shape.shape { - egui::Shape::Text(t) if t.galley.text() == label => { - Some(t.pos + 0.5 * t.galley.size()) - } - _ => None, - }) - .unwrap_or_else(|| panic!("missing visible label: {label}")) - } - } - - #[test] - fn only_an_outside_primary_click_dismisses_and_it_never_reaches_the_opener() { - let mut s = Screen::new(); - let outside = s.opener.center(); - s.pointer(outside, PointerButton::Secondary, true); - s.pointer(outside, PointerButton::Secondary, false); - assert!(s.window.open); - - let inside = s.text(tr("Move sounds")); - s.pointer(inside, PointerButton::Primary, true); - s.frame(vec![Event::PointerMoved(outside)]); - s.pointer(outside, PointerButton::Primary, false); - assert!(s.window.open); - s.pointer(outside, PointerButton::Primary, true); - assert!(s.window.open); - s.pointer(outside, PointerButton::Primary, false); - assert!(!s.window.open); - assert_eq!(s.clicks, 1); - } - - #[test] - fn settings_tabs_popup_items_and_titlebar_close_still_receive_clicks() { - let mut s = Screen::new(); - let interface = s.text(tr("Interface")); - s.click(interface); - assert!(s.window.tab == Tab::Interface); - let combo = s.text(Lang::En.label()); - let layer = s.ctx.layer_id_at(combo).unwrap(); - let rect = s.ctx.memory(|m| m.area_rect(layer.id)).unwrap(); - s.click(combo); - let choice = s.text(Lang::Kk.label()); - assert!(!rect.contains(choice), "exercise the overhanging popup"); - s.click(choice); - assert_eq!(s.settings.language, Lang::Kk); - assert!(s.window.open); - - s.frame(vec![]); - let title = s.text(tr("Settings")); - let layer = s.ctx.layer_id_at(title).unwrap(); - let rect = s.ctx.memory(|m| m.area_rect(layer.id)).unwrap(); - s.click(egui::pos2(rect.right() - 15.0, title.y)); - assert!(!s.window.open); - } -} diff --git a/apps/desktop/src/sound.rs b/apps/desktop/src/sound.rs index 9474fb1..cb10a76 100644 --- a/apps/desktop/src/sound.rs +++ b/apps/desktop/src/sound.rs @@ -1,19 +1,14 @@ -//! Sound playback: on a computer on a dedicated thread (missing audio devices are -//! tolerated silently); in a browser by its audio elements, each sound's file made once. +//! Sound playback on a dedicated thread; missing audio devices are tolerated silently. -#[cfg(not(web))] use std::io::Cursor; -#[cfg(not(web))] use std::sync::mpsc::{Sender, channel}; use crate::assets::{Sound, SoundSet, sound_bytes}; -#[cfg(not(web))] pub struct SoundPlayer { tx: Option>, } -#[cfg(not(web))] impl SoundPlayer { pub fn new() -> Self { let (tx, rx) = channel::<(SoundSet, Sound, f32)>(); @@ -55,45 +50,3 @@ impl SoundPlayer { } } } - -/// The sounds' files for the page's audio elements (`blob:` addresses), by the sound's -/// bytes (each sound is a file of its own). -#[cfg(web)] -pub struct SoundPlayer { - urls: std::cell::RefCell>, -} - -#[cfg(web)] -impl SoundPlayer { - pub fn new() -> Self { - Self { - urls: Default::default(), - } - } - - fn url(&self, bytes: &'static [u8]) -> Option { - let key = bytes.as_ptr() as usize; - if let Some(u) = self.urls.borrow().get(&key) { - return Some(u.clone()); - } - let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes)); - let opts = web_sys::BlobPropertyBag::new(); - opts.set_type("audio/ogg"); - let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).ok()?; - let url = web_sys::Url::create_object_url_with_blob(&blob).ok()?; - self.urls.borrow_mut().insert(key, url.clone()); - Some(url) - } - - /// Plays the sound; a browser that cannot (no audio, not allowed yet) stays silent. - pub fn play(&self, set: SoundSet, sound: Sound, volume: f32) { - let Some(url) = self.url(sound_bytes(set, sound)) else { - return; - }; - if let Ok(audio) = web_sys::HtmlAudioElement::new_with_src(&url) { - audio.set_volume(f64::from(volume.clamp(0.0, 1.0))); - // The promise fails when the page may not play yet: nothing to do then. - let _ = audio.play(); - } - } -} diff --git a/apps/desktop/src/translate.rs b/apps/desktop/src/translate.rs index ad63370..a4a0d2a 100644 --- a/apps/desktop/src/translate.rs +++ b/apps/desktop/src/translate.rs @@ -789,7 +789,6 @@ impl std::fmt::Display for Failure { } } -#[cfg(not(web))] pub fn agent(body_timeout: Duration) -> ureq::Agent { let config = ureq::Agent::config_builder() .user_agent(format!( @@ -884,34 +883,6 @@ impl Backend { } } -/// Why nothing is asked of a service in a browser: the web version has no machine -/// translation (its requests would block a thread the page does not have). -#[cfg(web)] -pub fn no_requests() -> Failure { - Failure::Offline("the web version makes no requests to translation services".into()) -} - -#[cfg(web)] -pub fn list_models(_base: &str, _key: Option<&str>, _local: bool) -> Result, Failure> { - Err(no_requests()) -} - -#[cfg(web)] -#[allow(clippy::too_many_arguments)] -fn chat( - _base: &str, - _key: Option<&str>, - _model: &str, - _json_mode: bool, - _local: bool, - _system: &str, - _user: &str, - _cancel: &AtomicBool, -) -> Result { - Err(no_requests()) -} - -#[cfg(not(web))] /// The models a key connection offers (`GET {base}/models`). pub fn list_models(base: &str, key: Option<&str>, local: bool) -> Result, Failure> { let mut req = agent(Duration::from_secs(30)).get(format!("{base}/models")); @@ -944,7 +915,6 @@ pub fn list_models(base: &str, key: Option<&str>, local: bool) -> Result Failure { if local { Failure::LocalDown @@ -969,7 +939,6 @@ fn status_failure(status: u16, body: &str, model: &str) -> Failure { } } -#[cfg(not(web))] #[allow(clippy::too_many_arguments)] fn chat( base: &str, @@ -1226,11 +1195,13 @@ impl Job { let cancel = Arc::new(AtomicBool::new(false)); let c = cancel.clone(); let ctx = ctx.clone(); - let _ = crate::platform::spawn("translate", move || { - run(&backend, target, &via, &context, texts, &c, &tx, &ctx); - let _ = tx.send(Event::Finished); - ctx.request_repaint(); - }); + let _ = std::thread::Builder::new() + .name("translate".into()) + .spawn(move || { + run(&backend, target, &via, &context, texts, &c, &tx, &ctx); + let _ = tx.send(Event::Finished); + ctx.request_repaint(); + }); Job { rx, cancel } } @@ -1630,7 +1601,7 @@ mod tests { ); let mut done = Vec::new(); let mut bad = Vec::new(); - let start = web_time::Instant::now(); + let start = std::time::Instant::now(); 'wait: while start.elapsed() < Duration::from_secs(20) { for e in job.poll() { match e { @@ -1682,7 +1653,7 @@ mod tests { texts.clone(), ); let mut done = Vec::new(); - let start = web_time::Instant::now(); + let start = std::time::Instant::now(); 'wait: while start.elapsed() < Duration::from_secs(20) { for e in job.poll() { match e { diff --git a/apps/desktop/src/translate_ui.rs b/apps/desktop/src/translate_ui.rs index fe85b0c..e3d0698 100644 --- a/apps/desktop/src/translate_ui.rs +++ b/apps/desktop/src/translate_ui.rs @@ -368,7 +368,7 @@ impl Hub { } let ok = c.result.is_ok(); if let Err(e) = &c.result { - crate::platform::log(&format!("translation check via {}: {e}", s.service_id())); + crate::graphics::log(&format!("translation check via {}: {e}", s.service_id())); } self.check_result = Some(c.result); let flow = self.resume || (self.setup_open && self.step == Step::Checking); @@ -1640,7 +1640,7 @@ impl GameTranslation { } } Event::Failed(f) => { - crate::platform::log(&format!("translation via {}: {f}", self.job_service)); + crate::graphics::log(&format!("translation via {}: {f}", self.job_service)); match f { Failure::PlanLimit => hub.chatgpt = ChatGptState::Limit, Failure::SignedOut => hub.chatgpt = ChatGptState::SignedOut, diff --git a/apps/desktop/src/viewed.rs b/apps/desktop/src/viewed.rs index 9f3cf91..693a50d 100644 --- a/apps/desktop/src/viewed.rs +++ b/apps/desktop/src/viewed.rs @@ -12,12 +12,13 @@ pub struct Viewed { impl Viewed { fn file() -> Option { - crate::platform::data_dir().map(|d| d.join("viewed.json")) + directories::ProjectDirs::from("io.github", "vrubelroman", "ChessPenguin") + .map(|d| d.data_dir().join("viewed.json")) } pub fn load() -> Viewed { let games = Self::file() - .and_then(|p| crate::platform::fs::read(&p).ok()) + .and_then(|p| std::fs::read(p).ok()) .and_then(|b| serde_json::from_slice::>(&b).ok()) .unwrap_or_default(); Viewed { diff --git a/apps/desktop/src/widgets.rs b/apps/desktop/src/widgets.rs index abac255..c79f65c 100644 --- a/apps/desktop/src/widgets.rs +++ b/apps/desktop/src/widgets.rs @@ -2,71 +2,6 @@ use egui::{Color32, Sense, Stroke, Ui, vec2}; -/// The application's settings action, shared by screen headers. -pub fn settings_button(ui: &mut Ui, compact: bool) -> egui::Response { - let tr = crate::i18n::tr; - ui.button(if compact { "⚙" } else { tr("⚙ Settings") }) - .on_hover_text(format!("{} (Ctrl+,)", tr("Settings"))) -} - -/// A section header: reserve global actions before laying out a long title. -/// Returns (back, settings). -#[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; - ui.horizontal(|ui| { - ui.set_min_height(26.0); - clicked.0 = ui.button(back).clicked(); - ui.separator(); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - clicked.1 = settings_button(ui, compact).clicked(); - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - ui.add(egui::Label::new(egui::RichText::new(title).heading()).truncate()) - .on_hover_text(title); - }); - }); - }); - clicked -} - -/// A 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| { - // 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 }) - .weak(), - ) - .truncate(), - ); - if !subtitle.is_empty() { - sub.on_hover_text(subtitle); - } - }); - }); - }); - ui.add_space(4.0); - 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 @@ -97,17 +32,6 @@ pub fn check_panel(name: &str, panel: &egui::Response) { } } -/// A sortable column's header: the title in bold, ▲/▼ when the table is ordered by -/// it (`Some(ascending)`); click to sort. -pub fn sort_header(ui: &mut Ui, label: &str, ascending: Option) -> egui::Response { - let arrow = match ascending { - Some(true) => " ⏶", - Some(false) => " ⏷", - None => "", - }; - ui.add(egui::Button::new(egui::RichText::new(format!("{label}{arrow}")).strong()).frame(false)) -} - /// Compact ✕ (e.g. to cancel a running task); the caller adds the tooltip. pub fn small_close_button(ui: &mut Ui) -> egui::Response { x_button(ui, vec2(22.0, 20.0), 4.5) @@ -151,23 +75,6 @@ pub fn primary(ui: &mut egui::Ui, label: &str) -> egui::Response { primary_wide(ui, label, 0.0) } -/// The king of a side, `size` points square: White's light with a dark outline, -/// Black's dark with a light one, the same in both themes (task 45; a font's ♔/♚ read -/// the other way round on a dark background). From the classic set, whatever the board's. -pub fn side_king(white: bool, size: f32) -> egui::Image<'static> { - let color = if white { - shakmaty::Color::White - } else { - shakmaty::Color::Black - }; - crate::assets::PieceSet::Cburnett - .image(shakmaty::Piece { - color, - role: shakmaty::Role::King, - }) - .fit_to_exact_size(egui::vec2(size, size)) -} - /// `primary()` at least `width` wide (a button whose label changes keeps its place). pub fn primary_wide(ui: &mut egui::Ui, label: &str, width: f32) -> egui::Response { ui.add( @@ -220,28 +127,3 @@ pub fn icon_button(ui: &mut Ui, check: bool, primary: bool) -> egui::Response { } resp } - -/// `text` cut to `max` characters, with «…» in the middle when longer (a file's or an -/// engine's name keeps its start and its end, where versions and extensions are). -pub fn shorten(text: &str, max: usize) -> String { - let n = text.chars().count(); - if n <= max || max < 3 { - return text.to_owned(); - } - let head = (max - 1) / 2; - let tail = max - 1 - head; - let start: String = text.chars().take(head).collect(); - let end: String = text.chars().skip(n - tail).collect(); - format!("{start}…{end}") -} - -#[cfg(test)] -mod shorten_tests { - #[test] - fn long_names_are_cut_in_the_middle() { - assert_eq!(super::shorten("Stockfish 19", 48), "Stockfish 19"); - assert_eq!(super::shorten("abcdefghij", 5), "ab…ij"); - assert_eq!(super::shorten("абвгдежзик", 7), "абв…зик"); - assert_eq!(super::shorten("abcdefghij", 7).chars().count(), 7); - } -} diff --git a/apps/web/Cargo.toml b/apps/web/Cargo.toml deleted file mode 100644 index 889099e..0000000 --- a/apps/web/Cargo.toml +++ /dev/null @@ -1,23 +0,0 @@ -[package] -name = "chesspenguin-web" -description = "ChessPenguin in a browser: the entry point of the web version (the interface is apps/desktop's)" -version.workspace = true -authors.workspace = true -repository.workspace = true -homepage.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -publish = false - -# Built for WebAssembly only (apps/web/build.sh); elsewhere the crate is empty. -[lib] -crate-type = ["cdylib"] - -[target.'cfg(target_family = "wasm")'.dependencies] -chesspenguin = { path = "../desktop" } -wasm-bindgen = "0.2.129" -wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location", "UrlSearchParams"] } -log = "0.4" -eframe.workspace = true diff --git a/apps/web/build.sh b/apps/web/build.sh deleted file mode 100755 index b17514a..0000000 --- a/apps/web/build.sh +++ /dev/null @@ -1,79 +0,0 @@ -#!/bin/sh -# Builds the web version into a folder served as the site's /app/ (docs/dev/web.md): -# -# apps/web/build.sh [out-dir] (default: target/web/app) -# PROFILE=release apps/web/build.sh (the default profile is `web`: small, slower to build) -# -# Needs: the target wasm32-unknown-unknown (rustup target add wasm32-unknown-unknown), -# wasm-bindgen-cli of the version in Cargo.lock (cargo install wasm-bindgen-cli --version …; -# WASM_BINDGEN= points at another binary), python3. wasm-opt (binaryen) makes the program -# smaller when it is there. -set -eu - -here=$(cd "$(dirname "$0")" && pwd) -root=$(cd "$here/../.." && pwd) -out=${1:-$root/target/web/app} -profile=${PROFILE:-web} -bindgen=${WASM_BINDGEN:-wasm-bindgen} - -want=$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/version = |"/, ""); print; exit }' "$root/Cargo.lock") -have=$("$bindgen" --version | awk '{ print $2 }') -if [ "$want" != "$have" ]; then - echo "wasm-bindgen $have, but Cargo.lock has $want: cargo install wasm-bindgen-cli --version $want" >&2 - exit 1 -fi - -cd "$root" -cargo build -p chesspenguin-web --target wasm32-unknown-unknown --profile "$profile" -wasm="$root/target/wasm32-unknown-unknown/$profile/chesspenguin_web.wasm" - -rm -rf "$out" -mkdir -p "$out" -"$bindgen" --target web --no-typescript --out-dir "$out" --out-name chesspenguin_web "$wasm" -if command -v wasm-opt >/dev/null 2>&1; then - wasm-opt -Os --enable-bulk-memory --enable-nontrapping-float-to-int --enable-sign-ext \ - --enable-mutable-globals --enable-reference-types \ - "$out/chesspenguin_web_bg.wasm" -o "$out/chesspenguin_web_bg.wasm" -fi - -cp "$here/page/device.js" "$here/page/page.js" "$here/page/import-worker.js" "$out/" - -# The engine: Stockfish.js 19.0.1 (npm `stockfish`, GPL-3.0), its single-threaded build, -# checked against the registry's integrity (THIRD_PARTY_NOTICES.md). STOCKFISH_TGZ= points -# at a copy of the package; otherwise it is downloaded once into target/web/. -sf_url=https://registry.npmjs.org/stockfish/-/stockfish-19.0.1.tgz -sf_sha512=bTwsO4e9HAwPBKls1+szcfibmaWRNzTF20rQE/XPdB3LOSoT6XTZDr1zYwriwSRRFT5MkvqrglPmJrKEVXGnyQ== -tgz=${STOCKFISH_TGZ:-$root/target/web/stockfish-19.0.1.tgz} -if [ ! -f "$tgz" ]; then - mkdir -p "$(dirname "$tgz")" - curl -fsSL --retry 3 -o "$tgz.part" "$sf_url" - mv "$tgz.part" "$tgz" -fi -have_sha=$(openssl dgst -sha512 -binary "$tgz" | base64 -w0) -if [ "$have_sha" != "$sf_sha512" ]; then - echo "$tgz is not stockfish@19.0.1 (sha512 $have_sha)" >&2 - exit 1 -fi -mkdir -p "$out/engine" -tar -xzf "$tgz" -C "$out/engine" --strip-components=2 \ - package/bin/stockfish-19-single.js package/bin/stockfish-19-single.wasm -tar -xzf "$tgz" -C "$out/engine" --strip-components=1 package/Copying.txt -for size in 32 64 180; do - cp "$root/website/static/img/icon-$size.png" "$out/" -done -# The page's texts in the site's languages: the app_* keys and the shared ones it uses. -python3 -I - "$here/page/index.html" "$root/website/site/i18n" "$out/index.html" <<'PY' -import json, pathlib, sys -template, i18n, target = sys.argv[1], pathlib.Path(sys.argv[2]), sys.argv[3] -shared = ["btn_android", "and_light_title", "and_full_title", "and_requires", "next_android", - "copy_link", "link_copied", "email", "language"] -texts = {} -for f in sorted(i18n.glob("*.json")): - d = json.loads(f.read_text(encoding="utf-8")) - texts[f.stem] = {k: v for k, v in d.items() if k.startswith("app_") or k in shared} -page = pathlib.Path(template).read_text(encoding="utf-8") -blob = json.dumps(texts, ensure_ascii=False, separators=(",", ":")).replace("; what is checked is printed. -// -// node apps/web/check/app.mjs (app-dir: apps/web/build.sh's) -import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { session } from './steps.mjs'; -import { sleep } from './bidi.mjs'; - -const [appDir, outDir] = process.argv.slice(2).map((p) => resolve(p)); -const root = fileURLToPath(new URL('../../..', import.meta.url)); -mkdirSync(outDir, { recursive: true }); -let failures = 0; -const check = (ok, what) => { - console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); - if (!ok) failures++; -}; -// Places of buttons in a 1400×860 window. -const DOWNLOAD = [Number(process.env.DOWNLOAD_X || 1263), Number(process.env.DOWNLOAD_Y || 24)]; -const E2 = [519, 703]; -const E4 = [519, 505]; -// The card of «Test games» on the shelf after a reload (the draft's strip above it) and -// «Allow reading» on its pane. -const TEST_CARD = [300, 88]; -const ALLOW = [70, 232]; - -const s = await session(appDir, 18766); -const { t } = s; -const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); -const text = () => t.evaluate(`document.getElementById('cp-device').innerText`); -const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); -try { - // ----- the page for phones and tablets, without the program ---------------------------- - await t.navigate(`${s.base}?phone=1&lang=ru`); - await sleep(800); - check(/ChessPenguin на телефоне и планшете/.test(await text()), 'the device page in Russian'); - check(/Всё равно открыть веб-версию/.test(await text()), 'with «open the web version anyway»'); - const wasm = await t.evaluate(`performance.getEntriesByType('resource').some(e => e.name.endsWith('.wasm'))`); - check(!wasm, 'the program is not downloaded on it'); - await shot('web-phone-ru.png'); - await t.navigate(`${s.base}?phone=1&lang=de`); - await sleep(500); - check(/auf Handy und Tablet/.test(await text()), 'the device page in German'); - await t.navigate(`${s.base}?phone=android&lang=ru`); - await sleep(800); - check(/Скачать для Android/.test(await text()), 'the Android variant'); - await t.navigate(`${s.base}?phone=ios&lang=en`); - await sleep(800); - check(/iPhone and iPad app is coming soon/.test(await text()), 'the iPhone and iPad variant'); - - // ----- the program ------------------------------------------------------------------------- - await t.navigate(`${s.base}?lang=en`); - await started(); - await sleep(2500); - check(true, `the program started in ${s.b.name}`); - await shot('web-1-library.png'); - - // Open a PGN by the button's shortcut: the browser's file chooser gets the file. - const pgn = join(s.b.profile, 'Test games.pgn'); - copyFileSync(join(root, 'examples/alekhine.pgn'), pgn); - await t.choose([pgn], () => t.key('o', ['ctrl'])); - await sleep(3000); - await shot('web-2-opened.png'); - - // Drop a file on the window. - const dropped = readFileSync(join(root, 'examples/classics.pgn'), 'utf8'); - await t.evaluate(`(() => { - const dt = new DataTransfer(); - dt.items.add(new File([${JSON.stringify(dropped)}], 'Dropped classics.pgn', { type: 'application/x-chess-pgn' })); - const c = document.getElementById('cp-canvas'); - for (const type of ['dragenter', 'dragover', 'drop']) - c.dispatchEvent(new DragEvent(type, { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 700, clientY: 400 })); - return true; - })()`); - await sleep(3000); - await shot('web-3-dropped.png'); - - // A game from the table (double click), its moves on the board. - await t.click(300, 322, { double: true }); - await sleep(1500); - await shot('web-4-game.png'); - await t.key('right', [], 12); - await sleep(800); - await shot('web-5-moves.png'); - - // Download the PGN of the game (the header's button). - await t.click(...DOWNLOAD); - await sleep(2500); - const files = existsSync(s.b.downloads) ? readdirSync(s.b.downloads).filter((f) => f.endsWith('.pgn')) : []; - check(files.length === 1, `a PGN downloaded: ${files.join(', ') || 'none'}`); - if (files.length) { - const body = readFileSync(join(s.b.downloads, files[0]), 'utf8'); - check(/\[White "/.test(body) && /1\. /.test(body), 'the download is the game in PGN'); - } - - // The browser's Back is «← Library». - await t.evaluate(`history.back()`); - await sleep(1500); - await shot('web-6-back.png'); - check(await t.evaluate(`history.state === null || !history.state.cpGame`), 'Back left the game for the library'); - - // A move on the board of a new game (Ctrl+N; N in a browser): e2–e4 by two clicks. - await t.key('n'); - await sleep(1200); - await t.click(...E2); - await sleep(300); - await t.click(...E4); - await sleep(1000); - await shot('web-8-e4.png'); - - // An unsaved game: the browser asks before the page is left, and its draft is kept. - check(await t.evaluate(`typeof window.onbeforeunload === 'function'`), 'unsaved: the browser asks before leaving'); - await sleep(1500); - const draft = () => t.evaluate(`new Promise((ok) => { - const q = indexedDB.open('chesspenguin'); - q.onsuccess = () => { - const r = q.result.transaction('files').objectStore('files').get('/data/draft.json'); - r.onsuccess = () => ok(r.result ? JSON.parse(new TextDecoder().decode(r.result)).pgn : ''); - }; - q.onerror = () => ok(''); - })`); - check(/1\. e4/.test(await draft()), 'the draft of the unsaved game is kept'); - - // The settings and the shelf after a reload (the browser's storage). The question on - // leaving is answered «Leave». - await t.evaluate(`(window.onbeforeunload = null, true)`); - await t.navigate(`${s.base}?lang=en`); - await started(); - await sleep(2500); - await shot('web-9-reloaded.png'); - check(/1\. e4/.test(await draft()), 'the draft is there after the reload (offered over the library)'); - if (await t.evaluate(`typeof window.showOpenFilePicker === 'function'`)) { - // Chrome, Edge: the file chosen before the reload is read again by itself. - check(s.logs.some((l) => /remembered file read again: .*Test games\.pgn/.test(l)), 'the chosen file is remembered (File System Access)'); - // When the browser asks first (its permission not kept): the card offers «Allow - // reading», the browser's question is answered «Allow», the file is read. - await t.beforeLoad(`FileSystemHandle.prototype.queryPermission = async () => 'prompt'; - FileSystemHandle.prototype.requestPermission = async () => 'granted';`); - await t.navigate(`${s.base}?lang=en`); - await started(); - await sleep(2500); - await t.click(...TEST_CARD); - await sleep(1500); - await shot('web-10-allow.png'); - await t.click(...ALLOW); - await sleep(2500); - await shot('web-11-allowed.png'); - check(s.logs.some((l) => /remembered file allowed again: .*Test games\.pgn/.test(l)), '«Allow reading» reads the remembered file again'); - } -} finally { - await s.stop(); -} -for (const e of s.errors) console.log('console:', e); -check(s.errors.length === 0, 'no panic or error in the console'); -console.log(failures ? `${failures} failed` : 'all ok'); -process.exit(failures ? 1 : 0); diff --git a/apps/web/check/bidi.mjs b/apps/web/check/bidi.mjs deleted file mode 100644 index c73a929..0000000 --- a/apps/web/check/bidi.mjs +++ /dev/null @@ -1,78 +0,0 @@ -// A minimal WebDriver BiDi client for headless Firefox (Node 22+: global WebSocket). -// Used by the web checks (docs/dev/web.md, «Проверки»); no windows are opened. - -export async function connect(port) { - const ws = new WebSocket(`ws://127.0.0.1:${port}/session`); - let id = 0; - const pending = new Map(); - const listeners = []; - ws.onmessage = (m) => { - const d = JSON.parse(m.data); - if (d.id && pending.has(d.id)) { - const p = pending.get(d.id); - pending.delete(d.id); - if (d.type === 'error') p.rej(new Error(`${d.error}: ${d.message}`)); - else p.res(d.result); - } else if (d.method) { - for (const l of listeners) l(d.method, d.params); - } - }; - await new Promise((res, rej) => { - ws.onopen = res; - ws.onerror = () => rej(new Error('cannot connect to Firefox')); - }); - const send = (method, params) => - new Promise((res, rej) => { - const i = ++id; - pending.set(i, { res, rej }); - ws.send(JSON.stringify({ id: i, method, params })); - }); - await send('session.new', { capabilities: {} }); - return { - send, - on: (f) => listeners.push(f), - close: async () => { - await send('session.end', {}).catch(() => {}); - ws.close(); - }, - }; -} - -export const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - -// A tab of `width`×`height` CSS pixels with the console forwarded to `log`. -export async function tab(b, width, height, log = console.log) { - await b.send('session.subscribe', { events: ['log.entryAdded'] }); - b.on((method, p) => { - if (method === 'log.entryAdded') log(`[${p.level}] ${p.text}`); - }); - const { context } = await b.send('browsingContext.create', { type: 'tab' }); - await b.send('browsingContext.setViewport', { context, viewport: { width, height } }); - const evaluate = async (expression) => { - const r = await b.send('script.evaluate', { - expression, - target: { context }, - awaitPromise: true, - }); - if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); - return r.result?.value; - }; - return { - context, - evaluate, - navigate: (url) => b.send('browsingContext.navigate', { context, url, wait: 'complete' }), - screenshot: async () => - Buffer.from((await b.send('browsingContext.captureScreenshot', { context })).data, 'base64'), - actions: (actions) => b.send('input.performActions', { context, actions }), - // Waits until `expression` is truthy (polled), or throws after `ms`. - waitFor: async (expression, ms = 10000) => { - const end = Date.now() + ms; - for (;;) { - const v = await evaluate(expression).catch(() => undefined); - if (v) return v; - if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); - await sleep(100); - } - }, - }; -} diff --git a/apps/web/check/browser.mjs b/apps/web/check/browser.mjs deleted file mode 100644 index 45ae52a..0000000 --- a/apps/web/check/browser.mjs +++ /dev/null @@ -1,296 +0,0 @@ -// One way to drive a headless browser for the web checks: Firefox over WebDriver BiDi -// (firefox.mjs, bidi.mjs) or Chromium / Chrome for Testing over the DevTools protocol. -// The browser: CP_BROWSER=firefox (default) | chromium, the Chromium binary in -// CP_CHROME. No window is ever shown; the browser is stopped by its PID. -// -// const b = await open(port); const t = await b.tab(1400, 860, log); -// t.navigate(url) · t.evaluate(js) · t.waitFor(js, ms) · t.screenshot() -// t.click(x, y, {double, right}) · t.key(key, mods, times) · t.setFiles(inputId, paths) -// t.choose(paths, open): the user chooses the files in the dialog open() brings up -// t.chooseFolder(dir, open): … the folder -// t.beforeLoad(js): js runs in every page loaded later, before its scripts -import { spawn } from 'node:child_process'; -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { basename, join } from 'node:path'; -import { launch as launchFirefox } from './firefox.mjs'; -import { sleep, tab as bidiTab } from './bidi.mjs'; - -// WebDriver key values (BiDi) and their DevTools descriptions. -const KEYS = { - ctrl: { bidi: '', key: 'Control', code: 'ControlLeft', vk: 17, mod: 2 }, - shift: { bidi: '', key: 'Shift', code: 'ShiftLeft', vk: 16, mod: 8 }, - alt: { bidi: '', key: 'Alt', code: 'AltLeft', vk: 18, mod: 1 }, - esc: { bidi: '', key: 'Escape', code: 'Escape', vk: 27 }, - enter: { bidi: '', key: 'Enter', code: 'Enter', vk: 13, text: '\r' }, - right: { bidi: '', key: 'ArrowRight', code: 'ArrowRight', vk: 39 }, - left: { bidi: '', key: 'ArrowLeft', code: 'ArrowLeft', vk: 37 }, -}; - -function keyOf(k) { - if (KEYS[k]) return KEYS[k]; - if (k === ',') return { bidi: ',', key: ',', code: 'Comma', vk: 188, text: ',' }; - if (/^[0-9]$/.test(k)) return { bidi: k, key: k, code: `Digit${k}`, vk: 48 + Number(k), text: k }; - return { bidi: k, key: k, code: `Key${k.toUpperCase()}`, vk: k.toUpperCase().charCodeAt(0), text: k }; -} - -const waitFor = (evaluate) => async (expression, ms = 10000) => { - const end = Date.now() + ms; - for (;;) { - const v = await evaluate(expression).catch(() => undefined); - if (v) return v; - if (Date.now() > end) throw new Error(`timed out waiting for ${expression}`); - await sleep(100); - } -}; - -// ----- Firefox -------------------------------------------------------------------------- - -async function firefox(port) { - const ff = await launchFirefox(port); - return { - name: 'firefox', - profile: ff.profile, - downloads: ff.downloads, - stop: ff.stop, - tab: async (width, height, log) => { - const t = await bidiTab(ff.browser, width, height, log); - const evaluate = async (expression) => { - const r = await ff.browser.send('script.evaluate', { - expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, - target: { context: t.context }, - awaitPromise: true, - }); - if (r.type === 'exception') throw new Error(r.exceptionDetails?.text || 'script failed'); - return JSON.parse(r.result.value); - }; - return { - evaluate, - waitFor: waitFor(evaluate), - navigate: t.navigate, - screenshot: t.screenshot, - // `js` runs in every page loaded from now on, before the page's own scripts. - beforeLoad: (js) => ff.browser.send('script.addPreloadScript', { functionDeclaration: `() => { ${js} }`, contexts: [t.context] }), - click: async (x, y, { double = false, right = false } = {}) => { - const acts = [{ type: 'pointerMove', x, y }]; - for (let i = 0; i < (double ? 2 : 1); i++) { - acts.push({ type: 'pointerDown', button: right ? 2 : 0 }, { type: 'pointerUp', button: right ? 2 : 0 }); - } - await t.actions([{ type: 'pointer', id: 'mouse', parameters: { pointerType: 'mouse' }, actions: acts }]); - }, - key: async (key, mods = [], times = 1) => { - const m = mods.map((x) => KEYS[x].bidi); - const v = keyOf(key).bidi; - const acts = [...m.map((value) => ({ type: 'keyDown', value })), { type: 'keyDown', value: v }, { type: 'keyUp', value: v }, ...[...m].reverse().map((value) => ({ type: 'keyUp', value }))]; - for (let i = 0; i < times; i++) await t.actions([{ type: 'key', id: 'kb', actions: acts }]); - }, - setFiles: async (id, files) => { - const node = await ff.browser.send('script.evaluate', { - expression: `document.getElementById(${JSON.stringify(id)})`, target: { context: t.context }, awaitPromise: false, - }); - await ff.browser.send('input.setFiles', { context: t.context, element: { sharedId: node.result.sharedId }, files }); - }, - // The user chooses `files` in the dialog `open()` brings up (the page's file input). - async choose(files, open) { - await open(); - await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - await this.setFiles('cp-open-files', files); - }, - // The user chooses the folder `dir` (the page's folder input, webkitdirectory). - // WebDriver gives such an input no folder in Firefox ("Is directory"): the - // folder's own files are given, as the browser would give them. - async chooseFolder(dir, open) { - await open(); - await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000); - const files = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => join(dir, e.name)); - await this.setFiles('cp-open-folder', files); - }, - }; - }, - }; -} - -// ----- Chromium (DevTools protocol) ----------------------------------------------------------- - -async function chromium(port) { - const binary = process.env.CP_CHROME; - if (!binary) throw new Error('CP_CHROME: the Chromium / Chrome for Testing binary'); - const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-chrome-')); - const downloads = join(profile, 'downloads'); - mkdirSync(downloads, { recursive: true }); - const proc = spawn(binary, [ - '--headless=new', `--remote-debugging-port=${port}`, `--user-data-dir=${profile}`, - '--no-first-run', '--no-default-browser-check', '--disable-gpu-sandbox', '--use-angle=swiftshader', - '--enable-unsafe-swiftshader', 'about:blank', - ], { stdio: process.env.CP_CHROME_LOG ? 'inherit' : 'ignore' }); - let ws; - for (let i = 0; i < 300 && !ws; i++) { - try { - const v = await (await fetch(`http://127.0.0.1:${port}/json/version`)).json(); - ws = v.webSocketDebuggerUrl; - } catch { - await sleep(100); - } - } - if (!ws) throw new Error('Chromium did not start'); - const sock = new WebSocket(ws); - await new Promise((res) => (sock.onopen = res)); - let id = 0; - const pending = new Map(); - const listeners = []; - sock.onmessage = (m) => { - const d = JSON.parse(m.data); - if (d.id && pending.has(d.id)) { - const p = pending.get(d.id); - pending.delete(d.id); - d.error ? p.rej(new Error(d.error.message)) : p.res(d.result); - } else if (d.method) for (const l of listeners) l(d); - }; - const send = (method, params = {}, sessionId) => - new Promise((res, rej) => { - const i = ++id; - pending.set(i, { res, rej }); - sock.send(JSON.stringify({ id: i, method, params, sessionId })); - }); - await send('Browser.setDownloadBehavior', { behavior: 'allow', downloadPath: downloads }); - return { - name: 'chromium', - profile, - downloads, - send, - on: (f) => listeners.push(f), - stop: async () => { - try { sock.close(); } catch {} - try { process.kill(proc.pid); } catch {} - await sleep(500); - rmSync(profile, { recursive: true, force: true }); - }, - tab: async (width, height, log = console.log) => { - const { targetId } = await send('Target.createTarget', { url: 'about:blank' }); - const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }); - const s = (method, params) => send(method, params, sessionId); - listeners.push((d) => { - if (d.sessionId !== sessionId) return; - if (d.method === 'Runtime.consoleAPICalled') { - log(`[${d.params.type}] ${d.params.args.map((a) => a.value ?? a.description ?? '').join(' ')}`); - } else if (d.method === 'Runtime.exceptionThrown') { - log(`[error] ${d.params.exceptionDetails.exception?.description || d.params.exceptionDetails.text}`); - } else if (d.method === 'Log.entryAdded' && d.params.entry.level === 'error') { - log(`[error] ${d.params.entry.text}`); - } - }); - await s('Page.enable'); - await s('Runtime.enable'); - await s('Log.enable'); - await s('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false }); - const evaluate = async (expression) => { - const r = await s('Runtime.evaluate', { expression: `Promise.resolve(${expression}).then((v) => JSON.stringify(v === undefined ? null : v))`, awaitPromise: true, returnByValue: true }); - if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text); - return JSON.parse(r.result.value); - }; - let modifiers = 0; - return { - sessionId, - send: s, - evaluate, - waitFor: waitFor(evaluate), - beforeLoad: (js) => s('Page.addScriptToEvaluateOnNewDocument', { source: js }), - navigate: async (url) => { - await s('Page.navigate', { url }); - await waitFor(evaluate)(`document.readyState === 'complete'`, 30000); - }, - screenshot: async () => Buffer.from((await s('Page.captureScreenshot', { format: 'png' })).data, 'base64'), - click: async (x, y, { double = false, right = false } = {}) => { - const button = right ? 'right' : 'left'; - await s('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y }); - for (let i = 1; i <= (double ? 2 : 1); i++) { - await s('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button, clickCount: i }); - await s('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button, clickCount: i }); - } - }, - key: async (key, mods = [], times = 1) => { - for (let n = 0; n < times; n++) { - for (const m of mods) { - modifiers |= KEYS[m].mod; - await s('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); - } - const k = keyOf(key); - const text = modifiers & 3 ? undefined : k.text; - await s('Input.dispatchKeyEvent', { type: text ? 'keyDown' : 'rawKeyDown', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers, text }); - await s('Input.dispatchKeyEvent', { type: 'keyUp', key: k.key, code: k.code, windowsVirtualKeyCode: k.vk, modifiers }); - for (const m of [...mods].reverse()) { - modifiers &= ~KEYS[m].mod; - await s('Input.dispatchKeyEvent', { type: 'keyUp', key: KEYS[m].key, code: KEYS[m].code, windowsVirtualKeyCode: KEYS[m].vk, modifiers }); - } - } - }, - setFiles: async (id, files) => { - const { result } = await s('Runtime.evaluate', { expression: `document.getElementById(${JSON.stringify(id)})` }); - await s('DOM.setFileInputFiles', { objectId: result.objectId, files }); - }, - // The user chooses `files` in the dialog `open()` brings up. Chrome's own dialog - // (showOpenFilePicker, the files remembered) cannot be driven headless: the files - // are put into the site's private file system and its handles are what the - // dialog gives — the same kind of handle, kept and read again the same way. - async choose(files, open) { - const picker = await this.evaluate(`typeof window.showOpenFilePicker === 'function'`); - if (!picker) { - await open(); - await this.waitFor(`!!document.getElementById('cp-open-files')`, 5000); - return this.setFiles('cp-open-files', files); - } - const given = files.map((f) => ({ name: basename(f), b64: readFileSync(f).toString('base64') })); - await this.evaluate(`(() => { - const given = ${JSON.stringify(given)}; - window.showOpenFilePicker = async () => { - const root = await navigator.storage.getDirectory(); - const handles = []; - for (const g of given) { - const h = await root.getFileHandle(g.name, { create: true }); - const w = await h.createWritable(); - await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); - await w.close(); - handles.push(h); - } - return handles; - }; - return true; - })()`); - await open(); - }, - // The user chooses the folder `dir`: in Chromium showDirectoryPicker, its files - // put into a folder of the site's private file system (as for choose()). - async chooseFolder(dir, open) { - const picker = await this.evaluate(`typeof window.showDirectoryPicker === 'function'`); - if (!picker) { - await open(); - await this.waitFor(`!!document.getElementById('cp-open-folder')`, 5000); - return this.setFiles('cp-open-folder', [dir]); - } - const given = readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()) - .map((e) => ({ name: e.name, b64: readFileSync(join(dir, e.name)).toString('base64') })); - await this.evaluate(`(() => { - const given = ${JSON.stringify(given)}; - window.showDirectoryPicker = async () => { - const root = await navigator.storage.getDirectory(); - const d = await root.getDirectoryHandle(${JSON.stringify(basename(dir))}, { create: true }); - for (const g of given) { - const h = await d.getFileHandle(g.name, { create: true }); - const w = await h.createWritable(); - await w.write(Uint8Array.from(atob(g.b64), (c) => c.charCodeAt(0))); - await w.close(); - } - return d; - }; - return true; - })()`); - await open(); - }, - }; - }, - }; -} - -export async function open(port, kind = process.env.CP_BROWSER || 'firefox') { - return kind === 'chromium' ? chromium(port) : firefox(port); -} diff --git a/apps/web/check/chessbase.mjs b/apps/web/check/chessbase.mjs deleted file mode 100644 index 96e925c..0000000 --- a/apps/web/check/chessbase.mjs +++ /dev/null @@ -1,80 +0,0 @@ -// ChessBase databases in the browser (several files): a .cbh chosen alone asks for its -// folder, the folder's files make the database; all its files chosen at once; one too -// big for a browser is refused politely; Chrome remembers the folder. -// -// node apps/web/check/chessbase.mjs [] -// -// : a small ChessBase database's folder (.cbh, .cbg, …), only that -// database in it. Firefox by default, Chromium with CP_BROWSER=chromium (browser.mjs). -import { readdirSync, writeFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; -import { session } from './steps.mjs'; -import { sleep } from './bidi.mjs'; - -const [appDir, outDir, baseDir, bigDir] = process.argv.slice(2).map((p) => p && resolve(p)); -let failures = 0; -const check = (ok, what) => { - console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); - if (!ok) failures++; -}; -// «📁 Choose the database's folder» in the window about a .cbh chosen alone (1400×860). -const ADD = [155, 20]; -const FOLDER = (process.env.FOLDER || '833,471').split(',').map(Number); -const s = await session(appDir, 18768); -const { t } = s; -const shot = async (name) => writeFileSync(join(outDir, name), await t.screenshot()); -const started = () => t.waitFor(`document.getElementById('cp-status').hidden && !document.getElementById('cp-app').hidden`, 30000); -const read = (name) => s.logs.filter((l) => l.includes(`database read: ${name}`)); -const cbh = readdirSync(baseDir).find((n) => n.toLowerCase().endsWith('.cbh')); -const stem = cbh.slice(0, -4); -try { - await t.navigate(`${s.base}?lang=${process.env.CP_LANG || "en"}`); - await started(); - await sleep(2500); - - // A .cbh alone: the window asks for the database's folder; nothing is opened yet. - await t.choose([join(baseDir, cbh)], () => t.key('o', ['ctrl'])); - await sleep(2000); - await shot('cb-1-lone.png'); - check(read(stem).length === 0, 'a .cbh alone is not opened'); - // The folder: the database's files are found by their names. - await t.chooseFolder(baseDir, () => t.click(...FOLDER)); - await sleep(4000); - await shot('cb-2-folder.png'); - check(read(stem).length === 1, `the folder makes the database: ${read(stem)[0] || 'not read'}`); - - // All its files chosen at once. - const all = readdirSync(baseDir).map((n) => join(baseDir, n)); - // By the shelf's «+ Add database». - await t.choose(all, () => t.click(...ADD)); - await sleep(4000); - await shot('cb-3-files.png'); - check(read(stem).length === 2, 'all its files chosen at once make the database'); - - if (bigDir) { - // A database over the limit: refused before it is read, with the way to the - // desktop program. - const big = readdirSync(bigDir).find((n) => n.toLowerCase().endsWith('.cbh')); - await t.choose([join(bigDir, big)], () => t.click(...ADD)); - await sleep(2000); - await t.chooseFolder(bigDir, () => t.click(...FOLDER)); - await sleep(3000); - await shot('cb-4-too-big.png'); - check(read(big.slice(0, -4)).length === 0, 'a database over 2 GB is not read'); - } - - // The next visit: Chrome reads the remembered folder's database again by itself. - await t.navigate(`${s.base}?lang=${process.env.CP_LANG || "en"}`); - await started(); - await sleep(3000); - await shot('cb-5-reloaded.png'); - if (await t.evaluate(`typeof window.showDirectoryPicker === 'function'`)) { - check(s.logs.some((l) => l.includes('remembered file read again') && l.includes(cbh)), 'the folder is remembered (File System Access)'); - } -} finally { - await s.stop(); -} -for (const e of s.errors) console.log('console:', e); -check(s.errors.length === 0, 'no panic or error in the console'); -console.log(failures ? `${failures} failed` : 'all ok'); -process.exit(failures ? 1 : 0); diff --git a/apps/web/check/device.test.mjs b/apps/web/check/device.test.mjs deleted file mode 100644 index f41d1bc..0000000 --- a/apps/web/check/device.test.mjs +++ /dev/null @@ -1,49 +0,0 @@ -// Which devices get the program and which the page about the apps (page/device.js): -// -// node apps/web/check/device.test.mjs -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; -import vm from 'node:vm'; - -const source = readFileSync(fileURLToPath(new URL('../page/device.js', import.meta.url)), 'utf8'); - -// device.js in a window that looks like `d`. -function classOf(d) { - const media = { '(pointer: coarse)': d.coarse, '(any-pointer: fine)': d.fine }; - const window = { - navigator: { userAgent: d.ua, platform: d.platform || '', maxTouchPoints: d.touch || 0, userAgentData: d.uad }, - screen: { width: d.screen[0], height: d.screen[1] }, - matchMedia: (q) => ({ matches: !!media[q] }), - }; - window.window = window; - vm.runInNewContext(source, window); - return window.CPDevice.deviceClass(); -} - -const MAC = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15'; -const cases = [ - ['Windows laptop', { ua: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/159.0', screen: [1920, 1080], fine: true }, 'computer'], - ['Mac', { ua: MAC, platform: 'MacIntel', screen: [1512, 982], fine: true }, 'computer'], - ['laptop with a touch screen', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [1366, 768], touch: 10, coarse: false, fine: true }, 'computer'], - ['Chromebook', { ua: 'Mozilla/5.0 (X11; CrOS x86_64 15000.0.0) Chrome/140.0', screen: [1366, 768], touch: 5, coarse: true }, 'computer'], - ['iPhone', { ua: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Mobile/15E148', screen: [390, 844], touch: 5, coarse: true }, 'iphone'], - ['iPhone asking for the desktop site', { ua: MAC, platform: 'MacIntel', screen: [390, 844], touch: 5, coarse: true }, 'iphone'], - ['iPad (says it is a Mac)', { ua: MAC, platform: 'MacIntel', screen: [820, 1180], touch: 5, coarse: true }, 'ipad'], - ['iPad mini', { ua: MAC, platform: 'MacIntel', screen: [744, 1133], touch: 5, coarse: true }, 'ipad'], - ['Android phone', { ua: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) Chrome/140.0 Mobile', screen: [412, 915], touch: 5, coarse: true }, 'android-phone'], - ['Android tablet', { ua: 'Mozilla/5.0 (Linux; Android 14; SM-X710) Chrome/140.0', screen: [800, 1280], touch: 10, coarse: true }, 'android-tablet'], - ['Galaxy Fold folded', { ua: 'Mozilla/5.0 (Linux; Android 14; SM-F946B) Chrome/140.0 Mobile', screen: [344, 882], touch: 5, coarse: true }, 'android-phone'], - ['tablet asking for the desktop site', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [800, 1280], touch: 10, coarse: true, fine: false }, 'tablet'], - ['phone asking for the desktop site', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', screen: [412, 915], touch: 5, coarse: true, fine: false }, 'phone'], - ['a mobile Chromium by its client hints', { ua: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/140.0', uad: { mobile: true, platform: 'Linux' }, screen: [412, 915], touch: 5, coarse: true }, 'phone'], -]; - -let failed = 0; -for (const [name, device, want] of cases) { - const got = classOf(device); - const ok = got === want; - if (!ok) failed++; - console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${got}${ok ? '' : ` (want ${want})`}`); -} -console.log(failed ? `${failed} of ${cases.length} failed` : `all ${cases.length} ok`); -process.exit(failed ? 1 : 0); diff --git a/apps/web/check/firefox.mjs b/apps/web/check/firefox.mjs deleted file mode 100644 index 088ec12..0000000 --- a/apps/web/check/firefox.mjs +++ /dev/null @@ -1,51 +0,0 @@ -// Starts a headless Firefox with a temporary profile and WebDriver BiDi; stops it by -// its PID. No window is ever shown (MOZ_HEADLESS). -import { spawn } from 'node:child_process'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { connect, sleep } from './bidi.mjs'; - -export async function launch(port = 19222) { - const profile = mkdtempSync(join(process.env.TMPDIR || tmpdir(), 'cp-firefox-')); - writeFileSync( - join(profile, 'user.js'), - [ - 'user_pref("remote.active-protocols", 1);', - 'user_pref("browser.shell.checkDefaultBrowser", false);', - 'user_pref("datareporting.policy.dataSubmissionEnabled", false);', - 'user_pref("toolkit.telemetry.reportingpolicy.firstRun", false);', - // Downloads go to the profile without asking. - 'user_pref("browser.download.folderList", 2);', - `user_pref("browser.download.dir", "${join(profile, 'downloads')}");`, - 'user_pref("browser.download.useDownloadDir", true);', - 'user_pref("browser.download.always_ask_before_handling_new_types", false);', - '', - ].join('\n'), - ); - const log = join(profile, 'firefox.log'); - const out = (await import('node:fs')).openSync(log, 'a'); - const ff = spawn( - 'firefox', - ['--headless', '--no-remote', '--profile', profile, '--remote-debugging-port', String(port), 'about:blank'], - { env: { ...process.env, MOZ_HEADLESS: '1' }, stdio: ['ignore', out, out] }, - ); - for (let i = 0; i < 100; i++) { - if (readFileSync(log, 'utf8').includes('WebDriver BiDi listening')) break; - await sleep(100); - } - const browser = await connect(port); - return { - browser, - profile, - downloads: join(profile, 'downloads'), - stop: async () => { - await browser.close().catch(() => {}); - try { - process.kill(ff.pid); - } catch {} - await sleep(300); - rmSync(profile, { recursive: true, force: true }); - }, - }; -} diff --git a/apps/web/check/review.mjs b/apps/web/check/review.mjs deleted file mode 100644 index c6e8892..0000000 --- a/apps/web/check/review.mjs +++ /dev/null @@ -1,95 +0,0 @@ -// The game review of the web version against the desktop program's, on games of the -// chess.com check set (crates/game-review/chesscom/): the browser reviews them (Stockfish -// 19 wasm in workers), its evaluations are read out of its storage and compared with the -// ones `chesscom_check` keeps (target/chesscom-check/v1): the same search must give the -// same evaluations, so the same !!/!. -// -// node apps/web/check/review.mjs ... -import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'; -import { basename, join } from 'node:path'; -import { session } from './steps.mjs'; -import { sleep } from './bidi.mjs'; - -const [appDir, outDir, nativeDir, ...games] = process.argv.slice(2); -mkdirSync(outDir, { recursive: true }); -const all = join(outDir, 'chesscom-games.pgn'); -writeFileSync(all, games.map((g) => readFileSync(g, 'utf8').trim()).join('\n\n') + '\n'); - -const s = await session(appDir); -const { t } = s; -const stored = `new Promise((ok, no) => { - const q = indexedDB.open('chesspenguin'); - q.onerror = () => no('no db'); - q.onsuccess = () => { - const st = q.result.transaction('files').objectStore('files'); - const keys = st.getAllKeys(), values = st.getAll(); - values.onsuccess = () => ok(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i])]) - .filter(([k]) => k.startsWith('/cache/analysis/'))); - }; -}).then((r) => JSON.stringify(r))`; -const readStored = async () => JSON.parse(await t.evaluate(stored)); -let failed = 0; -try { - await s.run({ url: '?lang=en' }, outDir); - await sleep(2000); - // The games in one file, reviewed one by one. - await t.choose([all], () => s.run({ key: 'o', mods: ['ctrl'] }, outDir)); - await sleep(3000); - await s.run({ shot: 'review-0-opened.png' }, outDir); - for (let i = 0; i < games.length; i++) { - const before = (await readStored()).length; - await s.run({ click: [300, 214 + 27 * i], double: true }, outDir); - await sleep(1500); - await s.run({ key: 'a', mods: ['shift'] }, outDir); - // The first time the engine is offered: downloaded, the review starts by itself. - if (i === 0) { - await sleep(1000); - await s.run({ shot: 'review-0-offer.png' }, outDir); - await s.run({ key: 'enter' }, outDir); - await sleep(5000); - await s.run({ shot: 'review-0-downloading.png' }, outDir); - } - const t0 = Date.now(); - for (;;) { - await sleep(2000); - if ((await readStored()).length > before) break; - if (Date.now() - t0 > 600000) throw new Error(`no review of ${games[i]}`); - } - console.log(`${basename(games[i])}: reviewed in ${((Date.now() - t0) / 1000).toFixed(0)} s`); - await s.run({ shot: `review-${i + 1}.png` }, outDir); - await s.run({ click: [55, 15] }, outDir); - await sleep(1000); - } - // The comparison. - const fromBrowser = await readStored(); - for (const [key, text] of fromBrowser) { - const name = basename(key); - writeFileSync(join(outDir, name), text); - const web = JSON.parse(text); - const nativePath = join(nativeDir, name); - if (!existsSync(nativePath)) { - console.log(`FAIL ${name}: no native evaluations to compare with`); - failed++; - continue; - } - const native = new Map(JSON.parse(readFileSync(nativePath, 'utf8')).evals); - let same = 0, differ = 0, missing = 0; - for (const [k, e] of web.evals) { - const n = native.get(k); - if (!n) { missing++; continue; } - if (JSON.stringify(n) === JSON.stringify(e)) same++; - else { - differ++; - if (differ <= 3) console.log(' differs', k.slice(-40), JSON.stringify(n).slice(0, 160), '|', JSON.stringify(e).slice(0, 160)); - } - } - const ok = differ === 0 && missing === 0 && same > 0; - if (!ok) failed++; - console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${same} positions the same${differ ? `, ${differ} differ` : ''}${missing ? `, ${missing} not in the native set` : ''} (engine ${web.meta.engine}, ${web.meta.nodes} nodes)`); - } -} finally { - await s.stop(); -} -for (const e of s.errors) console.log('console:', e); -console.log(failed ? `${failed} failed` : 'all the same'); -process.exit(failed ? 1 : 0); diff --git a/apps/web/check/serve.py b/apps/web/check/serve.py deleted file mode 100644 index 122b287..0000000 --- a/apps/web/check/serve.py +++ /dev/null @@ -1,37 +0,0 @@ -"""The site's layout for the web version, locally: the built program at /app/ and the -site's static files at /static/ (screenshots of the device page). Only for checks: -the site itself serves /app/ when the web version is published (docs/dev/web.md). - - python3 -I apps/web/check/serve.py [port] -""" - -import functools -import http.server -import pathlib -import sys - -APP, STATIC = pathlib.Path(sys.argv[1]).resolve(), pathlib.Path(sys.argv[2]).resolve() -PORT = int(sys.argv[3]) if len(sys.argv) > 3 else 18765 - - -class Handler(http.server.SimpleHTTPRequestHandler): - extensions_map = { - **http.server.SimpleHTTPRequestHandler.extensions_map, - ".wasm": "application/wasm", - ".js": "text/javascript", - } - - def translate_path(self, path): - path = path.split("?", 1)[0].split("#", 1)[0] - for prefix, base in (("/app/", APP), ("/static/", STATIC), ("/screenshots/", STATIC / "screenshots")): - if path.startswith(prefix): - target = (base / path[len(prefix):]).resolve() - if target == base or base in target.parents: - return str(target / "index.html" if target.is_dir() else target) - return str(APP / "__missing__") - - def log_message(self, *args): - pass - - -http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() diff --git a/apps/web/check/stage2.mjs b/apps/web/check/stage2.mjs deleted file mode 100644 index ab3588e..0000000 --- a/apps/web/check/stage2.mjs +++ /dev/null @@ -1,83 +0,0 @@ -// «My games», the data in the browser and the files of a visit in headless Firefox: -// Ctrl+S puts a game of the samples into «My games» (kept in IndexedDB), a file kept as -// a copy opens after a reload, a file only opened asks to be chosen again. -// -// node apps/web/check/stage2.mjs -// (KEEP_X, KEEP_Y: where «Keep a copy in the browser» is, for a 1400×860 window) -import { copyFileSync, mkdirSync } from 'node:fs'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { session } from './steps.mjs'; -import { sleep } from './bidi.mjs'; - -const [appDir, outDir] = process.argv.slice(2); -mkdirSync(outDir, { recursive: true }); -const root = fileURLToPath(new URL('../../..', import.meta.url)); -let failures = 0; -const check = (ok, what) => { - console.log(`${ok ? 'ok ' : 'FAIL'} ${what}`); - if (!ok) failures++; -}; - -const s = await session(appDir, 18810); -const { t } = s; -const kept = `new Promise((ok) => { - const q = indexedDB.open('chesspenguin'); - q.onsuccess = () => { - const st = q.result.transaction('files').objectStore('files'); - const keys = st.getAllKeys(), values = st.getAll(); - values.onsuccess = () => ok(JSON.stringify(keys.result.map((k, i) => [k, new TextDecoder().decode(values.result[i]).slice(0, 2000)]))); - }; -})`; -const files = async () => new Map(JSON.parse(await t.evaluate(kept))); -const step = (x) => s.run(x, outDir); -try { - await step({ url: '?lang=en' }); - await sleep(2500); - await step({ shot: 's2-1-library.png' }); - // A game of the samples into «My games». - await step({ click: [300, 322], double: true }); - await sleep(1500); - await step({ key: 's', mods: ['ctrl'] }); - await sleep(3000); - await step({ shot: 's2-2-saved.png' }); - let f = await files(); - const mine = [...f.keys()].find((k) => k.startsWith('/data/my-games/')); - check(!!mine && /Anderssen/.test(f.get(mine)), `the game is in «My games» in the browser's storage (${mine})`); - await step({ click: [55, 15] }); - await sleep(1500); - await step({ shot: 's2-3-my-games.png' }); - await step({ key: ',', mods: ['ctrl'] }); - await sleep(1000); - await step({ shot: 's2-4-settings.png' }); - await step({ click: [1366, 77] }); - // Two files opened; one kept as a copy. - const a = join(s.b.profile, 'Kept games.pgn'); - const b = join(s.b.profile, 'Visit games.pgn'); - copyFileSync(join(root, 'examples/alekhine.pgn'), a); - copyFileSync(join(root, 'examples/classics.pgn'), b); - for (const file of [b, a]) { - await t.choose([file], () => step({ key: 'o', mods: ['ctrl'] })); - await sleep(2500); - } - await step({ shot: 's2-5-opened.png' }); - if (process.env.KEEP_X) { - await step({ click: [Number(process.env.KEEP_X), Number(process.env.KEEP_Y)] }); - await sleep(2000); - await step({ shot: 's2-6-kept.png' }); - f = await files(); - check([...f.keys()].some((k) => /^\/data\/copies\/[0-9]+\/Kept games\.pgn$/.test(k)), 'a copy of the file is kept in the browser'); - } - // After a reload: «My games» and the copy are there, the other file is to be chosen again. - await step({ url: '?lang=en' }); - await sleep(3000); - await step({ shot: 's2-7-reloaded.png' }); - f = await files(); - check(!!mine && /Anderssen/.test(f.get(mine) || ''), '«My games» after a reload'); -} finally { - await s.stop(); -} -for (const e of s.errors) console.log('console:', e); -check(s.errors.length === 0, 'no panic or error in the console'); -console.log(failures ? `${failures} failed` : 'all ok'); -process.exit(failures ? 1 : 0); diff --git a/apps/web/check/steps.mjs b/apps/web/check/steps.mjs deleted file mode 100644 index 559cbbf..0000000 --- a/apps/web/check/steps.mjs +++ /dev/null @@ -1,64 +0,0 @@ -// A session of the web version in a headless browser (browser.mjs: Firefox, or -// Chromium with CP_BROWSER=chromium) over the site's layout (serve.py), and a runner of -// step lists — for finding the places of buttons, and for the scenario checks. -// -// node apps/web/check/steps.mjs -// -// A step: {"url": "?lang=en"} | {"wait": ms} | {"click": [x, y], "double": true} -// | {"key": "l", "mods": ["ctrl"], "times": 3} | {"shot": "name.png"} | {"eval": "js"} -// | {"until": "js expression", "ms": 60000} -import { spawn } from 'node:child_process'; -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { open } from './browser.mjs'; -import { sleep } from './bidi.mjs'; - -export async function session(appDir, port = Number(process.env.CP_CHECK_PORT || 18767)) { - const root = fileURLToPath(new URL('../../..', import.meta.url)); - const server = spawn('python3', ['-I', join(root, 'apps/web/check/serve.py'), resolve(appDir), join(root, 'website/static'), String(port)], { stdio: 'ignore' }); - const b = await open(port + 457); - const errors = []; - const logs = []; - const t = await b.tab(1400, 860, (line) => { - logs.push(line); - if (/panicked|RuntimeError|\[error\]/.test(line) && !/favicon|404/.test(line)) errors.push(line); - if (process.env.CONSOLE) console.log(line); - }); - const base = `http://127.0.0.1:${port}/app/`; - const run = async (step, outDir) => { - if (step.url !== undefined) { - await t.navigate(base + step.url); - await t.waitFor(`document.getElementById('cp-status').hidden || !document.getElementById('cp-device').hidden`, 30000); - } - if (step.wait) await sleep(step.wait); - if (step.click) { - await t.click(step.click[0], step.click[1], step); - await sleep(300); - } - if (step.key) { - await t.key(step.key, step.mods || [], step.times || 1); - await sleep(300); - } - if (step.eval) console.log('eval:', JSON.stringify(await t.evaluate(step.eval)).slice(0, 2000)); - if (step.until) await t.waitFor(step.until, step.ms || 60000); - if (step.shot) writeFileSync(join(outDir, step.shot), await t.screenshot()); - }; - return { - t, b, base, errors, logs, run, - stop: async () => { await b.stop(); server.kill(); }, - }; -} - -if (process.argv[1] === fileURLToPath(import.meta.url)) { - const [appDir, outDir, stepsFile] = process.argv.slice(2); - mkdirSync(outDir, { recursive: true }); - const steps = JSON.parse(readFileSync(stepsFile, 'utf8')); - const s = await session(appDir); - try { - for (const step of steps) await s.run(step, outDir); - } finally { - await s.stop(); - } - for (const e of s.errors) console.log('console:', e); -} diff --git a/apps/web/check/uci-worker.mjs b/apps/web/check/uci-worker.mjs deleted file mode 100644 index 6288a65..0000000 --- a/apps/web/check/uci-worker.mjs +++ /dev/null @@ -1,60 +0,0 @@ -// The tests of uci's worker transport (crates/uci/tests/worker.rs) in headless -// Firefox. wasm-bindgen-test-runner serves them (NO_HEADLESS: it does not look for a -// WebDriver) and this script opens its page and reads the outcome. -// -// node apps/web/check/uci-worker.mjs -// -// Needs wasm-bindgen-test-runner of the wasm-bindgen version in Cargo.lock in PATH -// or in WASM_BINDGEN_TEST_RUNNER. -import { spawn } from 'node:child_process'; -import { launch } from './firefox.mjs'; -import { sleep, tab } from './bidi.mjs'; - -const runner = process.env.WASM_BINDGEN_TEST_RUNNER || 'wasm-bindgen-test-runner'; -const address = '127.0.0.1:18731'; -const cargo = spawn( - 'cargo', - ['test', '-p', 'uci', '--target', 'wasm32-unknown-unknown', '--test', 'worker'], - { - env: { - ...process.env, - CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: runner, - NO_HEADLESS: '1', - WASM_BINDGEN_TEST_ADDRESS: address, - }, - stdio: ['ignore', 'pipe', 'inherit'], - // Its own process group: the runner it starts is stopped with it. - detached: true, - }, -); -const stopCargo = () => { - try { - process.kill(-cargo.pid); - } catch {} -}; -let served = false; -cargo.stdout.on('data', (d) => { - if (String(d).includes(address)) served = true; -}); -for (let i = 0; i < 1200 && !served; i++) await sleep(100); -if (!served) { - console.error('the test runner did not start'); - stopCargo(); - process.exit(1); -} -const ff = await launch(); -let failed = true; -try { - const t = await tab(ff.browser, 1000, 800, () => {}); - await t.navigate(`http://${address}/`); - const text = await t.waitFor( - `(() => { const t = document.body.innerText; return /test result: /.test(t) && t; })()`, - 60000, - ); - console.log(text.trim()); - failed = !/test result: ok\./.test(text); -} finally { - await ff.stop(); - stopCargo(); -} -process.exit(failed ? 1 : 0); diff --git a/apps/web/page/device.js b/apps/web/page/device.js deleted file mode 100644 index a8ccbb3..0000000 --- a/apps/web/page/device.js +++ /dev/null @@ -1,43 +0,0 @@ -// What device opened the page (docs/design/web-version.md §3.6.1; decisions «Веб-версия»: -// the web application is for computers only, phones and tablets get the app page). -// Decided by the page itself before anything large is loaded: a server cannot tell an -// iPad (it says "Macintosh") nor see the size of the screen. -// -// One function for the site and /app/, so that they never disagree whom to send where -// (the site takes this file over when the web version is published). -(function (global) { - "use strict"; - - // "computer" | "iphone" | "ipad" | "android-phone" | "android-tablet" | "phone" | "tablet" - function deviceClass() { - var ua = navigator.userAgent || ""; - var uad = navigator.userAgentData; - var plat = (uad && uad.platform) || navigator.platform || ""; - var touch = navigator.maxTouchPoints > 0; - // CSS pixels of the whole screen, not of the window: a narrow window of a computer - // stays a computer; min() removes the orientation. - var short = Math.min(screen.width, screen.height); - var coarse = matchMedia("(pointer: coarse)").matches; - var finePresent = matchMedia("(any-pointer: fine)").matches; - - // iPadOS (and an iPhone asking for the desktop site) says "Mac"; a Mac has no touch. - var ios = /iPhone|iPod|iPad/.test(ua) || (/Mac/.test(plat) && navigator.maxTouchPoints > 1); - if (ios) return short < 600 ? "iphone" : "ipad"; - if (/Android/i.test(ua)) return short < 600 ? "android-phone" : "android-tablet"; - if (uad && uad.mobile) return short < 600 ? "phone" : "tablet"; - if (/CrOS/.test(ua)) return "computer"; - // A phone or tablet asking for the desktop site (Chrome on large tablets does by - // default): a touch screen and no fine pointer. A laptop with a touch screen has its - // touchpad, so it stays a computer. - if (touch && coarse && !finePresent) return short < 600 ? "phone" : "tablet"; - return "computer"; - } - - // The Android version of an Android device (0: not said). - function androidVersion() { - var m = /Android (\d+)/.exec(navigator.userAgent || ""); - return m ? Number(m[1]) : 0; - } - - global.CPDevice = { deviceClass: deviceClass, androidVersion: androidVersion }; -})(window); diff --git a/apps/web/page/import-worker.js b/apps/web/page/import-worker.js deleted file mode 100644 index 49365f9..0000000 --- a/apps/web/page/import-worker.js +++ /dev/null @@ -1,29 +0,0 @@ -// The page's reader: a second instance of the program that reads the databases the user -// opens, so that the page does not stop while a large one is read -// (apps/desktop/src/platform/web/import.rs). One database at a time, in order: its files -// one by one (the user's are the browser's File objects, read here), then the reading. -import init, { reader_give, reader_read } from './chesspenguin_web.js'; - -const ready = init(); - -self.onmessage = async (e) => { - await ready; - const { id, names, parts, count } = e.data; - let answer; - try { - for (let i = 0; i < names.length; i++) { - const part = parts[i]; - const bytes = part instanceof Blob ? new Uint8Array(await part.arrayBuffer()) : part; - parts[i] = null; - reader_give(names[i], bytes); - } - answer = reader_read(count); - } catch (err) { - // The program stopped (out of memory, most likely): this instance is spent. - self.postMessage({ id, crashed: String(err) }); - self.close(); - return; - } - answer.id = id; - self.postMessage(answer, answer.text ? [answer.text.buffer] : []); -}; diff --git a/apps/web/page/index.html b/apps/web/page/index.html deleted file mode 100644 index 2d20d55..0000000 --- a/apps/web/page/index.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - - -ChessPenguin - - - - - - - - - -
- - - - - - diff --git a/apps/web/page/page.js b/apps/web/page/page.js deleted file mode 100644 index 142f0c3..0000000 --- a/apps/web/page/page.js +++ /dev/null @@ -1,211 +0,0 @@ -// The page /app/: a computer gets ChessPenguin (the WebAssembly program, loaded only -// then); a phone or a tablet gets the page about the apps (docs/design/web-version.md -// §3.6, decisions «Веб-версия»), with a quiet way to open the web version anyway. -// -// ?phone=1 the device page on any device (checks, screenshots of the site); -// ?phone=android, ?phone=ios: that variant of it -// ?phone=0 the program on any device -// ?lang=xx the language (also of the program) -(function () { - "use strict"; - - var LANGS = [ - ["en", "English"], ["ru", "Русский"], ["fr", "Français"], ["de", "Deutsch"], ["es", "Español"], - ["it", "Italiano"], ["pt", "Português"], ["uz", "Oʻzbekcha"], ["kk", "Қазақша"], - ]; - // The engine the web version downloads for analysis (Stockfish 19, brotli). - var ENGINE_MB = 78; - var ANYWAY_KEY = "cp.web.phoneAnyway"; - var SITE = "https://chess.vrubel.xyz"; - - var params = new URLSearchParams(location.search); - var texts = window.CP_TEXTS || {}; - - function pickLang() { - var asked = (params.get("lang") || "").toLowerCase(); - if (texts[asked]) return asked; - var prefs = navigator.languages || [navigator.language || ""]; - for (var i = 0; i < prefs.length; i++) { - var code = String(prefs[i]).split(/[-_]/)[0].toLowerCase(); - if (texts[code]) return code; - } - return "en"; - } - var lang = pickLang(); - - function t(key, vars) { - var s = (texts[lang] && texts[lang][key]) || (texts.en && texts.en[key]) || key; - for (var k in vars || {}) s = s.split("{" + k + "}").join(vars[k]); - return s; - } - - function el(tag, attrs, children) { - var e = document.createElement(tag); - for (var a in attrs || {}) { - if (a === "text") e.textContent = attrs[a]; - else if (a === "onclick") e.addEventListener("click", attrs[a]); - else e.setAttribute(a, attrs[a]); - } - (children || []).forEach(function (c) { if (c) e.appendChild(c); }); - return e; - } - - function storage(get, value) { - try { - if (get) return localStorage.getItem(ANYWAY_KEY); - if (value === null) localStorage.removeItem(ANYWAY_KEY); - else localStorage.setItem(ANYWAY_KEY, value); - } catch (e) {} - return null; - } - - // ----- the program -------------------------------------------------------------- - - function startApp() { - document.documentElement.lang = lang; - document.title = t("app_title"); - document.getElementById("cp-device").hidden = true; - var status = document.getElementById("cp-status"); - status.textContent = t("app_loading"); - status.hidden = false; - var failed = function (e) { - console.error("ChessPenguin did not start:", e); - document.getElementById("cp-app").hidden = true; - status.textContent = t("app_failed"); - status.className = "failed"; - status.hidden = false; - }; - import("./chesspenguin_web.js") - .then(function (m) { return m.default().then(function () { return m; }); }) - .then(function (m) { - document.getElementById("cp-app").hidden = false; - return m.start("cp-canvas"); - }) - .then(function () { - status.hidden = true; - document.getElementById("cp-canvas").focus(); - }) - .catch(failed); - } - - // ----- the page for phones and tablets --------------------------------------------- - - function shots(names) { - return el("div", { class: "shots" }, names.map(function (n) { - return el("img", { src: "/screenshots/" + n, alt: "", loading: "lazy" }); - })); - } - - function shareButton() { - var url = SITE + "/app/?lang=" + lang; - var label = navigator.share ? t("app_send_link") : t("copy_link"); - var b = el("button", { class: "btn", type: "button", text: "⇪ " + label }); - b.addEventListener("click", function () { - if (navigator.share) { - navigator.share({ title: "ChessPenguin", url: url }).catch(function () {}); - } else if (navigator.clipboard) { - navigator.clipboard.writeText(url).then(function () { b.textContent = t("link_copied"); }); - } - }); - return b; - } - - function anyway() { - var size = ENGINE_MB + (lang === "ru" || lang === "kk" ? " МБ" : " MB"); - return el("div", null, [ - el("hr"), - el("button", { - class: "anyway", type: "button", text: t("app_open_anyway"), - onclick: function () { storage(false, "1"); startApp(); }, - }), - el("p", { class: "weak", text: t("app_open_anyway_note", { size: size }) }), - ]); - } - - function androidPart() { - var v = CPDevice.androidVersion(); - if (v && v < 12) { - return [el("p", { text: t("app_and_old", { version: String(v) }) }), shareButton()]; - } - var hint = el("p", { class: "weak", text: t("next_android"), hidden: "" }); - var show = function () { hint.hidden = false; }; - return [ - el("a", { class: "btn", href: "/download/android-noengine", rel: "nofollow", onclick: show }, [ - document.createTextNode(t("btn_android")), - el("small", { text: t("and_light_title") }), - ]), - el("p", null, [ - el("a", { class: "link", href: "/download/android", rel: "nofollow", onclick: show, text: t("and_full_title") + " ›" }), - ]), - el("p", { class: "weak", text: t("and_requires") }), - hint, - shots(["phone/01-home-360.webp", "phone/03-game-360.webp", "phone/04-engine-360.webp", "phone/08-review-360.webp"]), - el("p", null, [el("a", { class: "link", href: "/" + (lang === "en" ? "" : lang + "/") + "#download-android", text: t("app_and_more") + " ›" })]), - ]; - } - - function iosPart() { - return [ - el("p", { class: "lead", text: t("app_ios_lead") }), - el("p", { text: t("app_ios_now") }), - shareButton(), - el("p", { style: "margin-top:16px", text: t("app_ios_notify") }), - el("div", { class: "contacts" }, [ - el("a", { class: "link", href: "mailto:vrubelroman@gmail.com?subject=ChessPenguin", text: "✉ " + t("email") }), - el("a", { class: "link", href: "https://t.me/vrubelr", rel: "noopener", text: "✈ Telegram" }), - ]), - shots(["01-game-640.webp", "04-review-640.webp"]), - ]; - } - - function showDevicePage(kind) { - document.documentElement.lang = lang; - document.title = t("app_phone_title"); - var page = document.getElementById("cp-device"); - page.textContent = ""; - var select = el("select", { "aria-label": t("language") }, LANGS.map(function (l) { - var o = el("option", { value: l[0], text: l[1] }); - if (l[0] === lang) o.selected = true; - return o; - })); - select.addEventListener("change", function () { - lang = select.value; - showDevicePage(kind); - }); - page.appendChild(el("header", null, [ - el("span", { class: "brand" }, [el("img", { src: "icon-64.png", alt: "" }), document.createTextNode("ChessPenguin")]), - select, - ])); - page.appendChild(el("h1", { text: t("app_phone_title") })); - var body; - if (kind === "android-phone" || kind === "android-tablet") { - body = [el("p", { text: t("app_and_lead") })].concat(androidPart()); - } else if (kind === "iphone" || kind === "ipad") { - body = iosPart(); - } else { - body = [ - el("p", { text: t("app_phone_generic") }), - el("a", { class: "btn", href: "/download/android-noengine", rel: "nofollow", text: t("btn_android") }), - el("p"), - shareButton(), - ]; - } - body.forEach(function (n) { page.appendChild(n); }); - page.appendChild(anyway()); - page.hidden = false; - } - - // ----- which one -------------------------------------------------------------------- - - var asked = params.get("phone"); - var kind = CPDevice.deviceClass(); - if (asked === "1") { - showDevicePage(kind === "computer" ? "phone" : kind); - } else if (asked === "android" || asked === "ios") { - showDevicePage(asked === "android" ? "android-phone" : "iphone"); - } else if (asked === "0" || kind === "computer" || storage(true) === "1") { - startApp(); - } else { - showDevicePage(kind); - } -})(); diff --git a/apps/web/src/lib.rs b/apps/web/src/lib.rs deleted file mode 100644 index 147a881..0000000 --- a/apps/web/src/lib.rs +++ /dev/null @@ -1,37 +0,0 @@ -//! ChessPenguin in a browser: the entry point the page (`page/index.html`) calls once it -//! has decided the device is a computer. The interface is the desktop program's -//! (`chesspenguin_app`), with the web platform under it (`docs/dev/web.md`). -#![cfg(target_family = "wasm")] - -use wasm_bindgen::JsCast; -use wasm_bindgen::prelude::*; - -/// The reader worker's work (`page/import-worker.js`): one more file of the database -/// to read (its own file first) … -#[wasm_bindgen] -pub fn reader_give(name: String, bytes: Vec) { - chesspenguin_app::reader_give(name, bytes); -} - -/// … and the database read and indexed away from the page (or only its games counted). -#[wasm_bindgen] -pub fn reader_read(count: bool) -> JsValue { - chesspenguin_app::reader_read(count) -} - -/// Starts ChessPenguin in the page's canvas `canvas_id`. Resolves once the interface -/// runs; an error says why it could not start (no WebGL, …). -#[wasm_bindgen] -pub async fn start(canvas_id: String) -> Result<(), JsValue> { - // The program's log and its panics go to the browser's console. - let _ = eframe::WebLogger::init(log::LevelFilter::Info); - let window = web_sys::window().ok_or("no window")?; - let canvas = window - .document() - .ok_or("no document")? - .get_element_by_id(&canvas_id) - .ok_or("no canvas")? - .dyn_into::()?; - let lang = web_sys::UrlSearchParams::new_with_str(&window.location().search()?)?.get("lang"); - chesspenguin_app::start_web(canvas, lang).await -} diff --git a/crates/chess-core/Cargo.toml b/crates/chess-core/Cargo.toml index a66c3b8..2f0293e 100644 --- a/crates/chess-core/Cargo.toml +++ b/crates/chess-core/Cargo.toml @@ -9,12 +9,6 @@ license.workspace = true shakmaty.workspace = true encoding_rs.workspace = true thiserror.workspace = true -# The index of a database in serde's terms: the web version reads a database in a -# worker and gives its index to the page (`PgnIndex`). -serde = { workspace = true, optional = true } - -[features] -serde = ["dep:serde"] [dev-dependencies] # Independent oracle in corpus tests: the core uses its own lexer (byte offsets, diff --git a/crates/chess-core/src/database.rs b/crates/chess-core/src/database.rs index 34678df..731fe23 100644 --- a/crates/chess-core/src/database.rs +++ b/crates/chess-core/src/database.rs @@ -32,18 +32,6 @@ impl From for OpenError { } } -/// What reading a database's text found: everything of a [`PgnDatabase`] but the text. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PgnIndex { - detected: EncodingGuess, - encoding: TextEncoding, - entries: Vec, - content_hash: u64, - letter_repair: LetterRepairDetection, - repair_letters: bool, -} - /// Identity of the source content, for change detection and cache keys. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct SourceFingerprint { @@ -125,39 +113,6 @@ impl PgnDatabase { }) } - /// The database taken apart: its text and its index (to rebuild it elsewhere — - /// the web version reads a database in a worker and gives it to the page). - pub fn into_index(self) -> (Vec, PgnIndex) { - let index = PgnIndex { - detected: self.detected, - encoding: self.encoding, - entries: self.entries, - content_hash: self.fingerprint.content_hash, - letter_repair: self.letter_repair, - repair_letters: self.repair_letters, - }; - (self.bytes, index) - } - - /// The database again from its text and the index [`Self::into_index`] gave, - /// without reading the text once more. - pub fn from_index(bytes: Vec, index: PgnIndex) -> Self { - PgnDatabase { - path: None, - fingerprint: SourceFingerprint { - len: bytes.len() as u64, - modified: None, - content_hash: index.content_hash, - }, - bytes, - detected: index.detected, - encoding: index.encoding, - entries: index.entries, - letter_repair: index.letter_repair, - repair_letters: index.repair_letters, - } - } - pub fn path(&self) -> Option<&Path> { self.path.as_deref() } @@ -268,26 +223,6 @@ impl PgnDatabase { mod tests { use super::*; - /// A database taken apart and put together again is the same database. - #[test] - fn index_round_trip() { - let text = "[White \"A\"]\n[Black \"B\"]\n\n1. e4 e5 *\n\n[White \"C\"]\n\n1. d4 {x} *\n"; - let db = PgnDatabase::from_bytes( - text.as_bytes().to_vec(), - None, - &mut |_| {}, - &AtomicBool::new(false), - ) - .unwrap(); - let (entries, hash) = (db.entries().to_vec(), db.fingerprint.content_hash); - let (bytes, index) = db.into_index(); - let again = PgnDatabase::from_index(bytes, index); - assert_eq!(again.entries(), entries.as_slice()); - assert_eq!(again.fingerprint.content_hash, hash); - assert_eq!(again.bytes(), text.as_bytes()); - assert_eq!(again.load_game(1).unwrap().game.tag("White"), Some("C")); - } - fn assert_send_sync() {} #[test] diff --git a/crates/chess-core/src/encoding.rs b/crates/chess-core/src/encoding.rs index 19fa4bb..bc06a00 100644 --- a/crates/chess-core/src/encoding.rs +++ b/crates/chess-core/src/encoding.rs @@ -8,7 +8,6 @@ use std::borrow::Cow; /// Encodings supported for PGN sources. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum TextEncoding { Utf8, @@ -66,7 +65,6 @@ impl TextEncoding { } /// How sure the detector is. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Confidence { /// Valid UTF-8 (or pure ASCII), or a UTF-8 BOM. @@ -76,7 +74,6 @@ pub enum Confidence { } /// Result of [`detect_encoding`]. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct EncodingGuess { pub encoding: TextEncoding, diff --git a/crates/chess-core/src/lib.rs b/crates/chess-core/src/lib.rs index 94c0e7e..01d2f39 100644 --- a/crates/chess-core/src/lib.rs +++ b/crates/chess-core/src/lib.rs @@ -19,7 +19,7 @@ pub use comment::{ Annotation, CommentPart, ShapeColor, comment_display_text, parse_comment, shapes, with_shapes, with_text, }; -pub use database::{OpenError, PgnDatabase, PgnIndex, SourceFingerprint}; +pub use database::{OpenError, PgnDatabase, SourceFingerprint}; pub use diagnostic::{Diagnostic, DiagnosticCode, Severity, SourceLocation}; pub use edit::{EditError, EditOutcome}; pub use encoding::{Confidence, EncodingGuess, TextEncoding, detect_encoding}; diff --git a/crates/chess-core/src/pgn/scan.rs b/crates/chess-core/src/pgn/scan.rs index 87b1c9e..db47a62 100644 --- a/crates/chess-core/src/pgn/scan.rs +++ b/crates/chess-core/src/pgn/scan.rs @@ -7,7 +7,6 @@ use crate::encoding::TextEncoding; use crate::pgn::lexer::{Lexer, TokKind, parse_tag}; /// Summary flags computed while scanning. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct EntryFlags { pub has_fen: bool, @@ -29,7 +28,6 @@ pub struct EntryFlags { } /// One record of a PGN file. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq)] pub struct GameEntry { /// 0-based ordinal in the file. diff --git a/crates/chess-core/src/pgn/store.rs b/crates/chess-core/src/pgn/store.rs index 3985be2..69b4111 100644 --- a/crates/chess-core/src/pgn/store.rs +++ b/crates/chess-core/src/pgn/store.rs @@ -97,38 +97,21 @@ fn check_writable(db: &PgnDatabase) -> Result<&Path, WriteError> { /// before the new record stay as they were. pub fn append(db: &PgnDatabase, record: &str) -> Result { let path = check_writable(db)?; - let (data, sep) = tail_for(db.bytes(), record); + let bytes = db.bytes(); + let eol = line_ending(bytes); + let sep = separator(bytes, eol); + let mut data = sep.as_bytes().to_vec(); + data.extend(record_bytes(record, eol)); let mut file = std::fs::OpenOptions::new().append(true).open(path)?; - let offset = file.metadata()?.len() + sep as u64; + let offset = file.metadata()?.len() + sep.len() as u64; file.write_all(&data)?; file.sync_all()?; Ok(Appended { offset }) } -/// What goes at the end of `bytes` to add `record` after a blank line, and how many of -/// its bytes come before the record. -fn tail_for(bytes: &[u8], record: &str) -> (Vec, usize) { - let eol = line_ending(bytes); - let sep = separator(bytes, eol); - let mut data = sep.as_bytes().to_vec(); - data.extend(record_bytes(record, eol)); - (data, sep.len()) -} - -/// The text of `db` with `record` added at the end, and where the record starts: the -/// same bytes [`append`] writes, for a database kept elsewhere than in a file (the web -/// version's games in the browser). -pub fn appended(db: &PgnDatabase, record: &str) -> (Vec, u64) { - let bytes = db.bytes(); - let (tail, sep) = tail_for(bytes, record); - let mut out = Vec::with_capacity(bytes.len() + tail.len()); - out.extend_from_slice(bytes); - out.extend(tail); - (out, (bytes.len() + sep) as u64) -} - -/// The text of `db` with record `index` replaced by `record` (what [`replace`] writes). -pub fn replaced(db: &PgnDatabase, index: usize, record: &str) -> Result, WriteError> { +/// Replaces record `index` with `record`; every other byte of the file stays. +pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> { + let path = check_writable(db)?; let bytes = db.bytes(); let range = db .entries() @@ -141,11 +124,14 @@ pub fn replaced(db: &PgnDatabase, index: usize, record: &str) -> Result, out.extend_from_slice(&bytes[..range.start]); out.extend(record_bytes(record, eol)); out.extend_from_slice(&bytes[range.end..]); - Ok(out) + write_atomic(path, &out)?; + Ok(()) } -/// The text of `db` without record `index` (what [`remove`] writes) and the record. -pub fn removed(db: &PgnDatabase, index: usize) -> Result<(Vec, Removed), WriteError> { +/// Removes record `index`; the bytes before and after it stay. What was removed comes +/// back with [`restore`]. +pub fn remove(db: &PgnDatabase, index: usize) -> Result { + let path = check_writable(db)?; let bytes = db.bytes(); let range = db .entries() @@ -156,29 +142,11 @@ pub fn removed(db: &PgnDatabase, index: usize) -> Result<(Vec, Removed), Wri let mut out = Vec::with_capacity(bytes.len()); out.extend_from_slice(&bytes[..range.start]); out.extend_from_slice(&bytes[range.end..]); - Ok(( - out, - Removed { - index, - bytes: bytes[range].to_vec(), - }, - )) -} - -/// Replaces record `index` with `record`; every other byte of the file stays. -pub fn replace(db: &PgnDatabase, index: usize, record: &str) -> Result<(), WriteError> { - let path = check_writable(db)?; - write_atomic(path, &replaced(db, index, record)?)?; - Ok(()) -} - -/// Removes record `index`; the bytes before and after it stay. What was removed comes -/// back with [`restore`]. -pub fn remove(db: &PgnDatabase, index: usize) -> Result { - let path = check_writable(db)?; - let (out, gone) = removed(db, index)?; write_atomic(path, &out)?; - Ok(gone) + Ok(Removed { + index, + bytes: bytes[range].to_vec(), + }) } /// Puts a removed record back at its place: the file is byte for byte what it was @@ -186,12 +154,6 @@ pub fn remove(db: &PgnDatabase, index: usize) -> Result { /// database as read after the removal. pub fn restore(db: &PgnDatabase, removed: &Removed) -> Result<(), WriteError> { let path = check_writable(db)?; - write_atomic(path, &restored(db, removed)?)?; - Ok(()) -} - -/// The text of `db` with a removed record back at its place (what [`restore`] writes). -pub fn restored(db: &PgnDatabase, removed: &Removed) -> Result, WriteError> { let bytes = db.bytes(); let at = match db.entries().get(removed.index) { Some(e) => e.byte_range.start, @@ -202,7 +164,8 @@ pub fn restored(db: &PgnDatabase, removed: &Removed) -> Result, WriteErr out.extend_from_slice(&bytes[..at]); out.extend_from_slice(&removed.bytes); out.extend_from_slice(&bytes[at..]); - Ok(out) + write_atomic(path, &out)?; + Ok(()) } /// Writes every record of `db` into `dest` as UTF-8 (LF, one blank line between @@ -232,66 +195,44 @@ pub fn write_utf8_copy(db: &PgnDatabase, dest: &Path) -> io::Result<()> { write_atomic(dest, &out) } -/// What makes two records the same game for [`find_same_game`]: the players (without -/// case) and the date, the start position and the moves of the main line. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct SameGame { - white: String, - black: String, - date: String, - fen: Option, - moves: Vec, -} - -fn same_name(v: Option<&str>) -> String { - v.unwrap_or("?").trim().to_lowercase() -} - -fn same_date(v: Option<&str>) -> String { - // An unknown date in any spelling is one value. - match v.map(str::trim) { - None | Some("" | "?") => "????.??.??".to_owned(), - Some(d) => d.to_owned(), - } -} - -/// The identity of `game` for finding the same game (see [`SameGame`]). -pub fn same_game(game: &crate::Game) -> SameGame { - SameGame { - white: same_name(game.tag("White")), - black: same_name(game.tag("Black")), - date: same_date(game.tag("Date")), - fen: game.tag("FEN").map(str::to_owned), - moves: game - .mainline() - .iter() - .filter_map(|id| game.game_move(*id).map(|m| m.san.clone())) - .collect(), - } -} - -/// The bytes an append writes for `record` into a file that holds only records written -/// so (starting empty): a new database filled in one go has the same bytes as one -/// filled by [`append`] record after record. -pub fn record_for_new_file(record: &str) -> Vec { - record_bytes(record, "\n") -} - /// The record of `db` that is the same game as `game`: the same players and date, and /// the same moves of the main line. `None` when there is none. pub fn find_same_game(db: &PgnDatabase, game: &crate::Game) -> Option { - let key = same_game(game); + // Names compared without case; an unknown date in any spelling is one value. + let name = |v: Option<&str>| v.unwrap_or("?").trim().to_lowercase(); + let date = |v: Option<&str>| match v.map(str::trim) { + None | Some("" | "?") => "????.??.??".to_owned(), + Some(d) => d.to_owned(), + }; + let (white, black, when) = ( + name(game.tag("White")), + name(game.tag("Black")), + date(game.tag("Date")), + ); + let sans: Vec<&str> = game + .mainline() + .iter() + .filter_map(|id| game.game_move(*id).map(|m| m.san.as_str())) + .collect(); (0..db.len()).find(|&i| { let e = &db.entries()[i]; - if same_name(e.white()) != key.white - || same_name(e.black()) != key.black - || same_date(e.date()) != key.date - { + if name(e.white()) != white || name(e.black()) != black || date(e.date()) != when { return false; } + let Some(parsed) = db.load_game(i) else { + return false; + }; // Two studies from different positions are different games. - db.load_game(i) - .is_some_and(|parsed| same_game(&parsed.game) == key) + if parsed.game.tag("FEN") != game.tag("FEN") { + return false; + } + let other: Vec = parsed + .game + .mainline() + .iter() + .filter_map(|id| parsed.game.game_move(*id).map(|m| m.san.clone())) + .collect(); + other.len() == sans.len() && other.iter().zip(&sans).all(|(a, b)| a == b) }) } diff --git a/crates/chess-core/src/repair.rs b/crates/chess-core/src/repair.rs index 77f0831..d095cb3 100644 --- a/crates/chess-core/src/repair.rs +++ b/crates/chess-core/src/repair.rs @@ -45,7 +45,6 @@ impl LetterRepairCounts { } /// Source-level detection result. -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] pub struct LetterRepairDetection { /// Substitution pattern found (see [`detect_letter_substitution`]). @@ -74,18 +73,37 @@ pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> Lette ) { return LetterRepairDetection::default(); } - // The source's letters as they come, never all at once: a large file's text is - // twice its size in UTF-8, four times as `char`s (more than a browser's memory). - let chars = || source_chars(bytes, encoding); - let genuine_letters = chars() + let (text, _) = encoding.decode(bytes); + let genuine_letters = text + .chars() .filter(|c| matches!(c, 'ч' | 'Ч' | 'ю' | 'Ю')) .count(); - let sequences = sequences(chars()); - let markers = chars().filter(|c| matches!(c, '~' | '^')).count(); + let chars: Vec = text.chars().collect(); + let is_cyr = + |c: Option<&char>| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё')); + let mut sequences = 0usize; + let mut i = 0; + while i + 1 < chars.len() { + let pair = [chars[i], chars[i + 1]]; + if TABLE + .iter() + .any(|(s, _)| s.chars().eq(pair.iter().copied())) + { + let before = i.checked_sub(1).and_then(|p| chars.get(p)); + let after = chars.get(i + 2); + if is_cyr(before) || is_cyr(after) { + sequences += 1; + } + i += 2; + } else { + i += 1; + } + } + let markers = chars.iter().filter(|c| matches!(c, '~' | '^')).count(); // Each `~~` has two markers, each `x^` one; `><` has none. let detected = sequences >= MIN_SEQUENCES && genuine_letters * 50 < sequences - && markers * 9 <= sequence_markers(chars()) * 10; + && markers * 9 <= sequence_markers(&chars) * 10; LetterRepairDetection { detected, sequences, @@ -93,53 +111,20 @@ pub fn detect_letter_substitution(bytes: &[u8], encoding: TextEncoding) -> Lette } } -/// The letters of `bytes` in a single-byte `encoding`, decoded a piece at a time (a -/// byte is a letter: any place splits the text). -fn source_chars(bytes: &[u8], encoding: TextEncoding) -> impl Iterator + '_ { - bytes.chunks(1 << 20).flat_map(move |piece| { - let (text, _) = encoding.decode(piece); - text.chars().collect::>() - }) -} - -/// The sequences of the table next to a Cyrillic letter (a pair taken is not looked at -/// again). -fn sequences(chars: impl Iterator) -> usize { - let is_cyr = - |c: Option| c.is_some_and(|c| matches!(c, 'а'..='я' | 'А'..='Я' | 'ё' | 'Ё')); - let mut chars = chars.peekable(); +fn sequence_markers(chars: &[char]) -> usize { let mut n = 0; - let mut before = None; - while let Some(a) = chars.next() { - let Some(&b) = chars.peek() else { break }; - if TABLE.iter().any(|(s, _)| s.chars().eq([a, b])) { - chars.next(); - if is_cyr(before) || is_cyr(chars.peek().copied()) { - n += 1; - } - before = Some(b); - } else { - before = Some(a); - } - } - n -} - -fn sequence_markers(chars: impl Iterator) -> usize { - let mut chars = chars.peekable(); - let mut n = 0; - while let Some(a) = chars.next() { - let Some(&b) = chars.peek() else { break }; - match (a, b) { + let mut i = 0; + while i + 1 < chars.len() { + match (chars[i], chars[i + 1]) { ('~', '~') => { n += 2; - chars.next(); + i += 2; } ('o' | 'о' | 'O' | 'О', '^') => { n += 1; - chars.next(); + i += 2; } - _ => {} + _ => i += 1, } } n diff --git a/crates/chess-import/src/chessbase/base.rs b/crates/chess-import/src/chessbase/base.rs index 4a649e0..24a9bd8 100644 --- a/crates/chess-import/src/chessbase/base.rs +++ b/crates/chess-import/src/chessbase/base.rs @@ -73,8 +73,6 @@ pub(crate) struct Names { folded: Vec, rank: Vec, games: Vec, - white_games: Vec, - black_games: Vec, } impl Names { @@ -92,15 +90,11 @@ impl Names { }; } let games = vec![0; shown.len()]; - let white_games = vec![0; shown.len()]; - let black_games = vec![0; shown.len()]; Names { shown, folded, rank, games, - white_games, - black_games, } } @@ -110,30 +104,6 @@ impl Names { } } - /// Counts one game of a player. A player on both sides still has one game in - /// total, while each colour has that game in its own count. - pub(crate) fn count_player_game(&mut self, white: u32, black: u32) { - self.count(white); - if black != white { - self.count(black); - } - if let Some(n) = self.white_games.get_mut(white as usize) { - *n += 1; - } - if let Some(n) = self.black_games.get_mut(black as usize) { - *n += 1; - } - } - - pub(crate) fn player_counts(&self, id: u32) -> (u32, u32, u32) { - let at = |values: &[u32]| values.get(id as usize).copied().unwrap_or(0); - ( - at(&self.games), - at(&self.white_games), - at(&self.black_games), - ) - } - pub(crate) fn get(&self, id: u32) -> &str { self.shown.get(id as usize).map_or("", String::as_str) } @@ -159,35 +129,19 @@ impl Names { /// Up to `limit` names containing every word of `query`: names starting with /// the first word first, then by number of games. Also the number of matches. pub(crate) fn suggest(&self, query: &str, limit: usize) -> (Vec, usize) { - self.suggest_page(query, 0, limit, false) - } - - /// A page of suggestions. With `all_when_empty`, an empty query lists every - /// non-empty name alphabetically (the Android player picker); otherwise it has - /// the old behaviour and returns no suggestions. - pub(crate) fn suggest_page( - &self, - query: &str, - start: usize, - limit: usize, - all_when_empty: bool, - ) -> (Vec, usize) { let words = words(query); - let all = words.is_empty() && all_when_empty; - if words.is_empty() && !all { + if words.is_empty() { return (Vec::new(), 0); } let mut hits: Vec<(bool, u32, u32)> = self .folded .iter() .enumerate() - .filter(|(_, n)| { - !n.trim().is_empty() && (all || words.iter().all(|w| n.contains(w.as_str()))) - }) + .filter(|(_, n)| words.iter().all(|w| n.contains(w.as_str()))) .map(|(id, n)| { let id = id as u32; ( - !all && !n.starts_with(words[0].as_str()), + !n.starts_with(words[0].as_str()), id, self.games[id as usize], ) @@ -195,18 +149,12 @@ impl Names { .collect(); let total = hits.len(); hits.sort_by(|a, b| { - if all { - self.rank(a.1).cmp(&self.rank(b.1)).then(a.1.cmp(&b.1)) - } else { - a.0.cmp(&b.0) - .then(b.2.cmp(&a.2)) - .then(self.rank(a.1).cmp(&self.rank(b.1))) - .then(a.1.cmp(&b.1)) - } + a.0.cmp(&b.0) + .then(b.2.cmp(&a.2)) + .then(self.rank(a.1).cmp(&self.rank(b.1))) }); let list = hits .into_iter() - .skip(start) .take(limit) .map(|(_, id, games)| Suggestion { id, @@ -266,11 +214,10 @@ pub fn fold(s: &str) -> String { out } -/// Folded words of a search query; commas separate words too ("Carlsen, M"), and so -/// does the full stop of an initial ("Carlsen, M." finds "Carlsen, Magnus"). +/// Folded words of a search query; commas separate words too ("Carlsen, M"). pub(crate) fn words(query: &str) -> Vec { fold(query) - .split(|c: char| c.is_whitespace() || c == ',' || c == '.') + .split(|c: char| c.is_whitespace() || c == ',') .filter(|w| !w.is_empty()) .map(str::to_owned) .collect() @@ -557,7 +504,8 @@ impl Base { if u(0x23, 2) >= 64576 { chess960 += 1; } - base.players.count_player_game(u(0x09, 3), u(0x0c, 3)); + base.players.count(u(0x09, 3)); + base.players.count(u(0x0c, 3)); base.tournaments.count(u(0x0f, 3)); } base.games = games; @@ -1006,40 +954,6 @@ impl Base { } } - /// The first `max_plies` moves of the main line of game `index`, decoded without - /// building the move tree (see [`moves::main_line`]). `None` for a text, a deleted - /// record or unreadable moves. - pub fn main_line(&self, index: usize, max_plies: usize) -> Option { - let Record::Game(h) = self.header(index)? else { - return None; - }; - let bytes = self.read_moves(h.moves_offset)?; - let walk = |fast: bool| -> Result { - let mut line = crate::MainLine::default(); - let mut first = true; - moves::main_line(&bytes, 0, fast, |pos, step| { - if std::mem::take(&mut first) { - line.standard_start = - crate::position::same_position(pos, &shakmaty::Chess::default()); - if !line.standard_start { - return false; - } - } - match step { - moves::Step::Move(m) => { - line.moves.push(*m); - line.moves.len() < max_plies - } - // A null move or the end: the opening line stops here. - moves::Step::Null | moves::Step::End => false, - } - })?; - Ok(line) - }; - // The fast decoder trusts the data: a damaged game is read again carefully. - walk(true).or_else(|_| walk(false)).ok() - } - /// The `.cbg` record at `offset` (its size is in bytes 1-3). fn read_moves(&self, offset: u32) -> Option> { let mut f = self.cbg.lock().ok()?; @@ -1057,21 +971,6 @@ impl Base { self.players.suggest(query, limit) } - /// A page of player names; an empty query lists every named player. - pub fn suggest_players_page( - &self, - query: &str, - start: usize, - limit: usize, - ) -> (Vec, usize) { - self.players.suggest_page(query, start, limit, true) - } - - /// Total, white and black games of a player (a self-game counts once in total). - pub fn player_counts(&self, id: u32) -> (u32, u32, u32) { - self.players.player_counts(id) - } - /// Tournament names ("Title (Place)") for a filter being typed. pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec, usize) { self.tournaments.suggest(query, limit) @@ -1508,9 +1407,6 @@ mod tests { assert_eq!(fold("Hübner, Robert"), "hubner, robert"); assert_eq!(fold("Łukasz Ćwikła"), "lukasz cwikla"); assert_eq!(words(" Carlsen,Magnus "), vec!["carlsen", "magnus"]); - // An initial with its full stop finds the full name. - assert_eq!(words("Вафин, Р."), vec!["вафин", "р"]); - assert_eq!(words("J.R. Capablanca"), vec!["j", "r", "capablanca"]); let names = Names::new(vec![ "Carlsen, Magnus".into(), "Carlsen, Henrik".into(), @@ -1520,9 +1416,6 @@ mod tests { assert_eq!(names.matching("hubner"), vec![false, false, true]); let (list, total) = names.suggest("carl", 1); assert_eq!((list.len(), total), (1, 2)); - let (list, total) = names.suggest("Carlsen, M.", 5); - assert_eq!((list.len(), total), (1, 1)); - assert_eq!(list[0].name, "Carlsen, Magnus"); } #[test] diff --git a/crates/chess-import/src/chessbase/booster.rs b/crates/chess-import/src/chessbase/booster.rs index a08b3ea..ce843ce 100644 --- a/crates/chess-import/src/chessbase/booster.rs +++ b/crates/chess-import/src/chessbase/booster.rs @@ -143,15 +143,6 @@ fn write_all_at(f: &File, buf: &[u8], at: u64) -> io::Result<()> { } Ok(()) } - // Elsewhere (WebAssembly) through the cursor: such a target has no threads to - // share it with. - #[cfg(not(any(unix, windows)))] - { - use std::io::{Seek, SeekFrom, Write}; - let mut f = f; - f.seek(SeekFrom::Start(at))?; - f.write_all(buf) - } } /// One pass over the main lines of `base`, in parallel, writing the booster to @@ -180,70 +171,75 @@ pub(super) fn build( None => None, }; let next = AtomicUsize::new(0); - let threads = crate::parallel::threads(4) + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get()) .min(total.div_ceil(BLOCK)) .max(1); let failure: Mutex> = Mutex::new(None); - crate::parallel::map(vec![(); threads], |()| { - let run = || -> io::Result<()> { - let cbg = File::open(base.cbg_path())?; - let file = part - .as_ref() - .map(|p| File::options().write(true).open(p)) - .transpose()?; - let mut games: Vec<(u32, u32)> = Vec::new(); - let (mut span, mut single) = (Vec::new(), Vec::new()); - let mut block = vec![0u8; BLOCK * CBB_RECORD]; - let mut entries: Vec = Vec::new(); - let mut set_up: Vec = Vec::new(); - loop { - if cancel.load(Ordering::Relaxed) { - return Ok(()); - } - let from = next.fetch_add(BLOCK, Ordering::Relaxed); - if from >= total { - return Ok(()); - } - let to = (from + BLOCK).min(total); - let bytes = &mut block[..(to - from) * CBB_RECORD]; - bytes.fill(0); - entries.clear(); - set_up.clear(); - games.clear(); - for i in from..to { - // Texts and Chess960 games (ECO field ≥ 64576) have no - // record, like in ChessBase's own file. - if base.kind(i) == RecordKind::Game - && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) - { - games.push((i as u32, base.moves_offset(i))); - } - } - read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { - let opening = sink.is_some().then_some(index); - if let Some(d) = game_data(data, rel, opening) { - let at = (index as usize - from) * CBB_RECORD; - bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); - entries.extend(d.opening); - if d.set_up { - set_up.push(index); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let run = || -> io::Result<()> { + let cbg = File::open(base.cbg_path())?; + let file = part + .as_ref() + .map(|p| File::options().write(true).open(p)) + .transpose()?; + let mut games: Vec<(u32, u32)> = Vec::new(); + let (mut span, mut single) = (Vec::new(), Vec::new()); + let mut block = vec![0u8; BLOCK * CBB_RECORD]; + let mut entries: Vec = Vec::new(); + let mut set_up: Vec = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return Ok(()); } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Ok(()); + } + let to = (from + BLOCK).min(total); + let bytes = &mut block[..(to - from) * CBB_RECORD]; + bytes.fill(0); + entries.clear(); + set_up.clear(); + games.clear(); + for i in from..to { + // Texts and Chess960 games (ECO field ≥ 64576) have no + // record, like in ChessBase's own file. + if base.kind(i) == RecordKind::Game + && be(base.record(i), 0x23, 2).is_some_and(|eco| eco < 64576) + { + games.push((i as u32, base.moves_offset(i))); + } + } + read_games(&cbg, &games, &mut span, &mut single, |index, data, rel| { + let opening = sink.is_some().then_some(index); + if let Some(d) = game_data(data, rel, opening) { + let at = (index as usize - from) * CBB_RECORD; + bytes[at..at + CBB_RECORD].copy_from_slice(&d.record); + entries.extend(d.opening); + if d.set_up { + set_up.push(index); + } + } + }); + if let Some(f) = &file { + write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; + } + if let Some(sink) = &sink { + sink.add(&entries, &set_up)?; + } + progress.fetch_add(to - from, Ordering::Relaxed); + } + }; + if let Err(e) = run() { + cancel.store(true, Ordering::Relaxed); + if let Ok(mut f) = failure.lock() { + f.get_or_insert(e); } - }); - if let Some(f) = &file { - write_all_at(f, bytes, ((from + 1) * CBB_RECORD) as u64)?; } - if let Some(sink) = &sink { - sink.add(&entries, &set_up)?; - } - progress.fetch_add(to - from, Ordering::Relaxed); - } - }; - if let Err(e) = run() { - cancel.store(true, Ordering::Relaxed); - if let Ok(mut f) = failure.lock() { - f.get_or_insert(e); - } + }); } }); let clean = || { @@ -269,11 +265,10 @@ pub(super) fn build( // The header last: a file without the count is never taken for a booster. let mut header = [0u8; CBB_RECORD]; header[..4].copy_from_slice(&(count as u32).to_be_bytes()); - { - let file = File::options().write(true).open(part)?; - write_all_at(&file, &header, 0)?; - file.sync_all()?; - } // Closed before the rename. + let file = File::options().write(true).open(part)?; + write_all_at(&file, &header, 0)?; + file.sync_all()?; + drop(file); std::fs::rename(part, out)?; } if let (Some(out), Some(sink)) = (openings, sink) { diff --git a/crates/chess-import/src/chessbase/mod.rs b/crates/chess-import/src/chessbase/mod.rs index 8bdf4de..cf2298b 100644 --- a/crates/chess-import/src/chessbase/mod.rs +++ b/crates/chess-import/src/chessbase/mod.rs @@ -62,22 +62,6 @@ impl Files { Ok(files) } - /// The database whose `.cbh` file is `cbh_name` from files given as (name, content), - /// taking the contents (others are left out). - pub fn from_owned(cbh_name: &str, members: Vec<(String, Vec)>) -> Files { - let stem = stem_of(cbh_name).to_owned(); - let mut files = Files { - name: stem.rsplit('/').next().unwrap_or(&stem).to_owned(), - files: HashMap::new(), - }; - for (name, data) in members { - if let Some(ext) = part_of(&name, &stem) { - files.files.insert(ext, data); - } - } - files - } - /// Picks the files of the database whose `.cbh` member is `cbh_name` from archive /// members (`name`, bytes). pub fn from_members<'a>( @@ -90,7 +74,11 @@ impl Files { files: HashMap::new(), }; for (name, data) in members { - if let Some(ext) = part_of(name, &stem) { + // Names differ in case in sets copied from Windows ("Base.CBH", "base.cbg"). + if let Some(ext) = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()) + && stem_of(name).to_lowercase() == stem.to_lowercase() + && USED.contains(&ext.as_str()) + { files.files.insert(ext, data.to_vec()); } } @@ -112,18 +100,7 @@ impl Files { } /// Files the reader uses; the others (search boosters, settings, media) are ignored. -pub const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"]; - -/// The files a database cannot be read without (the others hold names and comments). -pub const REQUIRED: [&str; 2] = ["cbh", "cbg"]; - -/// The extension of `name` when it is a file of the database `stem` the reader uses -/// (names differ in case in sets copied from Windows: "Base.CBH", "base.cbg"). -fn part_of(name: &str, stem: &str) -> Option { - let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase())?; - (stem_of(name).to_lowercase() == stem.to_lowercase() && USED.contains(&ext.as_str())) - .then_some(ext) -} +const USED: [&str; 6] = ["cbh", "cbg", "cba", "cbp", "cbt", "cbc"]; fn stem_of(name: &str) -> &str { name.rsplit_once('.').map_or(name, |(s, _)| s) diff --git a/crates/chess-import/src/chessbase/openings.rs b/crates/chess-import/src/chessbase/openings.rs index d4911a3..78375c1 100644 --- a/crates/chess-import/src/chessbase/openings.rs +++ b/crates/chess-import/src/chessbase/openings.rs @@ -314,12 +314,13 @@ impl Sink { let keys_len = keys.len() as u64; file.write_all(&keys)?; drop(keys); + let mut games = games.into_inner().map_err(|e| e.into_error())?; { use std::io::Seek; - let mut games = games.into_inner().map_err(|e| e.into_error())?; games.seek(io::SeekFrom::Start(0))?; io::copy(&mut games, &mut file)?; - } // Closed before it is removed. + } + drop(games); let _ = std::fs::remove_file(&games_path); // The games from a set-up position, ascending. let mut set_up = @@ -329,16 +330,17 @@ impl Sink { file.write_all(&g.to_le_bytes())?; } let set_up_len = set_up.len() as u64 * 4; + let mut file = file.into_inner().map_err(|e| e.into_error())?; { use std::io::Seek; - let mut file = file.into_inner().map_err(|e| e.into_error())?; file.seek(io::SeekFrom::Start(16))?; file.write_all(&prefix_len.to_le_bytes())?; file.write_all(&keys_len.to_le_bytes())?; file.write_all(&games_len.to_le_bytes())?; file.write_all(&set_up_len.to_le_bytes())?; - file.sync_all()?; - } // Closed before the rename. + } + file.sync_all()?; + drop(file); std::fs::rename(&part, out)?; Ok(true) } @@ -576,17 +578,22 @@ impl Index { } // Millions of games for an early position: tallied in parallel, each part // keeping its order. - let threads = crate::parallel::threads(1) + let threads = std::thread::available_parallelism() + .map_or(1, |n| n.get()) .min(games.len().div_ceil(1 << 16)) .max(1); let chunk = games.len().div_ceil(threads).max(1); let line = &line; - let parts: Vec = crate::parallel::map(games.chunks(chunk).collect(), |part| { - self.tally(base, part, line) - }) - .into_iter() - .map(Option::unwrap_or_default) - .collect(); + let parts: Vec = std::thread::scope(|s| { + let handles: Vec<_> = games + .chunks(chunk) + .map(|part| s.spawn(move || self.tally(base, part, line))) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap_or_default()) + .collect() + }); let mut out = Collector::default(); for part in parts { out.merge(part); diff --git a/crates/chess-import/src/chessbase/search.rs b/crates/chess-import/src/chessbase/search.rs index c680eeb..a8c5dfa 100644 --- a/crates/chess-import/src/chessbase/search.rs +++ b/crates/chess-import/src/chessbase/search.rs @@ -32,18 +32,11 @@ pub(super) const CBB_RECORD: usize = 52; /// booster is left out (it would read its whole file to rule out almost nothing). const SAMPLE: usize = 4096; -#[derive(Clone, Copy, PartialEq, Eq)] -enum SearchMode { - Explorer, - PlayedLine, -} - /// Games among `candidates` (record indices in ascending order; `None`: all records) /// whose main line reaches the position. `scanned` counts the candidates looked at. /// `None` when cancelled. -fn search_inner( +pub fn search( base: &Base, - mode: SearchMode, candidates: Option<&[u32]>, query: &PositionQuery, scanned: &AtomicUsize, @@ -51,12 +44,11 @@ fn search_inner( ) -> Option { // A position of the opening: the index knows its games, except those from a // set-up position, which the pass looks at. - if mode == SearchMode::Explorer - && let Some(index) = base.openings() + if let Some(index) = base.openings() && index.answers(query, candidates) { let others = index.set_up_games(candidates); - let mut out = collect(base, Some(&others), query, scanned, cancel, false)?; + let mut out = collect(base, Some(&others), query, scanned, cancel)?; if cancel.load(Ordering::Relaxed) { return None; } @@ -65,51 +57,7 @@ fn search_inner( scanned.fetch_add(total.saturating_sub(others.len()), Ordering::Relaxed); return Some(out.finish(&query.position)); } - collect( - base, - candidates, - query, - scanned, - cancel, - mode == SearchMode::PlayedLine, - ) - .map(|c| c.finish(&query.position)) -} - -/// The position explorer: it may use the opening index. -pub fn search( - base: &Base, - candidates: Option<&[u32]>, - query: &PositionQuery, - scanned: &AtomicUsize, - cancel: &AtomicBool, -) -> Option { - search_inner( - base, - SearchMode::Explorer, - candidates, - query, - scanned, - cancel, - ) -} - -/// The played-line preparation: never take the bounded opening index shortcut. -pub fn search_first( - base: &Base, - candidates: Option<&[u32]>, - query: &PositionQuery, - scanned: &AtomicUsize, - cancel: &AtomicBool, -) -> Option { - search_inner( - base, - SearchMode::PlayedLine, - candidates, - query, - scanned, - cancel, - ) + collect(base, candidates, query, scanned, cancel).map(|c| c.finish(&query.position)) } /// The pass of [`search`]: the matches in record order and the statistics, not yet @@ -120,54 +68,61 @@ fn collect( query: &PositionQuery, scanned: &AtomicUsize, cancel: &AtomicBool, - played_line: bool, ) -> Option { let total = candidates.map_or(base.records(), <[u32]>::len); if total == 0 { return Some(Collector::default()); } - let target = Target::new(query, played_line); + let target = Target::new(query); let cbb = base .cbb_path() .filter(|p| booster_helps(p, &target.signature)); let next = AtomicUsize::new(0); - let threads = crate::parallel::threads(4) + let threads = std::thread::available_parallelism() + .map_or(4, |n| n.get()) .min(total.div_ceil(BLOCK)) .max(1); // Per thread: its collector and, per block, (first candidate, first match). type Part = (Collector, Vec<(usize, usize)>); - let parts: Vec> = crate::parallel::map(vec![(); threads], |()| { - let mut worker = Worker { - base, - target: &target, - cbg: File::open(base.cbg_path()).ok()?, - cbb: cbb.and_then(|p| File::open(p).ok()), - games: Vec::new(), - span: Vec::new(), - single: Vec::new(), - out: Collector::default(), - }; - let mut blocks = Vec::new(); - loop { - if cancel.load(Ordering::Relaxed) { - return None; - } - let from = next.fetch_add(BLOCK, Ordering::Relaxed); - if from >= total { - return Some((worker.out, blocks)); - } - let to = (from + BLOCK).min(total); - blocks.push((from, worker.out.matches.len())); - match candidates { - Some(c) => worker.block(c[from..to].iter().copied()), - None => worker.block(from as u32..to as u32), - } - scanned.fetch_add(to - from, Ordering::Relaxed); - } - }) - .into_iter() - .map(Option::flatten) - .collect(); + let parts: Vec> = std::thread::scope(|s| { + let handles: Vec<_> = (0..threads) + .map(|_| { + s.spawn(|| { + let mut worker = Worker { + base, + target: &target, + cbg: File::open(base.cbg_path()).ok()?, + cbb: cbb.and_then(|p| File::open(p).ok()), + games: Vec::new(), + span: Vec::new(), + single: Vec::new(), + out: Collector::default(), + }; + let mut blocks = Vec::new(); + loop { + if cancel.load(Ordering::Relaxed) { + return None; + } + let from = next.fetch_add(BLOCK, Ordering::Relaxed); + if from >= total { + return Some((worker.out, blocks)); + } + let to = (from + BLOCK).min(total); + blocks.push((from, worker.out.matches.len())); + match candidates { + Some(c) => worker.block(c[from..to].iter().copied()), + None => worker.block(from as u32..to as u32), + } + scanned.fetch_add(to - from, Ordering::Relaxed); + } + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().ok().flatten()) + .collect() + }); if cancel.load(Ordering::Relaxed) { return None; } @@ -209,11 +164,10 @@ struct Target { line: Option>, start: Chess, signature: Signature, - played_line: bool, } impl Target { - fn new(query: &PositionQuery, played_line: bool) -> Target { + fn new(query: &PositionQuery) -> Target { let b = query.position.board(); let side = |c: Color| b.by_color(c); let pawns = |c: Color| side(c) & b.pawns(); @@ -229,7 +183,6 @@ impl Target { line: query.line.as_ref().map(|l| l.iter().map(uci).collect()), start: Chess::default(), signature: Signature::new(b), - played_line, } } @@ -249,15 +202,8 @@ impl Target { fn find(&self, cbg: &[u8], offset: u32, fast: bool) -> Result, WalkError> { let mut ply = 0u32; let mut in_order = self.line.is_some(); - let mut after_null = false; let mut hit = None; moves::main_line(cbg, offset, fast, |pos, step| { - if self.played_line && after_null { - return false; - } - if self.played_line && matches!(step, Step::Null) { - after_null = true; - } if ply == 0 && in_order && !same_position(pos, &self.start) { in_order = false; } @@ -546,15 +492,6 @@ fn read_at(f: &File, buf: &mut [u8], at: u64) -> std::io::Result { { std::os::windows::fs::FileExt::seek_read(f, buf, at) } - // Elsewhere (WebAssembly) through the cursor: such a target has no threads to - // share it with. - #[cfg(not(any(unix, windows)))] - { - use std::io::{Read, Seek, SeekFrom}; - let mut f = f; - f.seek(SeekFrom::Start(at))?; - f.read(buf) - } } fn read_exact_at(f: &File, mut buf: &mut [u8], mut at: u64) -> std::io::Result<()> { @@ -778,31 +715,6 @@ mod tests { assert_eq!(continuations as usize + nulls, want.len()); let ended = want.iter().filter(|w| w.2.is_none()).count(); assert_eq!(out.ended.games as usize, ended); - let first = search_first( - &base, - candidates, - &query, - &AtomicUsize::new(0), - &AtomicBool::new(false), - ) - .expect("played-line search"); - let actual: Vec<(u32, u32, Option)> = first - .matches - .iter() - .map(|m| (m.index, m.ply, m.next)) - .collect(); - let expected: Vec<(u32, u32, Option)> = want - .iter() - .filter(|(index, ply, _)| { - !lines[*index as usize].as_ref().is_some_and(|line| { - line[..*ply as usize] - .iter() - .any(|(_, next)| *next == Some(UciMove::Null)) - }) - }) - .cloned() - .collect(); - assert_eq!(actual, expected, "{name}: played-line first occurrence"); } } } diff --git a/crates/chess-import/src/lib.rs b/crates/chess-import/src/lib.rs index 7bc2f33..c3a20aa 100644 --- a/crates/chess-import/src/lib.rs +++ b/crates/chess-import/src/lib.rs @@ -8,13 +8,10 @@ //! records and a game is converted to PGN when it is opened. Sources are only read. mod archive; -// Timings of a database on disk: a command of the desktop program. -#[cfg(not(target_family = "wasm"))] pub mod bench; pub mod cbv; pub mod chessbase; pub mod memory; -mod parallel; pub mod pgn_catalog; pub mod pgn_positions; pub mod position; @@ -66,9 +63,6 @@ pub enum Unsupported { Encrypted, #[error("the ChessBase 2CBH format is not supported; export the database as CBH or PGN")] ChessBase2, - /// A ChessBase database's `.cbh` given alone: its other files are needed too. - #[error("a ChessBase database is several files: open its folder")] - ChessBaseFiles, } /// What a database was read from. @@ -82,14 +76,6 @@ pub enum Format { } impl Format { - pub const ALL: [Format; 5] = [ - Format::Pgn, - Format::ChessBase, - Format::ChessBaseArchive, - Format::Zip, - Format::SevenZip, - ]; - pub fn label(self) -> &'static str { match self { Format::Pgn => "PGN", @@ -185,14 +171,6 @@ impl std::ops::Deref for PgnDb { } } -/// The beginning of a game's main line (see [`Database::main_line`]). -#[derive(Clone, Debug, Default)] -pub struct MainLine { - /// The game starts from the usual position; otherwise `moves` is empty. - pub standard_start: bool, - pub moves: Vec, -} - /// An opened database. pub enum Database { Pgn(PgnDb), @@ -235,34 +213,6 @@ impl Database { } } - /// The first `max_plies` moves of the main line of record `index`, for passes - /// over the openings of many games: a ChessBase game is decoded without its tree - /// (microseconds), a PGN game is parsed. The line stops at a teaching null move. - /// `None` for a text, a deleted record or unreadable moves. - pub fn main_line(&self, index: usize, max_plies: usize) -> Option { - match self { - Database::Pgn(db) => { - let parsed = db.load_game(index)?; - let game = &parsed.game; - let mut line = MainLine { - standard_start: game.start().is_standard(), - moves: Vec::new(), - }; - if !line.standard_start { - return Some(line); - } - for id in game.mainline().into_iter().take(max_plies) { - match game.game_move(id).map(|m| &m.kind) { - Some(chess_core::MoveKind::Normal(m)) => line.moves.push(*m), - _ => break, - } - } - Some(line) - } - Database::ChessBase(b) => b.main_line(index, max_plies), - } - } - /// Bytes that identify record `index` (its content for PGN, its `.cbh` record for /// ChessBase), for remembering viewed games. pub fn identity(&self, index: usize) -> &[u8] { @@ -309,25 +259,6 @@ impl Database { } } - /// Search the main line, counting each played game once at its first occurrence. - pub fn search_position_first( - &self, - candidates: Option<&[u32]>, - query: &position::PositionQuery, - progress: &AtomicUsize, - cancel: &AtomicBool, - ) -> Option { - match self { - Database::Pgn(db) => { - let table = db.positions(progress, cancel)?; - table.search_first(&db.db, candidates, query, cancel) - } - Database::ChessBase(b) => { - chessbase::search::search_first(b, candidates, query, progress, cancel) - } - } - } - /// Memory a position search would need first and does not have (a PGN /// database's table, see [`PgnDb::positions_blocked`]). pub fn positions_blocked(&self) -> Option { @@ -406,14 +337,6 @@ impl Database { } } - /// The name of player `id` (from a suggestion), as the game list shows it. - pub fn player_name(&self, id: u32) -> &str { - match self { - Database::Pgn(db) => db.catalog().player_name(id), - Database::ChessBase(b) => b.player_name(id), - } - } - pub fn suggest_events( &self, query: &str, @@ -594,7 +517,11 @@ pub fn open_bytes( match ext.as_str() { "cbz" => return Err(ImportError::Unsupported(Unsupported::Encrypted)), "2cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBase2)), - "cbh" => return Err(ImportError::Unsupported(Unsupported::ChessBaseFiles)), + "cbh" => { + return Err(ImportError::Corrupt( + "a ChessBase database is several files: open its folder".into(), + )); + } _ => {} } if let Some(kind) = archive::sniff(&bytes) { @@ -640,93 +567,6 @@ pub fn open_chessbase_files( finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) } -/// [`open_chessbase_files`] taking the contents: each file's bytes are let go once -/// the database is converted (the browser reads databases near its memory's limit). -pub fn open_chessbase_owned( - cbh_name: &str, - files: Vec<(String, Vec)>, - progress: &mut dyn FnMut(ScanProgress), - cancel: &AtomicBool, -) -> Result { - let members = chessbase::Files::from_owned(cbh_name, files); - let part = convert_chessbase(&members)?; - drop(members); - finish(part.pgn, Format::ChessBase, part.notes, progress, cancel) -} - -/// What files the user chose (or found in a chosen folder) make: databases, each its -/// files' places in the list (the database's own file first: its `.cbh` for a -/// ChessBase one, with the files the reader uses after it), and ChessBase databases -/// some files of which are not among them. -#[derive(Debug, Default, PartialEq, Eq)] -pub struct Chosen { - pub databases: Vec>, - /// The database's name (the `.cbh` file's, or a part's when it is not there). - pub incomplete: Vec, -} - -/// Groups the files `names` into databases (see [`Chosen`]). A ChessBase database is -/// its `.cbh` and the files of the same name beside it; files of other kinds are -/// databases of their own — in a folder only those of [`EXTENSIONS`], when the user -/// chose them, any (the content decides, as in [`open`]). -pub fn group_chosen(names: &[&str], folder: bool) -> Chosen { - let lower: Vec = names.iter().map(|n| n.to_lowercase()).collect(); - let ext = |i: usize| { - lower[i] - .rsplit_once('.') - .map(|(_, e)| e.to_owned()) - .unwrap_or_default() - }; - let stem = |i: usize| { - lower[i] - .rsplit_once('.') - .map_or(lower[i].as_str(), |(s, _)| s) - .to_owned() - }; - let bases: Vec = (0..names.len()).filter(|&i| ext(i) == "cbh").collect(); - let mut chosen = Chosen::default(); - let mut taken = vec![false; names.len()]; - for &cbh in &bases { - let parts: Vec = (0..names.len()) - .filter(|&j| j != cbh && stem(j) == stem(cbh)) - .collect(); - for &j in &parts { - taken[j] = true; - } - taken[cbh] = true; - let has = |e: &str| e == "cbh" || parts.iter().any(|&j| ext(j) == e); - if chessbase::REQUIRED.iter().all(|e| has(e)) { - let mut db = vec![cbh]; - db.extend( - parts - .into_iter() - .filter(|&j| chessbase::USED.contains(&ext(j).as_str())), - ); - chosen.databases.push(db); - } else { - chosen.incomplete.push(names[cbh].to_owned()); - } - } - for i in 0..names.len() { - if taken[i] { - continue; - } - let e = ext(i); - if chessbase::USED.contains(&e.as_str()) { - // A part of a ChessBase database without its .cbh: one note per database. - taken[i] = true; - let own = names[i].rsplit_once('.').map_or(names[i], |(s, _)| s); - let name = format!("{own}.cbh"); - if !chosen.incomplete.contains(&name) { - chosen.incomplete.push(name); - } - } else if !folder || EXTENSIONS.contains(&e.as_str()) { - chosen.databases.push(vec![i]); - } - } - chosen -} - /// A converted part of a database: UTF-8 PGN and notes. struct Part { pgn: String, @@ -861,39 +701,3 @@ fn finish( notes, }) } - -#[cfg(test)] -mod chosen_tests { - use super::*; - - #[test] - fn files_chosen_make_databases() { - // A whole ChessBase set (case of Windows copies), a PGN, a text file. - let names = [ - "Base.CBH", - "base.cbg", - "Base.cba", - "Base.cbj", - "Base.ini", - "games.pgn", - "x.txt", - ]; - let c = group_chosen(&names, false); - // The settings file is the database's (ignored); a file chosen opens by content. - assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5], vec![6]]); - assert!(c.incomplete.is_empty()); - // In a folder only databases: no text files. - let c = group_chosen(&names, true); - assert_eq!(c.databases, vec![vec![0, 1, 2], vec![5]]); - } - - #[test] - fn a_cbh_alone_or_parts_alone_are_incomplete() { - let c = group_chosen(&["Mega Database 2026.cbh"], false); - assert!(c.databases.is_empty()); - assert_eq!(c.incomplete, vec!["Mega Database 2026.cbh".to_owned()]); - let c = group_chosen(&["Mega.cbg", "Mega.cba"], false); - assert!(c.databases.is_empty()); - assert_eq!(c.incomplete, vec!["Mega.cbh".to_owned()]); - } -} diff --git a/crates/chess-import/src/parallel.rs b/crates/chess-import/src/parallel.rs deleted file mode 100644 index 99c0c30..0000000 --- a/crates/chess-import/src/parallel.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Worker threads of the parallel passes (booster, position search, opening tallies). -//! -//! A target without threads (WebAssembly in a browser: `std::thread::spawn` panics -//! there) runs every pass on the calling thread; so does a pass with one worker. - -/// Workers for a parallel pass: the threads the system offers, `fallback` when it -/// cannot tell; always one where there are no threads. -pub(crate) fn threads(fallback: usize) -> usize { - if cfg!(target_family = "wasm") { - return 1; - } - std::thread::available_parallelism().map_or(fallback, |n| n.get()) -} - -/// `work` for every item, each on its own scoped thread, results in the items' order -/// (`None`: that worker panicked). One item runs on the calling thread. -pub(crate) fn map(items: Vec, work: F) -> Vec> -where - I: Send, - T: Send, - F: Fn(I) -> T + Sync, -{ - if items.len() <= 1 { - return items.into_iter().map(|i| Some(work(i))).collect(); - } - let work = &work; - std::thread::scope(|s| { - let handles: Vec<_> = items - .into_iter() - .map(|i| s.spawn(move || work(i))) - .collect(); - handles.into_iter().map(|h| h.join().ok()).collect() - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn keeps_order_and_runs_one_inline() { - let out = map(vec![3, 1, 2], |n| n * 10); - assert_eq!(out, vec![Some(30), Some(10), Some(20)]); - let here = std::thread::current().id(); - let one = map(vec![()], |()| std::thread::current().id()); - assert_eq!(one, vec![Some(here)]); - assert!(map(Vec::::new(), |n| n).is_empty()); - } - - #[test] - fn a_panicking_worker_gives_none() { - let out = map(vec![0, 1], |n| { - assert!(n == 0, "worker {n}"); - n - }); - assert_eq!(out, vec![Some(0), None]); - } -} diff --git a/crates/chess-import/src/pgn_catalog.rs b/crates/chess-import/src/pgn_catalog.rs index 6acfc21..12bdd49 100644 --- a/crates/chess-import/src/pgn_catalog.rs +++ b/crates/chess-import/src/pgn_catalog.rs @@ -225,8 +225,8 @@ impl Catalog { let white: Vec = ids.iter().step_by(2).copied().collect(); let black: Vec = ids.iter().skip(1).step_by(2).copied().collect(); let mut players = Names::new(names); - for sides in ids.as_chunks::<2>().0 { - players.count_player_game(sides[0], sides[1]); + for &id in &ids { + players.count(id); } let (event_names, event) = intern(entries.iter().map(event_name)); let mut events = Names::new(event_names); @@ -311,55 +311,6 @@ impl Catalog { self.players.suggest(query, limit) } - /// A page of player names; an empty query lists every named player. - pub fn suggest_players_page( - &self, - query: &str, - start: usize, - limit: usize, - ) -> (Vec, usize) { - self.players.suggest_page(query, start, limit, true) - } - - /// Total, white and black games of a player (a self-game counts once in total). - pub fn player_counts(&self, id: u32) -> (u32, u32, u32) { - self.players.player_counts(id) - } - - /// Games of exactly player `id` on one side, in record order. Ids come from - /// [`Catalog::suggest_players_page`] and represent normalized distinct names; - /// a self-game is returned once for either selected side. - pub fn player_games( - &self, - id: u32, - side: Side, - scanned: &AtomicUsize, - cancel: &AtomicBool, - ) -> Option> { - if self.player_name(id).is_empty() || !matches!(side, Side::White | Side::Black) { - return Some(Vec::new()); - } - let mut games = Vec::new(); - for i in 0..self.white.len() { - if i % 4096 == 0 { - if cancel.load(Ordering::Relaxed) { - return None; - } - scanned.store(i, Ordering::Relaxed); - } - let player = match side { - Side::White => self.white[i], - Side::Black => self.black[i], - Side::Any => continue, - }; - if !self.text[i] && player == id { - games.push(i as u32); - } - } - scanned.store(self.white.len(), Ordering::Relaxed); - (!cancel.load(Ordering::Relaxed)).then_some(games) - } - pub fn suggest_events(&self, query: &str, limit: usize) -> (Vec, usize) { self.events.suggest(query, limit) } diff --git a/crates/chess-import/src/pgn_positions.rs b/crates/chess-import/src/pgn_positions.rs index 400c66c..f1c5d4a 100644 --- a/crates/chess-import/src/pgn_positions.rs +++ b/crates/chess-import/src/pgn_positions.rs @@ -262,54 +262,6 @@ impl PositionTable { Some(collector.finish(&query.position)) } - /// The first main-line occurrence of every game, not a variation or a repetition. - pub fn search_first( - &self, - db: &PgnDatabase, - candidates: Option<&[u32]>, - query: &PositionQuery, - cancel: &AtomicBool, - ) -> Option { - let _ = db; - let key = query.key(); - let lo = self.keys.partition_point(|&k| k < key); - let hi = lo + self.keys[lo..].partition_point(|&k| k == key); - let line: Option> = query - .line - .as_ref() - .map(|l| l.iter().map(|m| encode(position::uci(m))).collect()); - let mut collector = Collector::default(); - let mut cand = 0; - let mut game = 0; - let mut i = lo; - while i < hi { - if (i - lo) % 4096 == 0 && cancel.load(Ordering::Relaxed) { - return None; - } - let node = self.refs[i] >> 1; - if node >= self.starts[game + 1] { - game += self.starts[game..].partition_point(|&s| s <= node) - 1; - } - let end = self.starts[game + 1]; - let mut j = i + 1; - while j < hi && self.refs[j] >> 1 < end { - j += 1; - } - let wanted = match candidates { - None => true, - Some(c) => { - cand += c[cand..].partition_point(|&g| (g as usize) < game); - c.get(cand).is_some_and(|&g| g as usize == game) - } - }; - if wanted { - self.collect_first(game, &self.refs[i..j], line.as_deref(), &mut collector); - } - i = j; - } - Some(collector.finish(&query.position)) - } - /// Adds game `game` whose entries for the position are `refs`. fn collect(&self, game: usize, refs: &[u32], line: Option<&[u16]>, out: &mut Collector) { let meta = self.meta[game]; @@ -386,59 +338,6 @@ impl PositionTable { } } - fn collect_first(&self, game: usize, refs: &[u32], line: Option<&[u16]>, out: &mut Collector) { - let meta = self.meta[game]; - let mut occurrences = refs.iter().filter_map(|&r| { - let node = (r >> 1) as usize; - (!self.nodes[node].in_variation()).then_some((node, r & 1 == 1)) - }); - let Some((raw_at, ended)) = occurrences.next() else { - return; - }; - let at = if ended { - raw_at - } else { - self.nodes[raw_at].parent().unwrap_or(raw_at) - }; - let next = if ended { - None - } else { - Some(decode(self.nodes[raw_at].mv)) - }; - if self.after_teaching_null(at) { - return; - } - let same_order = self.same_order(at, meta, line); - let index = game as u32; - out.add( - Match { - index, - ply: u32::from(self.nodes[at].ply), - same_order, - in_variation: false, - next, - }, - next, - meta.result, - meta.white_elo, - meta.black_elo, - meta.year, - ); - } - - /// A position after a teaching null move is not part of the played opening line. - fn after_teaching_null(&self, at: usize) -> bool { - let mut current = Some(at); - while let Some(node) = current { - let n = self.nodes[node]; - if n.parent().is_some() && n.mv == NULL_MOVE { - return true; - } - current = n.parent(); - } - false - } - /// The move of the first child of node `at` among the entries `refs` of its game /// (children come in text order, so the smallest node is the main continuation). fn first_child_move(&self, at: usize, refs: &[u32]) -> Option { @@ -749,90 +648,6 @@ mod tests { ); } - #[test] - fn the_played_line_counts_only_its_first_occurrence() { - let db = db(PGN); - let t = table(&db); - let out = t - .search_first( - &db, - None, - &query(&["d4", "d5", "Nf3"]), - &AtomicBool::new(false), - ) - .unwrap(); - let found: Vec<(u32, u32)> = out.matches.iter().map(|m| (m.index, m.ply)).collect(); - assert_eq!(found, vec![(0, 3), (1, 3), (3, 3), (4, 0), (6, 3)]); - assert_eq!( - out.moves - .iter() - .map(|m| (m.san.as_str(), m.tally.games, m.main_line_games)) - .collect::>(), - vec![("Nf6", 3, 3), ("e6", 1, 1)] - ); - assert_eq!(out.ended.games, 1); - assert_eq!(out.ended.draws, 1); - let nf6 = &out.moves[0]; - assert_eq!((nf6.tally.white_wins, nf6.tally.black_wins), (2, 1)); - assert!(out.matches.iter().all(|m| !m.in_variation)); - assert_eq!( - out.matches - .iter() - .map(|m| m.index) - .filter(|&i| i == 2) - .count(), - 0 - ); - assert_eq!(out.matches[0].next, Some(nf6.uci)); - assert_eq!(out.matches[2].next, None); - let candidates = t - .search_first( - &db, - Some(&[0, 2, 6]), - &query(&["d4", "d5", "Nf3"]), - &AtomicBool::new(false), - ) - .unwrap(); - assert_eq!( - candidates - .matches - .iter() - .map(|m| m.index) - .collect::>(), - vec![0, 6] - ); - let after_null: Chess = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2" - .parse::() - .unwrap() - .into_position(shakmaty::CastlingMode::Standard) - .unwrap(); - let after_null = t - .search_first( - &db, - None, - &PositionQuery::new(after_null, None), - &AtomicBool::new(false), - ) - .unwrap(); - assert!( - after_null.matches.is_empty(), - "a teaching null move is not a played continuation" - ); - // A repeated position must not choose a later transposition branch. - let repeat = crate::pgn_positions::tests::db( - "[Event \"repeat\"]\n1. Nf3 d5 2. d4 Nf6 3. Ng1 Ng8 4. Nf3 e6 *\n", - ); - let table = table(&repeat); - let q = query(&["Nf3", "d5", "d4", "Nf6", "Ng1", "Ng8", "Nf3"]); - let out = table - .search_first(&repeat, None, &q, &AtomicBool::new(false)) - .unwrap(); - assert_eq!(out.matches[0].ply, 3); - assert!(!out.matches[0].same_order); - assert_eq!(out.moves[0].san, "Nf6"); - assert_eq!(out.moves.len(), 1); - } - #[test] fn next_move_belongs_to_the_chosen_occurrence() { // The main line ends in the position; a variation reaches it and goes on. diff --git a/crates/chess-import/src/position.rs b/crates/chess-import/src/position.rs index 6678f45..1c15a15 100644 --- a/crates/chess-import/src/position.rs +++ b/crates/chess-import/src/position.rs @@ -281,85 +281,6 @@ pub fn uci(m: &Move) -> UciMove { m.to_uci(shakmaty::CastlingMode::Standard) } -/// Plies of a line checked one by one by [`theory_end`] before the end of the theory is -/// found by halving (an opening index answers the first plies at once). -pub const THEORY_LINEAR: usize = 12; - -/// Where a line of `total` positions leaves the "theory" of a database, as -/// [`theory_end`] finds it: indices into the line. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct TheoryEnd { - /// The last position still known to the database. - pub last_known: Option, - /// The first position it does not know; `None` when the whole line is known. - pub first_unknown: Option, -} - -/// Finds how far a line of `total` positions is known to a database, with as few -/// searches as possible: `known(i)` says whether position `i` is (`None`: cancelled, -/// the search stops too). A position is nearly always known when a later one of the -/// same line is, so the first plies are checked one by one, then the end is found by -/// doubling and halving. `from`: the positions before it are known already (a game -/// that grew past a theory reaching its end checks only the new moves). -pub fn theory_end( - total: usize, - from: usize, - mut known: impl FnMut(usize) -> Option, -) -> Option { - let from = from.min(total); - let linear_end = if from > 0 { - from - } else { - total.min(THEORY_LINEAR) - }; - let mut last_known: Option = from.checked_sub(1); - let mut first_unknown = None; - for ply in from..linear_end { - if known(ply)? { - last_known = Some(ply); - } else { - first_unknown = Some(ply); - break; - } - } - if first_unknown.is_none() && total > linear_end { - let mut lo = linear_end - 1; - let mut step = 2; - let mut hi = total; - while lo + step < total { - if known(lo + step)? { - lo += step; - step *= 2; - } else { - hi = lo + step; - break; - } - } - if hi == total && lo + 1 < total { - // Past the last doubling: the end of the line itself. - if known(total - 1)? { - lo = total - 1; - } - } - while hi - lo > 1 { - let mid = (lo + hi) / 2; - if known(mid)? { - lo = mid; - } else { - hi = mid; - } - } - last_known = Some(lo); - if hi < total { - first_unknown = Some(hi); - } - } - Some(TheoryEnd { - last_known, - first_unknown, - }) -} - #[cfg(test)] mod tests { use super::*; @@ -383,48 +304,6 @@ mod tests { assert!(!same_position(&a, &play(&["d4", "d5"]))); } - #[test] - fn theory_end_finds_the_boundary_with_few_searches() { - for total in [1usize, 5, 12, 13, 20, 40, 100] { - for boundary in 0..=total { - // Positions before `boundary` are known. - let mut asked = 0; - let end = theory_end(total, 0, |i| { - asked += 1; - Some(i < boundary) - }) - .expect("not cancelled"); - let expect_last = boundary.checked_sub(1); - let expect_first = (boundary < total).then_some(boundary); - assert_eq!( - (end.last_known, end.first_unknown), - (expect_last, expect_first), - "total {total}, boundary {boundary}" - ); - assert!(asked <= THEORY_LINEAR + 2 * 8, "{asked} searches"); - } - } - // Cancelled: no answer. - assert_eq!(theory_end(10, 0, |_| None), None); - // Continuing from a known prefix. - let end = theory_end(10, 4, |i| Some(i < 7)).expect("end"); - assert_eq!( - end, - TheoryEnd { - last_known: Some(6), - first_unknown: Some(7) - } - ); - let end = theory_end(10, 4, |_| Some(true)).expect("end"); - assert_eq!( - end, - TheoryEnd { - last_known: Some(9), - first_unknown: None - } - ); - } - #[test] fn collector_counts_and_names_moves() { let pos = Chess::default(); diff --git a/crates/chess-import/tests/formats.rs b/crates/chess-import/tests/formats.rs index 3903e43..cad488c 100644 --- a/crates/chess-import/tests/formats.rs +++ b/crates/chess-import/tests/formats.rs @@ -61,12 +61,10 @@ fn pgn_and_archives_open_from_bytes() { let z = chess_import::open_bytes("games.zip", bytes, &mut |_| {}, &never).expect("opens"); assert_eq!(z.format, Format::Zip); assert_eq!(z.db.raw_text(0), pgn.db.raw_text(0)); - // A .cbh alone is not a database: its other files are needed. + // A .cbh alone is not a database. assert!(matches!( chess_import::open_bytes("base.cbh", vec![0; 46], &mut |_| {}, &never), - Err(ImportError::Unsupported( - chess_import::Unsupported::ChessBaseFiles - )) + Err(ImportError::Corrupt(_)) )); } diff --git a/crates/game-review/Cargo.toml b/crates/game-review/Cargo.toml index 97583ee..44a1452 100644 --- a/crates/game-review/Cargo.toml +++ b/crates/game-review/Cargo.toml @@ -12,7 +12,5 @@ publish = false chess-core.workspace = true shakmaty.workspace = true uci.workspace = true -chess-openings.workspace = true serde.workspace = true serde_json.workspace = true -web-time.workspace = true diff --git a/crates/game-review/chesscom/README.md b/crates/game-review/chesscom/README.md deleted file mode 100644 index 24c3287..0000000 --- a/crates/game-review/chesscom/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Партии со сверкой по chess.com - -Партии, в которых отметки нашего разбора (!! и !) сверены с Game Review chess.com. После -каждой калибровки правил (`src/features.rs`, `src/report.rs`) прогонять **все**: - -``` -cargo run --release -p game-review --example chesscom_check -- -``` - -- Отметки chess.com записаны в партию как NAG: `$3` — !!, `$1` — !. Других NAG здесь нет. -- Тег `ChessComMarks` — какие отметки сверялись: `"!! !"` — обе, `"!!"` — только блестящие - (отметки ! chess.com для этой партии неизвестны, наши ! не считаются расхождением). -- Движок считает так же, как программа (фиксированный поиск разбора, `docs/decisions.md` - 2026-10-28): Stockfish 19 из ChessPenguin, 1 000 000 узлов (`SEARCH_NODES`), один поток, - Hash 32 МБ, `ucinewgame` перед каждым поиском, процессов — по числу ЦП (до 8). Оценки - поэтому одинаковы на любой машине. Кэш — `target/chesscom-check/v/`: - повторный прогон после правки правил идёт без движка. -- `CP_REVIEW_NODES=N` — другое число узлов, только для подбора константы (кэш в - `target/chesscom-check/v<версия>-N/`); программа так не считает. -- `CP_SHALLOW_NODES`, `CP_GREAT_HARD`, `CP_BRILLIANT_HARD`, `CP_GREAT_GAP`, - `CP_BRILLIANT_GAP`, `CP_GREAT_BANS`, `CP_HARD_DEPTH` — опыты с «трудностью» хода - (неглубокий поиск, `Hardness`; 2026-10-29, программа их пока не использует), см. - `examples/chesscom_check.rs`. Неглубокие поиски хранятся в том же кэше. -- Новую партию от владельца — сюда же, с источником в теге `Annotator`. - -## Порядок калибровки - -1. Новую партию сначала добавить и прогнать **без правок правил** — это честная проверка - (партия не участвовала в настройке). Записать: сколько !! и ! chess.com нашлось. -2. Только потом искать причины расхождений и править. Правка — общее правило о том, что - делает ход (жертва, отыгрыш, мат), а не исключение для хода; пороги не двигать ради - одной партии. -3. Прогнать весь набор: ничего из прежнего не должно сломаться. - -Итог прогона — доля найденных !! и ! chess.com и доля наших !! и !, которые совпали с -chess.com. Числа зависят только от правил и версии поиска: калибровки 1–7 делались на -3M узлов и 12 потоках, после перехода на фиксированный поиск (1M, один поток) они -пересчитаны (`docs/decisions.md`). - -## Вердикты владельца - -Партии `owner-*.pgn` — без отметок chess.com: тег `OwnerPlain` перечисляет ходы (SAN), которые -владелец считает очевидными; ни «!», ни «!!» на них быть не должно. Прогон печатает такие -нарушения строкой `OWNER` и считает их в итоговой строке. diff --git a/crates/game-review/chesscom/aronian-anand.pgn b/crates/game-review/chesscom/aronian-anand.pgn deleted file mode 100644 index 99c4aea..0000000 --- a/crates/game-review/chesscom/aronian-anand.pgn +++ /dev/null @@ -1,14 +0,0 @@ -[Event "Tata Steel-A 75th"] -[Site "Wijk aan Zee"] -[Date "2013.01.15"] -[Round "4"] -[White "Aronian, Levon"] -[Black "Anand, Viswanathan"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] - -1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 -Bd6 9. O-O O-O 10. Qc2 Bb7 11. a3 Rc8 12. Ng5 c5 13. Nxh7 Ng4 $3 14. f4 cxd4 $1 15. -exd4 Bc5 $3 16. Be2 Nde5 $3 17. Bxg4 Bxd4+ 18. Kh1 Nxg4 $1 19. Nxf8 f5 $1 20. Ng6 Qf6 21. h3 -Qxg6 22. Qe2 Qh5 23. Qd3 Be3 $3 0-1 diff --git a/crates/game-review/chesscom/byrne-fischer-2.pgn b/crates/game-review/chesscom/byrne-fischer-2.pgn deleted file mode 100644 index 277851f..0000000 --- a/crates/game-review/chesscom/byrne-fischer-2.pgn +++ /dev/null @@ -1,16 +0,0 @@ -[Event "Third Rosenwald Trophy"] -[Site "New York, NY USA"] -[Date "1956.10.17"] -[White "Byrne, Donald"] -[Black "Fischer, Robert James"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28): another move order of the opening"] - -1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 c6 7. Rd1 dxc4 8. Qxc4 -Nbd7 9. e4 $1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 $3 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 -Qb6 15. Bc4 Nxc3 $3 16. Bc5 Rfe8+ 17. Kf1 Be6 $3 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ $1 -20. Kf1 Nxd4+ 21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 -26. h3 Rxa2 27. Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. -Qb8 b5 33. h4 h5 34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ -39. Kc1 Ne2+ 40. Kb1 Nc3+ 41. Kc1 Rc2# 0-1 diff --git a/crates/game-review/chesscom/byrne-fischer.pgn b/crates/game-review/chesscom/byrne-fischer.pgn deleted file mode 100644 index 127e90a..0000000 --- a/crates/game-review/chesscom/byrne-fischer.pgn +++ /dev/null @@ -1,17 +0,0 @@ -[Event "Third Rosenwald Trophy"] -[Site "New York, NY USA"] -[Date "1956.10.17"] -[Round "8"] -[White "Byrne, Donald"] -[Black "Fischer, Robert James"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. Nf3 Nf6 2. c4 g6 3. Nc3 Bg7 4. d4 O-O 5. Bf4 d5 6. Qb3 dxc4 7. Qxc4 c6 8. e4 -Nbd7 9. Rd1 Nb6 10. Qc5 Bg4 11. Bg5 Na4 $3 12. Qa3 Nxc3 13. bxc3 Nxe4 14. Bxe7 Qb6 -15. Bc4 Nxc3 $3 16. Bc5 Rfe8+ 17. Kf1 Be6 $3 18. Bxb6 Bxc4+ 19. Kg1 Ne2+ $1 20. Kf1 Nxd4+ -21. Kg1 Ne2+ 22. Kf1 Nc3+ 23. Kg1 axb6 24. Qb4 Ra4 25. Qxb6 Nxd1 26. h3 Rxa2 27. -Kh2 Nxf2 28. Re1 Rxe1 29. Qd8+ Bf8 30. Nxe1 Bd5 31. Nf3 Ne4 32. Qb8 b5 33. h4 h5 -34. Ne5 Kg7 35. Kg1 Bc5+ 36. Kf1 Ng3+ 37. Ke1 Bb4+ 38. Kd1 Bb3+ 39. Kc1 Ne2+ 40. -Kb1 Nc3+ 41. Kc1 Rc2# 0-1 diff --git a/crates/game-review/chesscom/capablanca-marshall.pgn b/crates/game-review/chesscom/capablanca-marshall.pgn deleted file mode 100644 index 2396faf..0000000 --- a/crates/game-review/chesscom/capablanca-marshall.pgn +++ /dev/null @@ -1,15 +0,0 @@ -[Event "New York"] -[Site "New York USA"] -[Date "1918.10.23"] -[White "Capablanca, Jose Raul"] -[Black "Marshall, Frank James"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 -d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 Nf6 12. Re1 Bd6 13. h3 Ng4 14. Qf3 Qh4 -15. d4 Nxf2 16. Re2 Bg4 17. hxg4 Bh2+ 18. Kf1 Bg3 19. Rxf2 Qh1+ 20. Ke2 Bxf2 -21. Bd2 Bh4 22. Qh3 Rae8+ 23. Kd3 Qf1+ 24. Kc2 Bf2 25. Qf3 Qg1 26. Bd5 c5 27. -dxc5 Bxc5 28. b4 Bd6 29. a4 a5 30. axb5 axb4 31. Ra6 bxc3 32. Nxc3 Bb4 33. b6 -Bxc3 34. Bxc3 h6 35. b7 Re3 36. Bxf7+ $3 1-0 diff --git a/crates/game-review/chesscom/evergreen.pgn b/crates/game-review/chesscom/evergreen.pgn deleted file mode 100644 index eaff13e..0000000 --- a/crates/game-review/chesscom/evergreen.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[Event "Berlin casual game"] -[Site "Berlin"] -[Date "1852.??.??"] -[White "Anderssen, Adolf"] -[Black "Dufresne, Jean"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshots, 2026-10-28)"] - -1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d3 8. Qb3 -Qf6 $1 9. e5 Qg6 10. Re1 Nge7 $1 11. Ba3 b5 12. Qxb5 Rb8 13. Qa4 $1 Bb6 14. Nbd2 -Bb7 15. Ne4 Qf5 16. Bxd3 Qh5 17. Nf6+ gxf6 18. exf6 Rg8 $1 19. Rad1 Qxf3 20. -Rxe7+ $1 Nxe7 21. Qxd7+ $3 Kxd7 22. Bf5+ $1 Ke8 23. Bd7+ $1 Kf8 24. Bxe7# 1-0 diff --git a/crates/game-review/chesscom/immortal.pgn b/crates/game-review/chesscom/immortal.pgn deleted file mode 100644 index 7717673..0000000 --- a/crates/game-review/chesscom/immortal.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[Event "London casual game"] -[Site "London ENG"] -[Date "1851.06.21"] -[White "Anderssen, Adolf"] -[Black "Kieseritzky, Lionel"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 b5 5. Bxb5 Nf6 6. Nf3 Qh6 7. d3 Nh5 8. -Nh4 Qg5 9. Nf5 $1 c6 10. g4 Nf6 11. Rg1 cxb5 12. h4 $1 Qg6 13. h5 $1 Qg5 14. Qf3 -$1 Ng8 15. Bxf4 Qf6 16. Nc3 $1 Bc5 17. Nd5 Qxb2 18. Bd6 Bxg1 19. e5 Qxa1+ 20. -Ke2 $1 Na6 21. Nxg7+ Kd8 22. Qf6+ $3 Nxf6 23. Be7# 1-0 diff --git a/crates/game-review/chesscom/kasparov-topalov.pgn b/crates/game-review/chesscom/kasparov-topalov.pgn deleted file mode 100644 index b7078fc..0000000 --- a/crates/game-review/chesscom/kasparov-topalov.pgn +++ /dev/null @@ -1,17 +0,0 @@ -[Event "Hoogovens"] -[Site "Wijk aan Zee NED"] -[Date "1999.01.20"] -[Round "4"] -[White "Kasparov, Garry"] -[Black "Topalov, Veselin"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 Bg7 5. Qd2 c6 6. f3 b5 7. Nge2 Nbd7 8. Bh6 -Bxh6 9. Qxh6 Bb7 10. a3 e5 11. O-O-O Qe7 12. Kb1 a6 13. Nc1 O-O-O 14. Nb3 exd4 -15. Rxd4 c5 16. Rd1 Nb6 17. g3 Kb8 18. Na5 Ba8 19. Bh3 d5 20. Qf4+ Ka7 21. Rhe1 -d4 $1 22. Nd5 Nbxd5 23. exd5 Qd6 $1 24. Rxd4 cxd4 25. Re7+ $3 Kb6 $1 26. Qxd4+ Kxa5 27. b4+ $1 -Ka4 28. Qc3 Qxd5 29. Ra7 Bb7 $1 30. Rxb7 $3 Qc4 31. Qxf6 Kxa3 32. Qxa6+ $1 Kxb4 33. c3+ $3 -Kxc3 34. Qa1+ $1 Kd2 35. Qb2+ $1 Kd1 36. Bf1 $3 Rd2 37. Rd7 $3 Rxd7 38. Bxc4 bxc4 39. Qxh8 -Rd3 40. Qa8 c3 41. Qa4+ Ke1 42. f4 f5 43. Kc1 Rd2 44. Qa7 1-0 diff --git a/crates/game-review/chesscom/lasker-thomas.pgn b/crates/game-review/chesscom/lasker-thomas.pgn deleted file mode 100644 index abf3085..0000000 --- a/crates/game-review/chesscom/lasker-thomas.pgn +++ /dev/null @@ -1,12 +0,0 @@ -[Event "London"] -[Site "London ENG"] -[Date "1912.10.29"] -[White "Lasker, Edward"] -[Black "Thomas, George Alan"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. d4 e6 2. Nf3 f5 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 Bxf6 6. e4 fxe4 7. Nxe4 b6 8. -Ne5 O-O 9. Bd3 Bb7 10. Qh5 Qe7 11. Qxh7+ $3 Kxh7 12. Nxf6+ Kh6 13. Neg4+ $1 Kg5 -14. h4+ Kf4 15. g3+ Kf3 16. Be2+ Kg2 17. Rh2+ Kg1 18. Kd2# 1-0 diff --git a/crates/game-review/chesscom/levitsky-marshall.pgn b/crates/game-review/chesscom/levitsky-marshall.pgn deleted file mode 100644 index c00989d..0000000 --- a/crates/game-review/chesscom/levitsky-marshall.pgn +++ /dev/null @@ -1,14 +0,0 @@ -[Event "Breslau"] -[Site "Breslau GER"] -[Date "1912.07.20"] -[White "Levitsky, Stepan Mikhailovich"] -[Black "Marshall, Frank James"] -[Result "0-1"] -[ChessComMarks "counts"] -[ChessComCounts "white !! 0 ! 1, black !! 2 ! 1"] -[Annotator "chess.com Game Review summary only (owner's screenshot, 2026-10-28)"] - -1. d4 e6 2. e4 d5 3. Nc3 c5 4. Nf3 Nc6 5. exd5 exd5 6. Be2 Nf6 7. O-O Be7 8. -Bg5 O-O 9. dxc5 Be6 10. Nd4 Bxc5 11. Nxe6 fxe6 12. Bg4 Qd6 13. Bh3 Rae8 14. Qd2 -Bb4 15. Bxf6 Rxf6 16. Rad1 Qc5 17. Qe2 Bxc3 18. bxc3 Qxc3 19. Rxd5 Nd4 20. Qh5 -Ref8 21. Re5 Rh6 22. Qg5 Rxh3 23. Rc5 Qg3 0-1 diff --git a/crates/game-review/chesscom/morphy-opera.pgn b/crates/game-review/chesscom/morphy-opera.pgn deleted file mode 100644 index f547169..0000000 --- a/crates/game-review/chesscom/morphy-opera.pgn +++ /dev/null @@ -1,12 +0,0 @@ -[Event "Paris Opera"] -[Site "Paris FRA"] -[Date "1858.??.??"] -[White "Morphy, Paul"] -[Black "Duke Karl / Count Isouard"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Bxf3 5. Qxf3 dxe5 6. Bc4 Nf6 7. Qb3 $1 Qe7 8. -Nc3 c6 9. Bg5 b5 10. Nxb5 $3 cxb5 11. Bxb5+ Nbd7 12. O-O-O Rd8 13. Rxd7 $3 Rxd7 14. -Rd1 Qe6 15. Bxd7+ Nxd7 16. Qb8+ $3 Nxb8 17. Rd8# 1-0 diff --git a/crates/game-review/chesscom/owner-matovalov-1.pgn b/crates/game-review/chesscom/owner-matovalov-1.pgn deleted file mode 100644 index a4a07b2..0000000 --- a/crates/game-review/chesscom/owner-matovalov-1.pgn +++ /dev/null @@ -1,15 +0,0 @@ -[Event "rated rapid game"] -[Site "https://lichess.org/game/GPGwoXk9"] -[Date "2026.10.29"] -[White "Matovalov"] -[Black "SrihasSM"] -[Result "1-0"] -[OwnerPlain "Be2"] -[Annotator "The owner: 10.Be2 is no ! (2026-10-29)"] - -1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Nge7 6. Na3 Bd7 7. Nc2 Nf5 8. Bd3 -Nh4 9. O-O c4 10. Be2 Nxf3+ 11. Bxf3 Be7 12. Bf4 b5 13. a3 Qb6 14. Be3 O-O-O 15. -a4 b4 16. a5 Nxa5 17. cxb4 Nb3 18. Ra3 Kc7 19. Bd2 Bb5 20. Bc3 g5 21. Na1 Nxa1 -22. Qxa1 a6 23. Qd1 Qc6 24. Bh5 Qe8 25. Qa1 Kb7 26. Bd1 Qf8 27. Ba4 Ra8 28. Bxb5 -axb5 29. Ra5 Kb6 30. Qa3 Rxa5 31. Qxa5+ Kc6 32. Qa6+ Kc7 33. Qa7+ Kc8 34. Ra1 -Bd8 35. Qa6+ Kc7 36. Qxb5 1-0 diff --git a/crates/game-review/chesscom/owner-matovalov-2.pgn b/crates/game-review/chesscom/owner-matovalov-2.pgn deleted file mode 100644 index 59214f5..0000000 --- a/crates/game-review/chesscom/owner-matovalov-2.pgn +++ /dev/null @@ -1,27 +0,0 @@ -[Event "rated rapid game"] -[Site "https://lichess.org/game/Sc0SWXkI"] -[Date "2026.10.29"] -[White "Matovalov"] -[Black "Karataschessnew"] -[Result "1-0"] -[OwnerPlain "Ra7 Ra7+"] -[Annotator "The owner: Ra7 is no ! (2026-10-29)"] - -1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. e5 Ne4 6. O-O d5 7. exd6 Nxd6 8. -Re1+ Be7 9. Bb3 Bg4 10. h3 Bxf3 11. Qxf3 Qd7 12. Bf4 O-O 13. Nd2 Bf6 14. Bxd6 -Qxd6 15. Ne4 Qe7 16. Nxf6+ Qxf6 17. Qxf6 gxf6 18. Rad1 Rad8 19. Rd2 Rd6 20. Red1 -Kg7 21. Ba4 f5 22. Rd3 Kf6 23. R1d2 Rfd8 24. Bxc6 Rxc6 25. Re2 Re6 26. Red2 Re1+ -27. Kh2 c5 28. b4 cxb4 29. Rxd4 Rxd4 30. Rxd4 a5 31. Rd5 a4 32. Rb5 Rb1 33. Rxb7 -Rb2 34. f4 a3 35. Rb6+ Kg7 36. Rb5 Rxa2 37. Rxb4 Rxc2 38. Ra4 Ra2 39. Ra6 Ra1 -40. h4 a2 41. h5 f6 42. Ra7+ Kh6 43. Kg3 Kxh5 44. Rxh7+ Kg6 45. Ra7 Kh6 46. Kh2 -Rf1 47. Rxa2 Rxf4 48. Ra8 Rg4 49. Kg1 Kg5 50. Kf2 f4 51. Ra5+ Kg6 52. Kf3 f5 53. -Ra8 Kg7 54. Ra7+ Kf6 55. Ra6+ Ke5 56. Ra5+ Kd4 57. Rxf5 Rg3+ 58. Kxf4 Rxg2 59. -Rg5 Rf2+ 60. Kg4 Rf1 61. Ra5 Rf8 62. Ra4+ Kd5 63. Ra5+ Ke6 64. Ra6+ Kf7 65. Ra7+ -Kg8 66. Kg5 Rf1 67. Ra8+ Kg7 68. Ra7+ Kf8 69. Ra8+ Ke7 70. Ra7+ Kd8 71. Ra8+ Kc7 -72. Ra7+ Kb8 73. Rg7 Ka8 74. Kg6 Re1 75. Kh7 Kb8 76. Kg6 Ra1 77. Kf6 Ra6+ 78. -Ke5 Ka8 79. Re7 Ra1 80. Rg7 Kb8 81. Kf6 Ra2 82. Rg5 Ra1 83. Re5 Kc7 84. Re7+ Kd6 -85. Re6+ Kd5 86. Re5+ Kd4 87. Rh5 Rf1+ 88. Kg7 Rf4 89. Ra5 Kc4 90. Ra4+ Kd5 91. -Rxf4 Ke5 92. Rf6 Kd5 93. Kf7 Kd4 94. Rf5 Ke4 95. Ke6 Kd4 96. Rh5 Ke4 97. Rh4+ -Ke3 98. Kf5 Kd3 99. Ke5 Ke3 100. Rh3+ Kd2 101. Ke4 Kc2 102. Kd4 Kb2 103. Kc4 Kc2 -104. Rh2+ Kd1 105. Kc3 Ke1 106. Rg2 Kf1 107. Ra2 Ke1 108. Kd3 Kf1 109. Ke3 Kg1 -110. Kf3 Kh1 111. Kg3 1-0 diff --git a/crates/game-review/chesscom/pending/README.md b/crates/game-review/chesscom/pending/README.md deleted file mode 100644 index a7c439d..0000000 --- a/crates/game-review/chesscom/pending/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# Партии, отданные владельцу для chess.com - -Наш прогноз записан **до** ответа chess.com — честная проверка (партия не участвовала в -настройке). Когда ответ придёт: отметки chess.com вписать NAG-ами, файл перенести в -`chesscom/`, сравнить с прогнозом. - -## giri-gukesh-2024.pgn (отдана 2026-10-28) - -Прогноз (фиксированный режим, строгие «!»), записан до ответа chess.com: - -- 20... Rxd3 !! -- 24. Bxc6 !! - -## Пять партий из встроенной классики (отданы 2026-10-29) - -Прогноз (фиксированный режим, правила после «тихого отступления»), записан до ответов chess.com: - -- polugaevsky-nezhmetdinov.pgn: 19.f4 !, 21…Qh2+ !, 22.Ke3 !, 24…Rxf4 !!, 25…Rf3+ ! -- tal-larsen.pgn: 32.Kd2 !, 34.Bc5 !!, 35.Re8+ !, 36.Qe6+ ! -- short-timman.pgn: отметок нет -- topalov-shirov.pgn: 26…Nb4 !!, 40.Re3 !!, 47…Bh3 !!, 48…Kf5 !, 49…Ke4 !, 50…d4 !, 51…Kd3 !, 52…Kc4 ! -- aronian-anand.pgn: 15…Bc5 !!, 16…Nde5 !!, 23…Be3 !! - -## Итоги прошлых партий - -- **byrne-fischer.pgn** (2026-10-28): прогноз до ответа — !! 2 из 3 (17…Be6!! не нашли: ферзь - висел и до хода), ! 1 из 1, лишних ! 4 (12…Nxc3, 13…Nxe4, 18…Bxc4+, 17…Be6 как «!»). - Перенесена в набор. -- **kasparov-topalov.pgn** (2026-10-28): прогноз до ответа — !! 3 из 5 (нет 33.c3+, 37.Rd7; - лишний 24.Rxd4), ! 6 из 8 (лишних 6). Перенесена в набор. -- **morphy-opera.pgn** (2026-10-28): прогноз до ответа (строгие «!») — !! 2 из 3 (нет - 10.Nxb5 — конь за две пешки, чистая потеря 1 при пороге 2), лишних нет; ! 0 из 1 (7.Qb3). - Порог жертвы 1 вместо 2 пробовали: находит 10.Nxb5 и 22…Rxh3, но даёт ложные !! на - 22.Nd5 (Каспаров) и 17…Rxc3 (Пиллсбери) — отброшен. Перенесена в набор. -- **byrne-fischer-2.pgn**: та же партия в другом порядке ходов дебюта, отметки chess.com - те же плюс 9.e4!. -- **polugaevsky-nezhmetdinov.pgn** (2026-10-29): прогноз до ответа — !! 1 из 2 (нет 19…Be6!!), - ! 4 из 10, лишних нет (все 5 наших отметок — у chess.com). 22.Ke3 (уход из-под шаха) у - chess.com тоже «!». Перенесена в набор. -- **tal-larsen.pgn** (2026-10-29): прогноз до ответа — !! 1 из 1 (34.Bc5), ! 2 из 9, лишний 1 - (32.Kd2 — уход короля из-под шаха; 22.Ke3 у Полугаевского chess.com отметил). Перенесена. -- **short-timman.pgn** (2026-10-29): прогноз до ответа — отметок нет; у chess.com 34.Kg5!! (поход - короля, не жертва материала) и семь «!» белых. !! 0 из 1, ! 0 из 7, лишних нет. Перенесена. -- **topalov-shirov.pgn** (2026-10-29): прогноз до ответа — !! 2 из 2 (40.Re3, 47…Bh3), лишний !! - 26…Nb4 (у chess.com «!»); ! 4 из 12, лишний 50…d4. Снимок chess.com — с 14-го хода. Перенесена. -- **aronian-anand.pgn** (2026-10-29): прогноз до ответа — !! 3 из 4 (нет 13…Ng4), лишних нет; ! 0 из 3. - Перенесена. -- **Итог пяти партий до правок:** !! найдено 7 из 10, наших верных 7 из 8; ! найдено 10 из 41, наших - верных 10 из 12. Следующий шаг (одобрен владельцем): «неочевидность» хода по неглубокому поиску. diff --git a/crates/game-review/chesscom/pending/giri-gukesh-2024.pgn b/crates/game-review/chesscom/pending/giri-gukesh-2024.pgn deleted file mode 100644 index 0b5ee6a..0000000 --- a/crates/game-review/chesscom/pending/giri-gukesh-2024.pgn +++ /dev/null @@ -1,19 +0,0 @@ -[Event "Tata Steel Chess 2024"] -[Site "Wijk aan Zee NED"] -[Date "2024.01.16"] -[Round "4"] -[White "Giri, Anish"] -[Black "Gukesh, Dommaraju"] -[Result "1-0"] - -1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d3 d5 5. cxd5 Nxd5 6. g3 Nf6 7. Bg5 Be7 8. Bg2 -O-O 9. O-O h6 10. Bxf6 Bxf6 11. Rb1 a5 12. a3 Nd4 13. e3 Nxf3+ 14. Bxf3 c6 15. -Qc2 Bf5 16. Rfd1 Qd7 17. Na4 Qc7 18. b4 axb4 19. axb4 Rfd8 20. b5 Rxd3 21. Rxd3 -Bxd3 22. Qxd3 Rxa4 23. bxc6 bxc6 24. Bxc6 Ra7 25. Bd5 Qd8 26. h4 h5 27. Rb5 Rd7 -28. Qb3 Qe7 29. Bc6 Rd6 30. Rb8+ Rd8 31. Rb7 Qe6 32. Qxe6 fxe6 33. Be4 g5 34. -Bh7+ Kh8 35. hxg5 Bxg5 36. Bg6 Rd1+ 37. Kg2 Rd2 38. Kf1 h4 39. gxh4 Bf6 40. Rf7 -Bg7 41. h5 Rd8 42. Re7 Bf6 43. Rxe6 Rf8 44. Bf5 Kg7 45. Kg2 Kh6 46. Bg4 Kg5 47. -Kg3 Rf7 48. Rb6 Rf8 49. Rb7 Kh6 50. Ra7 Bg7 51. Bf3 Rf5 52. Rb7 Rf8 53. Be4 Rf6 -54. Rd7 Rf8 55. Ra7 Rf6 56. Ra2 Rf8 57. Kg4 Rf6 58. Bf5 Rb6 59. Ra7 Rc6 60. Kf3 -Rc4 61. Bd3 Rc6 62. Ke4 Rf6 63. f3 Bh8 64. Bc4 Rb6 65. Bf7 Bg7 66. Bg6 Rb4+ 67. -Kf5 Rb3 68. Ra6 Rb8 69. Bf7+ Kh7 70. Kg5 Bf8 71. Bg6+ Kh8 72. Re6 1-0 diff --git a/crates/game-review/chesscom/pillsbury-lasker.pgn b/crates/game-review/chesscom/pillsbury-lasker.pgn deleted file mode 100644 index 3262a1f..0000000 --- a/crates/game-review/chesscom/pillsbury-lasker.pgn +++ /dev/null @@ -1,15 +0,0 @@ -[Event "St. Petersburg"] -[Site "St. Petersburg RUE"] -[Date "1896.01.04"] -[White "Pillsbury, Harry Nelson"] -[Black "Lasker, Emanuel"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. Bg5 cxd4 6. Qxd4 Nc6 7. Qh4 Be7 8. -O-O-O Qa5 9. e3 Bd7 10. Kb1 h6 11. cxd5 exd5 12. Nd4 O-O 13. Bxf6 Bxf6 14. Qh5 -Nxd4 15. exd4 Be6 16. f4 Rac8 17. f5 Rxc3 18. fxe6 $1 Ra3 $3 19. exf7+ Rxf7 20. -bxa3 Qb6+ $1 21. Bb5 Qxb5+ 22. Ka1 Rc7 23. Rd2 $1 Rc4 24. Rhd1 Rc3 25. Qf5 Qc4 -26. Kb2 Rxa3 $3 27. Qe6+ Kh7 28. Kxa3 Qc3+ $1 29. Ka4 b5+ $3 30. Kxb5 Qc4+ $1 31. -Ka5 Bd8+ $1 32. Qb6 Bxb6# 0-1 diff --git a/crates/game-review/chesscom/polugaevsky-nezhmetdinov.pgn b/crates/game-review/chesscom/polugaevsky-nezhmetdinov.pgn deleted file mode 100644 index 391e28d..0000000 --- a/crates/game-review/chesscom/polugaevsky-nezhmetdinov.pgn +++ /dev/null @@ -1,16 +0,0 @@ -[Event "RSFSR-ch18"] -[Site "Sochi"] -[Date "1958.??.??"] -[Round "?"] -[White "Polugaevsky, Lev"] -[Black "Nezhmetdinov, Rashid"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] - -1. d4 Nf6 2. c4 d6 3. Nc3 e5 4. e4 exd4 5. Qxd4 Nc6 6. Qd2 g6 7. b3 Bg7 8. Bb2 -O-O 9. Bd3 Ng4 10. Nge2 Qh4 11. Ng3 Nge5 12. O-O f5 13. f3 Bh6 $1 14. Qd1 f4 15. -Nge2 g5 16. Nd5 $1 g4 17. g3 $1 fxg3 18. hxg3 Qh3 $1 19. f4 $1 Be6 $3 20. Bc2 Rf7 21. Kf2 Qh2+ $1 -22. Ke3 $1 Bxd5 23. cxd5 Nb4 $1 24. Rh1 Rxf4 $3 25. Rxh2 Rf3+ $1 26. Kd4 Bg7 27. a4 c5+ $1 28. -dxc6 bxc6 29. Bd3 Nexd3+ 30. Kc4 d5+ 31. exd5 cxd5+ 32. Kb5 Rb8+ 33. Ka5 Nc6+ -0-1 diff --git a/crates/game-review/chesscom/reti-tartakower.pgn b/crates/game-review/chesscom/reti-tartakower.pgn deleted file mode 100644 index dc995b4..0000000 --- a/crates/game-review/chesscom/reti-tartakower.pgn +++ /dev/null @@ -1,11 +0,0 @@ -[Event "Vienna"] -[Site "Vienna AUT"] -[Date "1910.??.??"] -[White "Reti, Richard"] -[Black "Tartakower, Saviely"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Qd3 e5 6. dxe5 Qa5+ 7. Bd2 $1 Qxe5 -8. O-O-O $1 Nxe4 9. Qd8+ $3 Kxd8 10. Bg5+ $1 Kc7 11. Bd8# 1-0 diff --git a/crates/game-review/chesscom/rodent-roman-2026-10-27.pgn b/crates/game-review/chesscom/rodent-roman-2026-10-27.pgn deleted file mode 100644 index f42e595..0000000 --- a/crates/game-review/chesscom/rodent-roman-2026-10-27.pgn +++ /dev/null @@ -1,18 +0,0 @@ -[Event "Партия с компьютером"] -[Site "ChessPenguin"] -[Date "2026.10.27"] -[White "Rodent IV 2200 (Spassky)"] -[Black "Roman"] -[Result "0-1"] -[ChessComMarks "!!"] -[Annotator "chess.com Game Review (owner, 2026-10-28): only !! compared; 18.Bxa7 is no !!"] - -1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 Qa5 8. -O-O O-O 9. Bb3 d6 10. f3 Bd7 11. Qe1 Nxd4 12. Bxd4 Bc6 13. Nd5 Qd8 14. Nxf6+ -exf6 15. Qc3 d5 16. Rad1 dxe4 17. fxe4 Bxe4 18. Bxa7 Qc8 19. Bd4 Qg4 20. Rd2 -Rad8 21. h3 Qg5 22. Rff2 Rxd4 $3 23. Rxd4 f5 24. Qd2 Qg3 25. Rd8 Qc7 26. Rxf8+ -Bxf8 27. Kf1 Bc5 28. Qc3 Qd6 29. Rd2 Qf4+ 30. Ke1 Bxg2 $3 31. Rd8+ Bf8 32. Ke2 -Qf1+ 33. Kd2 Qf4+ 34. Qe3 Qxe3+ 35. Kxe3 Bxh3 36. Kf4 Kg7 37. Rd7 Kh6 38. Bxf7 -g5+ 39. Kg3 Bf1 40. Rxb7 g4 41. Bg8 Kg5 42. Kf2 Bh3 43. Rb5 Kh4 44. Bxh7 g3+ 45. -Kg1 f4 46. Be4 Kg4 47. Bf5+ Kh4 48. Bxh3 Kxh3 49. Rf5 Bd6 50. a4 Kg4 51. Rd5 Bb8 -52. c4 f3 53. b4 g2 54. c5 Kh3 55. b5 Bh2+ 56. Kf2 g1=Q+ 0-1 diff --git a/crates/game-review/chesscom/rotlewi-rubinstein.pgn b/crates/game-review/chesscom/rotlewi-rubinstein.pgn deleted file mode 100644 index d8d5734..0000000 --- a/crates/game-review/chesscom/rotlewi-rubinstein.pgn +++ /dev/null @@ -1,13 +0,0 @@ -[Event "Lodz"] -[Site "Lodz POL"] -[Date "1907.12.26"] -[White "Rotlewi, Georg A"] -[Black "Rubinstein, Akiba"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. d4 d5 2. Nf3 e6 3. e3 c5 4. c4 Nc6 5. Nc3 Nf6 6. dxc5 Bxc5 7. a3 a6 8. b4 Bd6 -9. Bb2 O-O 10. Qd2 Qe7 11. Bd3 dxc4 12. Bxc4 b5 13. Bd3 Rd8 14. Qe2 Bb7 15. O-O -Ne5 16. Nxe5 Bxe5 17. f4 Bc7 18. e4 Rac8 19. e5 Bb6+ 20. Kh1 Ng4 $3 21. Be4 Qh4 -22. g3 Rxc3 $3 23. gxh4 Rd2 $3 24. Qxd2 Bxe4+ 25. Qg2 Rh3 0-1 diff --git a/crates/game-review/chesscom/short-timman.pgn b/crates/game-review/chesscom/short-timman.pgn deleted file mode 100644 index 910eb79..0000000 --- a/crates/game-review/chesscom/short-timman.pgn +++ /dev/null @@ -1,16 +0,0 @@ -[Event "Tilburg"] -[Site "Tilburg"] -[Date "1991.10.??"] -[Round "4"] -[White "Short, Nigel D"] -[Black "Timman, Jan H"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] - -1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 g6 5. Bc4 Nb6 6. Bb3 Bg7 7. Qe2 Nc6 8. O-O -O-O 9. h3 a5 10. a4 $1 dxe5 11. dxe5 Nd4 12. Nxd4 $1 Qxd4 13. Re1 e6 14. Nd2 Nd5 15. -Nf3 Qc5 16. Qe4 Qb4 17. Bc4 Nb6 18. b3 $1 Nxc4 19. bxc4 Re8 20. Rd1 Qc5 21. Qh4 b6 -22. Be3 $1 Qc6 23. Bh6 $1 Bh8 24. Rd8 Bb7 25. Rad1 $1 Bg7 26. R8d7 $1 Rf8 27. Bxg7 Kxg7 28. -R1d4 Rae8 29. Qf6+ Kg8 30. h4 h5 31. Kh2 Rc8 32. Kg3 Rce8 33. Kf4 Bc8 34. Kg5 $3 -1-0 diff --git a/crates/game-review/chesscom/steinitz-bardeleben.pgn b/crates/game-review/chesscom/steinitz-bardeleben.pgn deleted file mode 100644 index 1c06c14..0000000 --- a/crates/game-review/chesscom/steinitz-bardeleben.pgn +++ /dev/null @@ -1,14 +0,0 @@ -[Event "Hastings"] -[Site "Hastings ENG"] -[Date "1895.08.17"] -[White "Steinitz, William"] -[Black "Von Bardeleben, Curt"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-28)"] - -1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 d5 8. -exd5 Nxd5 9. O-O $1 Be6 10. Bg5 Be7 11. Bxd5 Bxd5 12. Nxd5 Qxd5 13. Bxe7 Nxe7 -14. Re1 f6 15. Qe2 Qd7 $1 16. Rac1 c6 17. d5 cxd5 18. Nd4 Kf7 $1 19. Ne6 Rhc8 -20. Qg4 $1 g6 21. Ng5+ $1 Ke8 22. Rxe7+ $3 Kf8 23. Rf7+ Kg8 24. Rg7+ $3 Kh8 25. -Rxh7+ 1-0 diff --git a/crates/game-review/chesscom/tal-larsen.pgn b/crates/game-review/chesscom/tal-larsen.pgn deleted file mode 100644 index 1067831..0000000 --- a/crates/game-review/chesscom/tal-larsen.pgn +++ /dev/null @@ -1,16 +0,0 @@ -[Event "Candidats sf1"] -[Site "Bled"] -[Date "1965.??.??"] -[Round "10"] -[White "Tal, Mihail"] -[Black "Larsen, Bent"] -[Result "1-0"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot, 2026-10-29)"] - -1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 e6 5. Nc3 d6 6. Be3 Nf6 7. f4 Be7 8. Qf3 -O-O 9. O-O-O Qc7 10. Ndb5 Qb8 $1 11. g4 a6 12. Nd4 $1 Nxd4 13. Bxd4 b5 14. g5 Nd7 $1 15. -Bd3 b4 16. Nd5 exd5 17. exd5 f5 18. Rde1 Rf7 19. h4 $1 Bb7 20. Bxf5 Rxf5 21. Rxe7 -Ne5 22. Qe4 $1 Qf8 23. fxe5 Rf4 24. Qe3 $1 Rf3 25. Qe2 Qxe7 26. Qxf3 dxe5 27. Re1 $1 Rd8 -28. Rxe5 Qd6 29. Qf4 Rf8 30. Qe4 b3 31. axb3 Rf1+ 32. Kd2 Qb4+ 33. c3 Qd6 34. -Bc5 $3 Qxc5 35. Re8+ $1 Rf8 36. Qe6+ $1 Kh8 37. Qf7 1-0 diff --git a/crates/game-review/chesscom/topalov-shirov.pgn b/crates/game-review/chesscom/topalov-shirov.pgn deleted file mode 100644 index b6c93b8..0000000 --- a/crates/game-review/chesscom/topalov-shirov.pgn +++ /dev/null @@ -1,18 +0,0 @@ -[Event "Linares"] -[Site "Linares"] -[Date "1998.03.04"] -[Round "10"] -[White "Topalov, Veselin"] -[Black "Shirov, Alexei"] -[Result "0-1"] -[ChessComMarks "!! !"] -[Annotator "chess.com Game Review (owner's screenshot from move 14, 2026-10-29)"] - -1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bb5+ c6 8. -Ba4 O-O 9. Ne2 Nd7 10. O-O e5 11. f3 Qe7 12. Be3 Rd8 13. Qc2 Nb6 14. Bb3 $1 Be6 15. -Rad1 Nc4 16. Bc1 b5 17. f4 $1 exd4 18. Nxd4 Bg4 19. Rde1 $1 Qc5 20. Kh1 a5 21. h3 Bd7 -22. a4 $1 bxa4 23. Ba2 $1 Be8 24. e5 Nb6 25. f5 Nd5 26. Bd2 Nb4 $1 27. Qxa4 Nxa2 28. Qxa2 -Bxe5 29. fxg6 hxg6 30. Bg5 Rd5 31. Re3 $1 Qd6 32. Qe2 Bd7 33. c4 Bxd4 34. cxd5 Bxe3 -35. Qxe3 Re8 36. Qc3 Qxd5 37. Bh6 Re5 38. Rf3 $1 Qc5 39. Qa1 Bf5 40. Re3 $3 f6 41. -Rxe5 Qxe5 42. Qa2+ Qd5 43. Qxd5+ cxd5 44. Bd2 a4 45. Bc3 Kf7 46. h4 Ke6 $1 47. Kg1 -Bh3 $3 48. gxh3 Kf5 $1 49. Kf2 Ke4 $1 50. Bxf6 d4 51. Be7 Kd3 $1 52. Bc5 Kc4 $1 53. Be7 Kb3 0-1 diff --git a/crates/game-review/examples/chesscom_check.rs b/crates/game-review/examples/chesscom_check.rs deleted file mode 100644 index 31be3d8..0000000 --- a/crates/game-review/examples/chesscom_check.rs +++ /dev/null @@ -1,289 +0,0 @@ -//! Our !! and ! against chess.com's on every game of `chesscom/` (see its README): run it -//! after each change of the rules, to see that a fix for one game broke no other. -//! -//! `cargo run --release -p game-review --example chesscom_check -- ` -//! -//! The engine searches as in the program: the fixed search of the game analysis -//! (`game_review::SEARCH_NODES` nodes, one thread, a clear hash), in one engine process -//! per CPU. `` is ChessPenguin's Stockfish 19. -//! -//! `CP_REVIEW_NODES=N` searches N nodes instead, for choosing the program's nodes (the -//! program itself never does): its evaluations are cached apart. -//! -//! How hard a move is to find (`game_review::Hardness`, being tried out; the program -//! does not use it yet), only for choosing its rules here: -//! - `CP_GREAT_HARD=P` — ! only for a move at least P % (win) hard to find; -//! - `CP_BRILLIANT_HARD=P` — !! also for the only good move at least P % hard; -//! - `CP_GREAT_GAP=P` — the gap of ! (default 25); -//! - `CP_BRILLIANT_GAP=P` — the gap of a hard move's !! (default 25); -//! - `CP_GREAT_BANS=0` — captures and quiet retreats can be ! too; -//! - `CP_HARD_DEPTH=1` — difficulty as the shallow search's underrating of the move -//! against the deep one (`Measure::Depth`), not against its own best move; -//! - `CP_SHALLOW_NODES=S` — the shallow search's nodes (default -//! `game_review::SHALLOW_NODES`), kept with the evaluations (other nodes are searched -//! again). - -use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicBool; - -use chess_core::shakmaty::Color; -use chess_core::{Game, Nag}; -use game_review::{ - GameAnalysis, Hardness, JobSettings, Judgement, Measure, SEARCH_NODES, SEARCH_VERSION, - SHALLOW_NODES, -}; - -fn main() { - let args: Vec = std::env::args().collect(); - let (Some(engine), 2) = (args.get(1), args.len()) else { - eprintln!("usage: chesscom_check "); - std::process::exit(2); - }; - let nodes: u64 = std::env::var("CP_REVIEW_NODES").map_or(SEARCH_NODES, |n| { - n.parse().expect("CP_REVIEW_NODES: a number") - }); - let number = |name: &str| { - std::env::var(name).ok().map(|v| { - v.parse::() - .unwrap_or_else(|_| panic!("{name}: a number")) - }) - }; - let defaults = Hardness::default(); - let hardness = Hardness { - great: number("CP_GREAT_HARD").or(defaults.great), - gap: number("CP_GREAT_GAP").unwrap_or(defaults.gap), - bans: number("CP_GREAT_BANS").is_none_or(|b| b != 0.0), - // `CP_BRILLIANT_HARD=0`: off. - brilliant: number("CP_BRILLIANT_HARD") - .map(Some) - .unwrap_or(defaults.brilliant) - .filter(|p| *p > 0.0), - brilliant_gap: number("CP_BRILLIANT_GAP").unwrap_or(defaults.brilliant_gap), - measure: if number("CP_HARD_DEPTH").is_some_and(|d| d != 0.0) { - Measure::Depth - } else { - Measure::Choice - }, - }; - let shallow = number("CP_SHALLOW_NODES").map_or(SHALLOW_NODES, |n| n as u64); - if hardness != defaults { - println!("{hardness:?}, shallow search {shallow} nodes"); - } - let root = Path::new(env!("CARGO_MANIFEST_DIR")); - // Evaluations of one version of the fixed search are the same on every machine; - // those of other nodes go apart. - let folder = if nodes == SEARCH_NODES { - format!("v{SEARCH_VERSION}") - } else { - format!("v{SEARCH_VERSION}-{nodes}") - }; - let cache = root.join("../../target/chesscom-check").join(folder); - println!("{nodes} nodes per search"); - std::fs::create_dir_all(&cache).expect("cache folder"); - - let mut files: Vec = std::fs::read_dir(root.join("chesscom")) - .expect("chesscom/") - .filter_map(|e| Some(e.ok()?.path())) - .filter(|p| p.extension().is_some_and(|x| x == "pgn")) - .collect(); - files.sort(); - - let (mut agree, mut differ) = (0, 0); - let mut owner_wrong = 0; - // Per mark ("!!", "!"): chess.com's, found by us, ours chess.com has not. - let mut tally = [Tally::default(), Tally::default()]; - for file in files { - let text = std::fs::read_to_string(&file).expect("pgn"); - let game = chess_core::parse_str(&text).game; - let mut a = GameAnalysis::new(&game, Some(&cache)); - a.set_hardness(hardness); - a.set_shallow_nodes(shallow); - review(&mut a, &game, engine, nodes); - a.save_cache(&cache).expect("cache"); - let compared = game.tag("ChessComMarks").unwrap_or("!! !").to_owned(); - println!( - "## {} — {} ({}; compared: {compared})", - game.tag("White").unwrap_or("?"), - game.tag("Black").unwrap_or("?"), - file.file_name().unwrap().to_string_lossy(), - ); - let line = a.line().to_vec(); - // The owner's verdict, no chess.com marks: these moves (SAN, as in the game) must - // not get ! or !! — obvious moves the owner called out ("10.Be2 — какой же это !"). - if let Some(plain) = game.tag("OwnerPlain") { - let plain: Vec<&str> = plain.split_whitespace().collect(); - for (i, j) in a.report.judgements.iter().enumerate() { - let Some(j @ (Judgement::Brilliant | Judgement::Great)) = j else { - continue; - }; - let label = game.move_label(line[i + 1]).unwrap_or_default(); - let san = label.rsplit(' ').next().unwrap_or_default(); - let mark = if *j == Judgement::Brilliant { - "!!" - } else { - "!" - }; - if plain.contains(&san) { - owner_wrong += 1; - println!(" OWNER {label:<14} ours {mark}, the owner: plain"); - } else { - println!(" ours {label:<14} {mark}"); - } - } - continue; - } - // Only chess.com's totals are known ("white !! 0 ! 1, black !! 2 ! 1"): compare - // counts, list our marks, leave the game out of the shares. - if let Some(counts) = game.tag("ChessComCounts") { - let ours = |white: bool, j: Judgement| { - a.report - .judgements - .iter() - .enumerate() - .filter(|(i, x)| **x == Some(j) && (a.movers()[*i] == Color::White) == white) - .count() - }; - println!(" chess.com: {counts}"); - println!( - " ours: white !! {} ! {}, black !! {} ! {}", - ours(true, Judgement::Brilliant), - ours(true, Judgement::Great), - ours(false, Judgement::Brilliant), - ours(false, Judgement::Great), - ); - for (i, j) in a.report.judgements.iter().enumerate() { - if let Some(j @ (Judgement::Brilliant | Judgement::Great)) = j { - let mark = if *j == Judgement::Brilliant { - "!!" - } else { - "!" - }; - let label = game.move_label(line[i + 1]).unwrap_or_default(); - println!(" ours {label:<14} {mark}"); - } - } - continue; - } - for i in 0..line.len() - 1 { - let node = line[i + 1]; - let theirs = game.node(node).map_or("", |n| mark_of_nags(n.nags())); - let ours = match a.report.judgements[i] { - Some(Judgement::Brilliant) => "!!", - Some(Judgement::Great) => "!", - _ => "", - }; - // Only the marks chess.com was compared on: with "!!" alone our ! says nothing. - let ours_compared = if ours == "!" && !compared.split(' ').any(|m| m == "!") { - "" - } else { - ours - }; - if theirs.is_empty() && ours_compared.is_empty() { - continue; - } - for (k, mark) in ["!!", "!"].into_iter().enumerate() { - let t = &mut tally[k]; - t.theirs += u32::from(theirs == mark); - t.found += u32::from(theirs == mark && ours_compared == mark); - t.extra += u32::from(ours_compared == mark && theirs != mark); - } - let label = game.move_label(node).unwrap_or_default(); - // How hard the move was to find, when the shallow search was made. - let hard = a - .eval_at(i) - .and_then(|e| Some((e.eval, e.shallow.as_ref()?))) - .filter(|(_, s)| s.nodes == shallow) - .map_or(String::new(), |(deep, s)| { - let [choice, depth] = [Measure::Choice, Measure::Depth] - .map(|m| m.difficulty(deep, s.best_eval, s.played_eval, a.movers()[i])); - format!( - " (hard: choice {choice:.1} %, depth {depth:.1} %; shallow {} {}, \ - played {}, deep {})", - s.best, - s.best_eval.format(), - s.played_eval.format(), - deep.format() - ) - }); - if theirs == ours_compared { - agree += 1; - println!(" ok {label:<14} {theirs}{hard}"); - } else { - differ += 1; - println!( - " DIFF {label:<14} chess.com {:<3} ours {}{hard}", - or_dash(theirs), - or_dash(ours_compared) - ); - } - } - } - println!("\nagree {agree}, differ {differ}, owner's plain moves marked {owner_wrong}"); - for (t, mark) in tally.iter().zip(["!!", "!"]) { - println!( - "{mark:<2} chess.com {:>3} found {:>3} ({}) ours not chess.com's {:>3} (ours {}, {} of them chess.com's)", - t.theirs, - t.found, - percent(t.found, t.theirs), - t.extra, - t.found + t.extra, - percent(t.found, t.found + t.extra), - ); - } - if differ > 0 { - std::process::exit(1); - } -} - -/// Fills in what the cache lacks (all of it the first time) at `nodes`. -fn review(a: &mut GameAnalysis, game: &Game, engine: &str, nodes: u64) { - let targets = a.begin(game, false); - if let Some(m) = &mut a.meta { - m.nodes = nodes; - } - if !targets.is_empty() { - let settings = JobSettings { - nodes, - ..JobSettings::new(game_review::processes(game_review::MAX_PROCESSES), None) - }; - let cancel = AtomicBool::new(false); - game_review::run( - uci::EngineConfig::new(engine), - &settings, - targets, - &cancel, - &mut |e| a.apply(e), - ) - .expect("engine"); - } - a.refresh(game); -} - -fn mark_of_nags(nags: &[Nag]) -> &'static str { - if nags.contains(&Nag::BRILLIANT_MOVE) { - "!!" - } else if nags.contains(&Nag::GOOD_MOVE) { - "!" - } else { - "" - } -} - -#[derive(Default)] -struct Tally { - theirs: u32, - found: u32, - extra: u32, -} - -fn percent(part: u32, whole: u32) -> String { - if whole == 0 { - "—".into() - } else { - format!("{:.0} %", 100.0 * f64::from(part) / f64::from(whole)) - } -} - -fn or_dash(mark: &str) -> &str { - if mark.is_empty() { "—" } else { mark } -} diff --git a/crates/game-review/examples/review_bench.rs b/crates/game-review/examples/review_bench.rs deleted file mode 100644 index d7ce1fc..0000000 --- a/crates/game-review/examples/review_bench.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Time of the fixed game analysis of one game, and a check that it is the same at any -//! number of engine processes: prints the time and a digest of every evaluation. -//! -//! `cargo run --release -p game-review --example review_bench -- ...` -//! -//! `CP_SHALLOW_NODES=S` adds the shallow searches of S nodes (for how hard a move was to -//! find, `game_review::Hardness`), as rules that use them would. - -use std::sync::atomic::AtomicBool; -use std::time::Instant; - -use game_review::{GameAnalysis, Hardness, JobSettings}; - -fn main() { - let args: Vec = std::env::args().collect(); - if args.len() < 4 { - eprintln!("usage: review_bench ..."); - std::process::exit(2); - } - let text = std::fs::read_to_string(&args[2]).expect("pgn"); - let game = chess_core::parse_str(&text).game; - let shallow: Option = std::env::var("CP_SHALLOW_NODES") - .ok() - .map(|n| n.parse().expect("CP_SHALLOW_NODES: a number")); - let mut digests = Vec::new(); - for p in &args[3..] { - let processes: usize = p.parse().expect("processes"); - let mut a = GameAnalysis::new(&game, None); - if let Some(nodes) = shallow { - a.set_shallow_nodes(nodes); - a.set_hardness(Hardness { - brilliant: Some(100.0), - ..Hardness::default() - }); - } - let targets = a.begin(&game, true); - let positions = targets.len(); - let (mut searches, mut shallows) = (0, 0); - let started = Instant::now(); - game_review::run( - uci::EngineConfig::new(&args[1]), - &JobSettings::new(processes, None), - targets, - &AtomicBool::new(false), - &mut |e| { - if let game_review::JobEvent::Eval { eval, .. } = &e { - searches += 1 + usize::from(eval.second.is_some()); - if let Some(s) = &eval.shallow { - shallows += 1 + usize::from(s.best != s.played); - } - } - a.apply(e); - }, - ) - .expect("engine"); - let secs = started.elapsed().as_secs_f64(); - // Every evaluation, line and second search, in the order of the game. - let all: Vec<_> = (0..a.line().len()).map(|i| a.eval_at(i).cloned()).collect(); - let bytes = serde_json::to_vec(&all).expect("json"); - let digest = bytes.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { - (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3) - }); - println!( - "processes {processes:>2}: {positions} positions, {searches} searches \ - (+{shallows} shallow), {secs:.1} s, evaluations {digest:016x}" - ); - digests.push(digest); - } - if digests.windows(2).any(|w| w[0] != w[1]) { - println!("DIFFERENT evaluations"); - std::process::exit(1); - } -} diff --git a/crates/game-review/src/features.rs b/crates/game-review/src/features.rs index 2de9eb2..08773aa 100644 --- a/crates/game-review/src/features.rs +++ b/crates/game-review/src/features.rs @@ -17,32 +17,15 @@ pub struct MoveFeatures { /// Takes back on the square where the opponent has just taken. pub recapture: bool, /// After the move the opponent can win a piece (a knight or more) for at least two - /// points more than the move took; not a piece selling itself (an attacked piece - /// taking something on its way, a desperado), nor one whose capture loses as much - /// back at once (the move uncovered an attack on a bigger piece: taking is no answer - /// to it). An attacked piece moved quietly to another square where it is lost is - /// offered: it could have stepped away (18…Ra3!! of Pillsbury — Lasker). + /// points more than the move took; a piece that was lost anyway does not count. pub sacrifice: bool, - /// A pawn moved (not taking) to a square where the opponent wins it: offered, but - /// brilliant only for a quicker mate (29…b5+!! of Pillsbury — Lasker). - pub pawn_offered: bool, - pub capture: bool, /// A capture that wins two points or more. pub winning_capture: bool, - /// The capture only wins back what the opponent has just taken, elsewhere (18.fxe6! - /// of Pillsbury — Lasker after 17…Rxc3): no gain, so it can be great. - pub takes_back: bool, /// The first rules' sacrifice ([`Rules::Strict`]): any piece the opponent can win /// after the move, also one that hung before it. pub sacrifice_any: bool, /// A piece (not the king) under attack moves away without loss. pub escape: bool, - /// The move goes into a position of the opening table (chess.com's «book»). - pub book: bool, - /// The move gives check. - pub gives_check: bool, - /// The king moves. - pub king_move: bool, } /// Which rules decide !! and !. Both stay, to compare them and to go back. @@ -59,9 +42,8 @@ pub enum Rules { } impl MoveFeatures { - /// `prev`: the opponent's move just before (for a recapture); `own`: the mover's move - /// before that. - pub fn of(before: &Chess, m: &Move, prev: Option<&Move>, own: Option<&Move>) -> MoveFeatures { + /// `prev`: the opponent's move just before (for a recapture). + pub fn of(before: &Chess, m: &Move, prev: Option<&Move>) -> MoveFeatures { let mover = before.turn(); let mut after = before.clone(); after.play_unchecked(*m); @@ -88,19 +70,12 @@ impl MoveFeatures { (threat, offered) }; let (threat, offered) = worst(&given); - // Taking the offered piece loses at least as much straight away: 18.Bxa7 opening - // the d-file on the queen (18…Rxa7 19.Rxd8) offers nothing — chess.com gives no !!. - let taking_loses = given - .iter() - .filter(|t| t.0 == threat && t.1 == offered) - .any(|t| taking_loses(before.board(), &after, t.2, threat)); let (threat_any, offered_any) = worst(&threats.iter().collect::>()); // The moved piece was hanging where it stood: losing it is no sacrifice. let from_threat = m .from() .map_or(0, |f| pseudo_threat(before.board(), f, mover.other())); let lost_anyway = from_threat >= 2; - let desperado = lost_anyway && m.is_capture(); let on_target = threats.iter().find(|t| t.2 == m.to()).map_or(0, |t| t.0); let gain = taken - on_target; MoveFeatures { @@ -109,25 +84,10 @@ impl MoveFeatures { promotion: m.is_promotion(), mates: after.is_checkmate(), recapture: m.is_capture() && prev.is_some_and(|p| p.is_capture() && p.to() == m.to()), - sacrifice: offered >= 3 && taken - threat <= -2 && !desperado && !taking_loses, - pawn_offered: m.role() == Role::Pawn - && !m.is_capture() - && pseudo_threat(after.board(), m.to(), mover.other()) > 0, - capture: m.is_capture(), + sacrifice: offered >= 3 && taken - threat <= -2 && !lost_anyway, winning_capture: m.is_capture() && gain >= 2, - takes_back: m.is_capture() - && prev.is_some_and(|p| { - // Not the piece the mover had just put there: taking it accepted an - // offer, and winning something now goes on with the combination - // (24…Bxe4+ of Rotlewi — Rubinstein after 23…Rd2 24.Qxd2). - p.capture().is_some_and(|r| gain - value(r) < 2) - && own.is_none_or(|o| o.to() != p.to()) - }), sacrifice_any: offered_any >= 3 && taken - threat_any <= -2 && !lost_anyway, escape: lost_anyway && from_threat < 900 && gain >= 0, - book: chess_openings::in_book(chess_openings::key(&after)), - gives_check: after.is_check(), - king_move: m.role() == Role::King, } } @@ -137,51 +97,26 @@ impl MoveFeatures { Rules::Strict => self.sacrifice_any, Rules::ChessCom => self.sacrifice, }; - sacrifice - && self.legal > 1 - && !self.check - && !self.promotion - && !(rules == Rules::ChessCom && self.book) + sacrifice && self.legal > 1 && !self.check && !self.promotion } /// Could be great: not a forced, obvious or finishing move. With [`Rules::ChessCom`] /// a piece saving itself on the only good square can be (13.Qa4 of the Evergreen - /// game), a book move cannot (6…Bb4+ of Steinitz — von Bardeleben). `bans`: the - /// quiet retreat is not ([`crate::report::Hardness::bans`]). - pub fn great_shape(&self, rules: Rules, bans: bool) -> bool { + /// game). + pub fn great_shape(&self, rules: Rules) -> bool { self.legal > 1 - && !(rules == Rules::ChessCom && self.book) && !self.mates && !self.recapture - && !(self.winning_capture && !(rules == Rules::ChessCom && self.takes_back)) + && !self.winning_capture && !(rules == Rules::Strict && self.escape) - // An attacked piece stepping quietly to its one good square is plain, not - // great (10.Be2 of an online game, the owner: «какой же это !»); stepping away - // with check is an attack (19…Ne2+ of Byrne — Fischer, chess.com's !). - && !(rules == Rules::ChessCom && bans && self.escape && !self.gives_check) - // The king stepping out of check is plain too (the owner, 2026-10-29: 23.Kd3 of - // Capablanca — Marshall, 20…Ka7 of Kasparov — Topalov, 32.Kd2 of Tal — Larsen). - && !(rules == Rules::ChessCom && bans && self.check && self.king_move) } - /// Worth asking the engine for the best other move (under either rules: one analysis - /// serves both); `bans` as for [`Self::great_shape`]. - pub fn candidate(&self, bans: bool) -> bool { - [Rules::Strict, Rules::ChessCom].into_iter().any(|r| { - self.brilliant_shape(r) - || self.pawn_shape(r) - || self.great_shape(r, r == Rules::Strict || bans) - }) - } - - /// Could be brilliant for a quicker mate only: a pawn offered ([`Rules::ChessCom`]). - pub fn pawn_shape(&self, rules: Rules) -> bool { - rules == Rules::ChessCom - && self.pawn_offered - && self.legal > 1 - && !self.check - && !self.promotion - && !self.book + /// Worth asking the engine for the best other move. + /// (Under either rules: one analysis serves both.) + pub fn candidate(&self) -> bool { + [Rules::Strict, Rules::ChessCom] + .into_iter() + .any(|r| self.brilliant_shape(r) || self.great_shape(r)) } } @@ -251,33 +186,6 @@ fn threats(pos: &Chess) -> Vec<(i32, i32, Square)> { out } -/// In `pos` (the opponent to move), taking on `sq` with the cheapest piece lets the -/// mover win at least `threat` elsewhere at once, with a threat the move itself made: -/// there after the move (before the capture), not before it (`before`: the board before -/// the move). One the capture opens is the point of a real sacrifice: 22.Rxe7+!! of -/// Steinitz — von Bardeleben, 22…Qxe7 23.Rxc8+ (the queen left d7); one standing -/// already is too: 37.Rd7!! of Kasparov — Topalov (the queen on c4 under the bishop since -/// 36.Bf1). chess.com marks both. -fn taking_loses(before: &Board, pos: &Chess, sq: Square, threat: i32) -> bool { - let Some(take) = pos - .legal_moves() - .into_iter() - .filter(|m| m.to() == sq && m.is_capture()) - .min_by_key(|m| value(m.role())) - else { - return false; - }; - let mut after = pos.clone(); - after.play_unchecked(take); - let mover = after.turn(); - threats(&after).iter().any(|t| { - t.2 != sq - && t.0 >= threat - && pseudo_threat(pos.board(), t.2, mover) >= threat - && pseudo_threat(before, t.2, mover) < threat - }) -} - /// What `by` would win taking on `sq`, whoever is to move (a piece already hanging). fn pseudo_threat(board: &Board, sq: Square, by: Color) -> i32 { let first = board @@ -306,7 +214,6 @@ mod tests { fn last(start: Chess, moves: &str) -> MoveFeatures { let mut pos = start; let mut prev = None; - let mut own = None; let sans: Vec<&str> = moves .split_whitespace() .filter(|t| !t.ends_with('.')) @@ -314,10 +221,9 @@ mod tests { for (i, san) in sans.iter().enumerate() { let m = san.parse::().unwrap().to_move(&pos).unwrap(); if i + 1 == sans.len() { - return MoveFeatures::of(&pos, &m, prev.as_ref(), own.as_ref()); + return MoveFeatures::of(&pos, &m, prev.as_ref()); } pos.play_unchecked(m); - own = prev; prev = Some(m); } unreachable!() @@ -335,13 +241,10 @@ mod tests { fn a_queen_offered_for_mate_is_a_sacrifice() { let f = last(Chess::default(), OPERA); assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); - assert!(!f.mates && f.candidate(true)); + assert!(!f.mates && f.candidate()); // 15.Bxd7+ Nxd7: taken back, not a move of note. let f = last(Chess::default(), &OPERA[..OPERA.find(" 16.").unwrap()]); - assert!( - f.recapture && !f.great_shape(Rules::ChessCom, true), - "{f:?}" - ); + assert!(f.recapture && !f.great_shape(Rules::ChessCom), "{f:?}"); } #[test] @@ -354,20 +257,17 @@ mod tests { // A free knight taken: a winning capture, never !. let f = features("4k3/8/8/3n4/8/8/8/3QK3 w - - 0 1", "Qxd5"); assert!( - f.winning_capture && !f.great_shape(Rules::ChessCom, true) && !f.sacrifice, + f.winning_capture && !f.great_shape(Rules::ChessCom) && !f.sacrifice, "{f:?}" ); } #[test] fn a_piece_saved_or_lost_anyway_is_no_sacrifice() { - // The bishop on c4 attacked by the pawn on d5: Bb3 saves it — never a sacrifice, - // and a quiet step away is not great either. + // The bishop on c4 attacked by the pawn on d5: Bb3 saves it, which can be the only + // good move (great), never a sacrifice. let f = features("4k3/8/8/3p4/2B5/8/8/4K3 w - - 0 1", "Bb3"); - assert!( - f.escape && !f.sacrifice && !f.great_shape(Rules::ChessCom, true), - "{f:?}" - ); + assert!(f.great_shape(Rules::ChessCom) && !f.sacrifice, "{f:?}"); // Taking the pawn instead, into the knight: it was lost anyway (desperado). let f = features("4k3/8/5n2/3p4/2B5/8/8/4K3 w - - 0 1", "Bxd5"); assert!(!f.sacrifice, "{f:?}"); @@ -376,8 +276,6 @@ mod tests { #[test] fn only_what_the_move_gives_up_is_offered() { // The knight on e5 hangs to the pawn on d6 before and after Ra2: not given by it. - // (Counting a piece left hanging as given would mark 17…Be6!! of Byrne — Fischer, - // but also 11.Rg1, 19.e5 of the Immortal game and more that chess.com does not.) let f = features("4k3/8/3p4/4N3/8/8/8/R3K3 w - - 0 1", "Ra2"); assert!(!f.sacrifice, "{f:?}"); // The rook on e1 guards it; Ra1 takes the guard away: the knight is given up. @@ -385,124 +283,6 @@ mod tests { assert!(f.sacrifice, "{f:?}"); } - #[test] - fn a_piece_whose_capture_loses_more_is_not_offered() { - // 18.Bxa7 (a game against Rodent, 2026-10-27): the bishop under the rook on a8, but - // the move opens the d-file on the queen: 18…Rxa7 19.Rxd8. chess.com: no !!. - let f = last( - Chess::default(), - "1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 Qa5 \ - 8. O-O O-O 9. Bb3 d6 10. f3 Bd7 11. Qe1 Nxd4 12. Bxd4 Bc6 13. Nd5 Qd8 \ - 14. Nxf6+ exf6 15. Qc3 d5 16. Rad1 dxe4 17. fxe4 Bxe4 18. Bxa7", - ); - assert!(!f.sacrifice && !f.brilliant_shape(Rules::ChessCom), "{f:?}"); - assert!(f.sacrifice_any, "the first rules stay as they were: {f:?}"); - } - - #[test] - fn a_threat_the_capture_opens_keeps_the_sacrifice() { - // 22.Rxe7+!! (Steinitz — von Bardeleben): 22…Qxe7 23.Rxc8+ wins back, but only - // because the queen left d7. chess.com: !!. - let f = last( - Chess::default(), - "1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 d5 \ - 8. exd5 Nxd5 9. O-O Be6 10. Bg5 Be7 11. Bxd5 Bxd5 12. Nxd5 Qxd5 13. Bxe7 Nxe7 \ - 14. Re1 f6 15. Qe2 Qd7 16. Rac1 c6 17. d5 cxd5 18. Nd4 Kf7 19. Ne6 Rhc8 \ - 20. Qg4 g6 21. Ng5+ Ke8 22. Rxe7+", - ); - assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); - } - - const PILLSBURY: &str = "1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. Bg5 cxd4 6. Qxd4 Nc6 \ - 7. Qh4 Be7 8. O-O-O Qa5 9. e3 Bd7 10. Kb1 h6 11. cxd5 exd5 12. Nd4 O-O 13. Bxf6 Bxf6 \ - 14. Qh5 Nxd4 15. exd4 Be6 16. f4 Rac8 17. f5 Rxc3 18. fxe6 Ra3"; - - #[test] - fn an_attacked_piece_moved_into_another_attack_is_offered() { - // 18…Ra3!! (Pillsbury — Lasker): the rook on c3 under the pawn could step away. - let f = last(Chess::default(), PILLSBURY); - assert!(f.sacrifice && f.brilliant_shape(Rules::ChessCom), "{f:?}"); - // 18.fxe6! just before: takes back the knight taken on c3, no gain. - let f = last( - Chess::default(), - &PILLSBURY[..PILLSBURY.rfind(" Ra3").unwrap()], - ); - assert!( - f.winning_capture && f.takes_back && f.great_shape(Rules::ChessCom, true), - "{f:?}" - ); - assert!( - !f.great_shape(Rules::Strict, true), - "the first rules stay: {f:?}" - ); - } - - #[test] - fn taking_back_an_offered_piece_is_no_trade() { - // 24…Bxe4+ (Rotlewi — Rubinstein) after 23…Rd2 24.Qxd2: the combination goes on. - let f = last( - Chess::default(), - "1. d4 d5 2. Nf3 e6 3. e3 c5 4. c4 Nc6 5. Nc3 Nf6 6. dxc5 Bxc5 7. a3 a6 8. b4 Bd6 \ - 9. Bb2 O-O 10. Qd2 Qe7 11. Bd3 dxc4 12. Bxc4 b5 13. Bd3 Rd8 14. Qe2 Bb7 \ - 15. O-O Ne5 16. Nxe5 Bxe5 17. f4 Bc7 18. e4 Rac8 19. e5 Bb6+ 20. Kh1 Ng4 \ - 21. Be4 Qh4 22. g3 Rxc3 23. gxh4 Rd2 24. Qxd2 Bxe4+", - ); - assert!( - f.winning_capture && !f.takes_back && !f.great_shape(Rules::ChessCom, true), - "{f:?}" - ); - } - - #[test] - fn a_pawn_offered_is_only_for_a_quicker_mate() { - // 29…b5+!! (Pillsbury — Lasker): the pawn under the king. - let line = format!( - "{PILLSBURY} 19. exf7+ Rxf7 20. bxa3 Qb6+ 21. Bb5 Qxb5+ 22. Ka1 Rc7 23. Rd2 Rc4 \ - 24. Rhd1 Rc3 25. Qf5 Qc4 26. Kb2 Rxa3 27. Qe6+ Kh7 28. Kxa3 Qc3+ 29. Ka4 b5+" - ); - let f = last(Chess::default(), &line); - assert!(f.pawn_offered && f.pawn_shape(Rules::ChessCom), "{f:?}"); - assert!(!f.sacrifice && !f.brilliant_shape(Rules::ChessCom), "{f:?}"); - assert!(!f.pawn_shape(Rules::Strict)); - } - - #[test] - fn a_quiet_escape_is_not_great_but_one_with_check_can_be() { - // 10.Be2 (an online game): the bishop on d3 under the pawn steps to its one good - // square — plain. - let f = last( - Chess::default(), - "1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Nge7 6. Na3 Bd7 7. Nc2 Nf5 \ - 8. Bd3 Nh4 9. O-O c4 10. Be2", - ); - assert!(f.escape && !f.gives_check, "{f:?}"); - assert!(!f.great_shape(Rules::ChessCom, true), "{f:?}"); - assert!(!f.candidate(true), "{f:?}"); - // Without the bans it is up to how hard it was to find. - assert!( - f.great_shape(Rules::ChessCom, false) && f.candidate(false), - "{f:?}" - ); - // Stepping away with check can be great. - let f = features("4k3/8/8/8/2p5/1B6/8/4K3 w - - 0 1", "Ba4+"); - assert!( - f.escape && f.gives_check && f.great_shape(Rules::ChessCom, true), - "{f:?}" - ); - } - - #[test] - fn the_king_out_of_check_is_not_great() { - // The king in check from the rook steps to the side: plain. - let f = features("4k3/8/8/8/8/8/8/r3K3 w - - 0 1", "Ke2"); - assert!(f.check && f.king_move, "{f:?}"); - assert!(!f.great_shape(Rules::ChessCom, true), "{f:?}"); - assert!( - f.great_shape(Rules::Strict, true), - "the first rules stay: {f:?}" - ); - } - #[test] fn a_piece_no_one_can_legally_take_is_not_offered() { // The rook on d7 is pinned by the bishop: the knight on d5 is no offer to it. diff --git a/crates/game-review/src/job.rs b/crates/game-review/src/job.rs index d215e20..a937703 100644 --- a/crates/game-review/src/job.rs +++ b/crates/game-review/src/job.rs @@ -1,98 +1,16 @@ -//! The engine job of a game analysis: one node-limited search per position, in engine -//! processes of its own, results reported as they come. Runs on the caller's thread -//! until it is done or cancelled; the game is never touched. -//! -//! The search is the same everywhere (decision of 2026-10-28): every position is -//! searched to [`SEARCH_NODES`] nodes by an engine with one thread and a hash of -//! [`SEARCH_HASH_MB`], cleared (`ucinewgame`) before each search. One thread and a -//! clear hash make a search depend on its position alone — not on the machine, the -//! order of the positions or what was searched before — so every computer and phone -//! gets the same evaluations, and the same marks. Speed comes from several engine -//! processes, each taking the next position; their number changes nothing but the time. +//! The engine job of a game analysis: its own engine process, one node-limited search +//! per position, results reported as they come. Runs on the caller's thread until it +//! is done or cancelled; the game is never touched. -use uci::{EnginePosition, Side}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; -use crate::PosEval; +use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits, Side}; -// What the job does for one target, whatever drives it. -mod work; -// The job in engine processes, each on a thread of its own: a computer's and a -// phone's. -#[cfg(not(target_family = "wasm"))] -mod engines; -#[cfg(not(target_family = "wasm"))] -pub use engines::run; -// Whether an engine is the Stockfish 19 of the analysis (a user's own one). -#[cfg(not(target_family = "wasm"))] -pub mod probe; -// The job in Web Workers: a browser's. -#[cfg(target_family = "wasm")] -mod workers; -#[cfg(target_family = "wasm")] -pub use workers::Dispatcher; +use crate::{Eval, PosEval, Second}; -/// Nodes of every search of a game analysis (0.85 s on one thread of an i7-13700KF, -/// depth about 24). -pub const SEARCH_NODES: u64 = 1_000_000; - -/// Nodes of the shallow search, for how hard a move is to find ([`crate::Measure`]): -/// made only for a move that could be brilliant or great and was the engine's best, and -/// only when the rules ask for it ([`crate::Hardness`]). At 5 000 nodes (depth about 10) -/// Stockfish already finds nearly every move of note itself; above 10 000 hardly any is -/// hard (the chess.com check set, 2026-10-29). Its time is lost in that of the full -/// searches (+0.2 % for a game). -pub const SHALLOW_NODES: u64 = 5_000; - -/// The engine's hash of every search, in MB. Part of the search: another size gives -/// other evaluations. -pub const SEARCH_HASH_MB: u32 = 32; - -/// The version of the fixed search: [`SEARCH_NODES`], [`SEARCH_HASH_MB`], one thread, a -/// clear hash, and the engine (ChessPenguin's Stockfish 19). Raised when any of them -/// changes: evaluations of another version are stale and are made again, never mixed. -pub const SEARCH_VERSION: u32 = 1; - -/// Engine processes of a job on a computer at most. -pub const MAX_PROCESSES: usize = 8; - -/// Engine processes of a job on a phone at most. -pub const PHONE_PROCESSES: usize = 4; - -/// Memory of the engine's network, shared by all its processes (Stockfish 19 keeps it -/// in shared memory), in MB. -const SHARED_MB: u64 = 200; - -/// Memory of one engine process of its own (the hash of [`SEARCH_HASH_MB`] included), -/// in MB. -const PROCESS_MB: u64 = 70; - -/// Engine processes for a job on this machine: one per logical CPU, at most `limit` -/// (and [`MAX_PROCESSES`]), and no more than the free memory holds. -pub fn processes(limit: usize) -> usize { - let cpus = std::thread::available_parallelism().map_or(1, |n| n.get()); - let memory = available_mb().map_or(usize::MAX, |mb| { - (mb.saturating_sub(SHARED_MB) / PROCESS_MB) - .try_into() - .unwrap_or(usize::MAX) - }); - cpus.min(limit).min(memory).clamp(1, MAX_PROCESSES) -} - -/// Memory available to new processes (`MemAvailable` of Linux and Android), in MB; -/// `None` where it is not known. -fn available_mb() -> Option { - let info = std::fs::read_to_string("/proc/meminfo").ok()?; - let line = info.lines().find(|l| l.starts_with("MemAvailable:"))?; - let kb: u64 = line.split_whitespace().nth(1)?.parse().ok()?; - Some(kb / 1024) -} - -/// Seconds `searches` take at `nps` nodes per second of one engine process (one -/// thread), in `processes` of them: the time estimate of a run. -pub fn estimate_secs(searches: usize, nps: f64, processes: usize) -> f64 { - let rate = nps.max(1.0) * processes.clamp(1, MAX_PROCESSES) as f64; - searches as f64 * SEARCH_NODES as f64 / rate -} +/// A node-limited search should never take this long; stop it if it does. +const SEARCH_GUARD: Duration = Duration::from_secs(300); /// A position to evaluate (from [`crate::GameAnalysis::begin`]). #[derive(Clone, Debug)] @@ -105,34 +23,19 @@ pub struct Target { pub played: Option, /// The other legal moves (UCI). pub others: Vec, - /// The evaluation already there: only the second or shallow search is left. + /// The evaluation already there: only the second search is left. pub known: Option, - /// Nodes of the shallow search of `played`, when the rules want it. - pub shallow: Option, } -/// How the job runs; the search itself is fixed (see the module). +/// How the engine searches. #[derive(Clone, Debug)] pub struct JobSettings { - /// Engine processes working at once (see [`processes`]). - pub processes: usize, + pub threads: u32, + pub hash_mb: u32, + /// Nodes per position. + pub nodes: u64, /// The network file of the engine (Stockfish `EvalFile`), when it is not beside it. pub eval_file: Option, - /// Nodes per search: [`SEARCH_NODES`] in the programs. Only an experiment (the - /// chess.com check, choosing the nodes) searches otherwise, never mixing its - /// evaluations with the programs'. - pub nodes: u64, -} - -impl JobSettings { - /// The fixed search in `processes` engine processes. - pub fn new(processes: usize, eval_file: Option) -> JobSettings { - JobSettings { - processes, - eval_file, - nodes: SEARCH_NODES, - } - } } /// What the job reports, for [`crate::GameAnalysis::apply`]. @@ -143,8 +46,7 @@ pub enum JobEvent { Eval { key: String, eval: PosEval, - /// The speed of the engine process in this search (one thread; 0 if it did - /// not say). + /// The engine's speed in this search (0 if it did not say). nps: u64, }, } @@ -160,39 +62,189 @@ pub enum JobFailure { Terminated(uci::TerminationReason), } +/// Evaluates `targets` one by one; `on_event` gets every result. Returns when all are +/// done, or soon after `cancel` is set (then with `Ok`). +pub fn run( + config: uci::EngineConfig, + settings: &JobSettings, + targets: Vec, + cancel: &AtomicBool, + on_event: &mut dyn FnMut(JobEvent), +) -> Result<(), JobFailure> { + let handle = uci::Engine::spawn_with(config, Box::new(|| {})) + .map_err(|e| JobFailure::Start(e.to_string()))?; + if let Some(name) = &handle.info().name { + on_event(JobEvent::Engine(name.clone())); + } + if let Some(file) = &settings.eval_file { + handle + .set_option("EvalFile", Some(file)) + .map_err(|e| JobFailure::Start(e.to_string()))?; + } + // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. + let _ = handle.set_threads(settings.threads.max(1)); + let _ = handle.set_hash_mb(settings.hash_mb.max(1)); + let _ = handle.set_multipv(1); + let _ = handle.new_game(); + let mut next_id = 0; + let mut search = |pos: &EnginePosition, among: Vec| { + next_id += 1; + search_once( + &handle, + pos, + SearchId(next_id), + among, + settings.nodes, + cancel, + ) + }; + for t in targets { + let (mut eval, nps) = match t.known { + Some(e) => (e, 0), + None => { + let Some((info, best)) = search(&t.pos, Vec::new())? else { + if cancel.load(Ordering::Relaxed) { + handle.quit(); + return Ok(()); + } + continue; + }; + let Some(score) = info.score else { continue }; + let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); + if let Some(b) = best + && pv.first() != Some(&b) + { + pv = vec![b]; + } + let eval = PosEval { + eval: Eval::from_white_eval(score.to_white(t.turn).eval), + pv, + depth: info.depth.unwrap_or(0), + second: None, + }; + (eval, info.nps.unwrap_or(0)) + } + }; + // The move played is the engine's best: what the best of the others gives says + // whether it was the only good move, or a sacrifice when nothing else won. + let mover = match t.turn { + Side::White => chess_core::shakmaty::Color::White, + Side::Black => chess_core::shakmaty::Color::Black, + }; + if let Some(played) = &t.played + && eval.pv.first() == Some(played) + && !t.others.is_empty() + && crate::report::worth_second(eval.eval, mover) + { + match search(&t.pos, t.others.clone())? { + // An engine that ignores `searchmoves` answers with the move played: + // no second move then. + Some((info, best)) + if best.as_ref() != Some(played) && info.pv.first() != Some(played) => + { + if let Some(score) = info.score { + eval.second = Some(Second { + without: played.clone(), + eval: Eval::from_white_eval(score.to_white(t.turn).eval), + }); + } + } + None if cancel.load(Ordering::Relaxed) => { + handle.quit(); + return Ok(()); + } + _ => {} + } + } + on_event(JobEvent::Eval { + key: t.key, + eval, + nps, + }); + } + handle.quit(); + Ok(()) +} + +/// One node-limited search: its last full line and the best move. `None` when it gave +/// no line or `cancel` was set. +fn search_once( + handle: &uci::EngineHandle, + pos: &EnginePosition, + id: SearchId, + among: Vec, + nodes: u64, + cancel: &AtomicBool, +) -> Result)>, JobFailure> { + handle + .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) + .map_err(|e| JobFailure::Engine(e.to_string()))?; + let started = Instant::now(); + let mut stopping = false; + let mut last: Option = None; + loop { + if cancel.load(Ordering::Relaxed) { + return Ok(None); + } + if !stopping && started.elapsed() > SEARCH_GUARD { + let _ = handle.stop(); + stopping = true; + } + match handle.recv_timeout(Duration::from_millis(100)) { + Some(EngineEvent::Info { search_id, info }) if search_id == id => { + if info.multipv_index() == 1 && info.score.is_some() { + let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); + if exact || last.is_none() { + last = Some(info); + } + } + } + Some(EngineEvent::BestMove { + search_id, best, .. + }) if search_id == id => { + return Ok(last.map(|info| (info, best.map(|b| b.to_string())))); + } + Some(EngineEvent::Terminated(reason)) => { + return Err(JobFailure::Terminated(reason)); + } + _ => {} + } + } +} + #[cfg(test)] mod tests { use super::*; - use crate::Eval; - use crate::GameAnalysis; - use std::sync::atomic::{AtomicBool, Ordering}; + use crate::{GameAnalysis, ReviewMeta}; - /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). - fn fake() -> &'static str { + /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`) answers + /// like Stockfish: every position gets an evaluation, in order. + #[test] + fn the_job_evaluates_every_position() { let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); assert!( std::path::Path::new(fake).exists(), "build the fake engine first: cargo build -p uci --bin fake_uci" ); - fake - } - - fn settings(processes: usize) -> JobSettings { - JobSettings::new(processes, None) - } - - /// The fake engine answers like Stockfish: every position gets an evaluation. - #[test] - fn the_job_evaluates_every_position() { let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 *").game; let mut a = GameAnalysis::new(&game, None); - let targets = a.begin(&game, false); + let meta = ReviewMeta { + engine: String::new(), + nodes: 1000, + }; + let targets = a.begin(&game, meta, false); let n = targets.len(); + let settings = JobSettings { + threads: 1, + hash_mb: 16, + nodes: 1000, + eval_file: None, + }; let mut evals = 0; let cancel = AtomicBool::new(false); run( - uci::EngineConfig::new(fake()), - &settings(2), + uci::EngineConfig::new(fake), + &settings, targets, &cancel, &mut |e| { @@ -207,16 +259,15 @@ mod tests { a.refresh(&game); assert_eq!(a.missing(), 0); assert!(a.report.complete); - assert_eq!(a.meta.as_ref().map(|m| m.engine.as_str()), Some("Fake UCI")); // A cancelled job ends at once, without results. let mut b = GameAnalysis::new(&game, None); - let targets = b.begin(&game, false); + let targets = b.begin(&game, ReviewMeta::default(), false); cancel.store(true, Ordering::Relaxed); let mut got = 0; run( - uci::EngineConfig::new(fake()), - &settings(3), + uci::EngineConfig::new(fake), + &settings, targets, &cancel, &mut |e| { @@ -228,183 +279,4 @@ mod tests { .expect("cancelled cleanly"); assert_eq!(got, 0); } - - /// The evaluations depend on the positions alone: not on the number of engine - /// processes, nor on the order of the positions. The fake engine with `--hash-memory` - /// lets earlier searches change a score, as a hash kept between searches does: only - /// a clear hash before every search gives the same results. - #[test] - fn the_evaluations_do_not_depend_on_processes_or_order() { - let game = chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 *").game; - let evaluate = |processes: usize, reverse: bool| { - let mut a = GameAnalysis::new(&game, None); - let mut targets = a.begin(&game, false); - if reverse { - targets.reverse(); - } - let mut config = uci::EngineConfig::new(fake()); - config.args = vec!["--hash-memory".into()]; - run( - config, - &settings(processes), - targets, - &AtomicBool::new(false), - &mut |e| a.apply(e), - ) - .expect("the job runs"); - a.refresh(&game); - (0..a.line().len()) - .map(|i| a.eval_at(i).cloned()) - .collect::>() - }; - let one = evaluate(1, false); - assert!(one.iter().all(Option::is_some)); - // The fake scores differ by position: the comparison means something. - assert!(one.windows(2).any(|w| w[0] != w[1])); - assert_eq!(evaluate(1, true), one); - assert_eq!(evaluate(3, false), one); - assert_eq!(evaluate(8, true), one); - } - - /// The shallow search is made only when the rules ask how hard a move was to find, - /// for the engine's best move that could be brilliant or great; an analysis without - /// it is filled in, without evaluating anything again. The fake engine (from a FEN - /// it always says e2e4) honours `searchmoves`, and below the nodes given prefers - /// d2d4 (+0.40) to e2e4 (+0.10 searched alone). - #[test] - fn the_shallow_search_says_how_hard_the_move_was() { - let game = chess_core::parse_str( - "[FEN \"rnbqkbnr/1ppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1\"] 1. e4 e5 *", - ) - .game; - let engine = |shallow_best: bool| { - let mut config = uci::EngineConfig::new(fake()); - config.args = vec!["--searchmoves".into()]; - if shallow_best { - config.args.extend([ - "--shallow".into(), - (SHALLOW_NODES + 1).to_string().into(), - "d2d4".into(), - ]); - } - config - }; - let job = |a: &mut GameAnalysis, shallow_best: bool| { - let targets = a.begin(&game, false); - let n = targets.len(); - run( - engine(shallow_best), - &settings(2), - targets, - &AtomicBool::new(false), - &mut |e| a.apply(e), - ) - .expect("the job runs"); - a.refresh(&game); - n - }; - let mut a = GameAnalysis::new(&game, None); - // Rules that do not ask how hard a move was: no shallow search. - a.set_hardness(crate::Hardness { - brilliant: None, - ..Default::default() - }); - assert_eq!(job(&mut a, true), 3); - let e = a.eval_at(0).expect("evaluated").clone(); - assert_eq!(e.pv.first().map(String::as_str), Some("e2e4")); - assert_eq!(e.second.as_ref().map(|s| s.eval), Some(Eval::Cp(10))); - assert!(e.shallow.is_none(), "the rules do not ask for it"); - assert_eq!(a.seconds_missing(), 0); - - // Rules that ask for it: the earlier analysis wants the shallow search only. - let hard = crate::Hardness { - great: Some(1.0), - gap: 1.0, - ..Default::default() - }; - a.set_hardness(hard); - a.refresh(&game); - assert_eq!(a.seconds_missing(), 1); - assert_eq!(a.report.judgements[0], None, "not known to be hard"); - assert_eq!(job(&mut a, true), 1); - assert_eq!(a.seconds_missing(), 0); - let e = a.eval_at(0).expect("evaluated"); - let s = e.shallow.as_ref().expect("the shallow search"); - assert_eq!( - (s.nodes, s.played.as_str(), s.best.as_str()), - (SHALLOW_NODES, "e2e4", "d2d4") - ); - assert_eq!((s.best_eval, s.played_eval), (Eval::Cp(40), Eval::Cp(10))); - assert_eq!(e.second.as_ref().map(|s| s.eval), Some(Eval::Cp(10))); - // 2.8 % harder than the shallow best: great at 1 %, not at 5 %, brilliant at 2 %. - let d = crate::Measure::Choice.difficulty( - e.eval, - s.best_eval, - s.played_eval, - chess_core::shakmaty::Color::White, - ); - assert!((2.0..5.0).contains(&d), "{d}"); - assert_eq!(a.report.judgements[0], Some(crate::Judgement::Great)); - a.set_hardness(crate::Hardness { - great: Some(5.0), - ..hard - }); - a.refresh(&game); - assert_eq!(a.report.judgements[0], None); - a.set_hardness(crate::Hardness { - brilliant: Some(2.0), - brilliant_gap: 1.0, - ..hard - }); - a.refresh(&game); - assert_eq!(a.report.judgements[0], Some(crate::Judgement::Brilliant)); - // Shallow searches of other nodes are made again. - a.set_shallow_nodes(SHALLOW_NODES / 2); - a.refresh(&game); - assert_eq!(a.seconds_missing(), 1); - assert_eq!(a.report.judgements[0], None); - - // The shallow search finding the move itself: not hard at all. - let mut b = GameAnalysis::new(&game, None); - b.set_hardness(hard); - assert_eq!(job(&mut b, false), 3); - let s = b - .eval_at(0) - .and_then(|e| e.shallow.clone()) - .expect("shallow"); - assert_eq!( - (s.best.as_str(), s.best_eval, s.played_eval), - ("e2e4", Eval::Cp(40), Eval::Cp(40)) - ); - assert_eq!(b.report.judgements[0], None, "0 % is below 1 %"); - } - - #[test] - fn a_failing_engine_fails_the_job() { - let game = chess_core::parse_str("1. e4 e5 *").game; - let mut a = GameAnalysis::new(&game, None); - let targets = a.begin(&game, false); - let result = run( - uci::EngineConfig::new("/nonexistent/engine"), - &settings(2), - targets, - &AtomicBool::new(false), - &mut |_| {}, - ); - assert!(matches!(result, Err(JobFailure::Start(_)))); - } - - #[test] - fn processes_are_bounded() { - assert_eq!(processes(1), 1); - assert!((1..=MAX_PROCESSES).contains(&processes(usize::MAX))); - assert_eq!(processes(0), 1); - assert!(processes(PHONE_PROCESSES) <= PHONE_PROCESSES); - } - - #[test] - fn the_estimate_counts_every_process() { - assert_eq!(estimate_secs(10, 1_000_000.0, 1), 10.0); - assert_eq!(estimate_secs(10, 1_000_000.0, 4), 2.5); - } } diff --git a/crates/game-review/src/job/engines.rs b/crates/game-review/src/job/engines.rs deleted file mode 100644 index 8e5b5ea..0000000 --- a/crates/game-review/src/job/engines.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! The engine job in engine processes, each driven from a thread of its own. - -use std::collections::HashSet; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::mpsc::channel; -use std::time::{Duration, Instant}; - -use uci::{EngineEvent, EnginePosition, ScoreBound, SearchId, SearchLimits}; - -use super::work::{Answer, Next, Work}; -use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target}; - -/// A node-limited search should never take this long; stop it if it does. -const SEARCH_GUARD: Duration = Duration::from_secs(300); - -enum WorkerMsg { - Event(JobEvent), - Failed(JobFailure), -} - -/// Evaluates `targets` in `settings.processes` engine processes; `on_event` gets every -/// result, on the caller's thread, in the order they come. Returns when all are done, -/// or soon after `cancel` is set (then with `Ok`). When an engine fails, the others -/// stop too and the first failure is returned; what came before it was reported. -pub fn run( - config: uci::EngineConfig, - settings: &JobSettings, - targets: Vec, - cancel: &AtomicBool, - on_event: &mut dyn FnMut(JobEvent), -) -> Result<(), JobFailure> { - if targets.is_empty() { - return Ok(()); - } - let workers = settings - .processes - .clamp(1, MAX_PROCESSES) - .min(targets.len()); - let next = AtomicUsize::new(0); - let failed = AtomicBool::new(false); - let halted = || cancel.load(Ordering::Relaxed) || failed.load(Ordering::Relaxed); - let (tx, rx) = channel(); - let mut failure = None; - std::thread::scope(|s| { - for _ in 0..workers { - let tx = tx.clone(); - let (config, targets, next, halted) = (config.clone(), &targets, &next, &halted); - s.spawn(move || { - let mut send = |e| { - let _ = tx.send(WorkerMsg::Event(e)); - }; - if let Err(e) = worker(config, settings, targets, next, halted, &mut send) { - let _ = tx.send(WorkerMsg::Failed(e)); - } - }); - } - drop(tx); - let mut names = HashSet::new(); - for msg in rx { - match msg { - WorkerMsg::Event(JobEvent::Engine(name)) => { - if names.insert(name.clone()) { - on_event(JobEvent::Engine(name)); - } - } - WorkerMsg::Event(e) => on_event(e), - WorkerMsg::Failed(e) => { - failed.store(true, Ordering::Relaxed); - failure.get_or_insert(e); - } - } - } - }); - match failure { - Some(e) if !cancel.load(Ordering::Relaxed) => Err(e), - _ => Ok(()), - } -} - -/// One engine process: takes the next target until there is none or `halted`. -fn worker( - config: uci::EngineConfig, - settings: &JobSettings, - targets: &[Target], - next: &AtomicUsize, - halted: &dyn Fn() -> bool, - on_event: &mut dyn FnMut(JobEvent), -) -> Result<(), JobFailure> { - let handle = uci::Engine::spawn_with(config, Box::new(|| {})) - .map_err(|e| JobFailure::Start(e.to_string()))?; - if let Some(name) = &handle.info().name { - on_event(JobEvent::Engine(name.clone())); - } - if let Some(file) = &settings.eval_file { - handle - .set_option("EvalFile", Some(file)) - .map_err(|e| JobFailure::Start(e.to_string()))?; - } - // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. - let _ = handle.set_threads(1); - let _ = handle.set_hash_mb(SEARCH_HASH_MB); - let _ = handle.set_multipv(1); - let mut next_id = 0; - // Every search starts from a clear hash, so that it depends on its position alone. - let mut search = |pos: &EnginePosition, among: Vec, nodes: u64| { - next_id += 1; - let _ = handle.new_game(); - search_once( - &handle, - pos, - SearchId(next_id), - among, - nodes, - SEARCH_GUARD, - halted, - ) - }; - 'targets: while let Some(t) = targets.get(next.fetch_add(1, Ordering::Relaxed)) { - if halted() { - break; - } - let mut work = Work::new(t.clone(), settings.nodes); - loop { - match work.next() { - Next::Search { pos, among, nodes } => { - let answer = search(&pos, among, nodes)?; - if answer.is_none() && halted() { - break 'targets; - } - work.answer(answer); - } - Next::Done(event) => { - if let Some(e) = event { - on_event(e); - } - break; - } - } - } - } - handle.quit(); - Ok(()) -} - -/// One node-limited search: its last full line and the best move. `None` when it gave -/// no line or the job was halted. After `guard` the search is stopped (an engine that -/// ignores `stop` is killed by the `uci` crate's stop timeout: `Terminated`). -pub(super) fn search_once( - handle: &uci::EngineHandle, - pos: &EnginePosition, - id: SearchId, - among: Vec, - nodes: u64, - guard: Duration, - halted: &dyn Fn() -> bool, -) -> Result { - handle - .search_among(pos.clone(), id, SearchLimits::Nodes(nodes), among) - .map_err(|e| JobFailure::Engine(e.to_string()))?; - let started = Instant::now(); - let mut stopping = false; - let mut last: Option = None; - loop { - if halted() { - return Ok(None); - } - if !stopping && started.elapsed() > guard { - let _ = handle.stop(); - stopping = true; - } - match handle.recv_timeout(Duration::from_millis(100)) { - Some(EngineEvent::Info { search_id, info }) if search_id == id => { - if info.multipv_index() == 1 && info.score.is_some() { - let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); - if exact || last.is_none() { - last = Some(info); - } - } - } - Some(EngineEvent::BestMove { - search_id, best, .. - }) if search_id == id => { - return Ok(last.map(|info| (info, best.map(|b| b.to_string())))); - } - Some(EngineEvent::Terminated(reason)) => { - return Err(JobFailure::Terminated(reason)); - } - _ => {} - } - } -} diff --git a/crates/game-review/src/job/probe.rs b/crates/game-review/src/job/probe.rs deleted file mode 100644 index b0956f2..0000000 --- a/crates/game-review/src/job/probe.rs +++ /dev/null @@ -1,312 +0,0 @@ -//! Whether an engine is the Stockfish 19 of the game analysis: its search gives the same -//! evaluations as ChessPenguin's, so a user's own Stockfish 19 can do the analysis and -//! the marks stay the same on every computer. -//! -//! Its name is not enough (a build of another commit, another network or a patched one -//! says the same). A few short searches in the fixed mode of the analysis — one -//! thread, a hash of [`SEARCH_HASH_MB`], `ucinewgame` before each, [`PROBE_NODES`] -//! nodes — are compared with those of ChessPenguin's Stockfish 19 ([`REFERENCE`]): the -//! best move, the score and the nodes of the line taken must all be the same. Stockfish -//! with one thread and a node limit is deterministic, whatever the CPU's instruction -//! set: its own check of the universal build (`scripts/check_universal.sh` of the -//! release) requires the same `bench` node count from every per-CPU build. - -use std::time::{Duration, Instant}; - -use uci::{EnginePosition, Score}; - -use super::engines::search_once; -use super::{JobFailure, SEARCH_HASH_MB}; - -/// Nodes of each probe search (about 0.1 s each). -pub const PROBE_NODES: u64 = 100_000; - -/// The name Stockfish 19 gives itself (`id name`). -pub const STOCKFISH_19: &str = "Stockfish 19"; - -/// What a probe search gives: the best move, the score of the line taken (the side to -/// move's) and its nodes. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ProbeAnswer { - pub best: String, - pub score: Score, - pub nodes: u64, -} - -/// The positions of the probe: an opening, a middlegame full of tactics, an endgame. -pub const PROBE_POSITIONS: [&str; 3] = [ - "r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3", - "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1", - "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1", -]; - -/// ChessPenguin's Stockfish 19 (the official `stockfish-linux-x86-64-universal`, sha256 -/// of its archive in `engine_download`) on [`PROBE_POSITIONS`], taken 2026-10-31. The -/// same from its x86-64-avxvnni slice and from builds of its source for x86-64 (SSE2) -/// and x86-64-bmi2. -pub const REFERENCE: [(&str, Score, u64); 3] = [ - ("a7a6", Score::Cp(-36), 76_994), - ("e2a6", Score::Cp(-196), 49_328), - ("b4f4", Score::Cp(176), 38_955), -]; - -/// What the probe found. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Probe { - /// The engine's name (`id name`). - pub name: Option, - /// The answers, one per position of [`PROBE_POSITIONS`] (fewer when one gave none, - /// took too long, or the engine is not called Stockfish 19: then none is searched). - pub answers: Vec, - /// A search took longer than allowed (an engine that ignores `go nodes`). - pub timed_out: bool, -} - -impl Probe { - /// Whether the engine is the Stockfish 19 of the analysis: its name and every answer. - pub fn same(&self) -> bool { - self.name.as_deref() == Some(STOCKFISH_19) - && self.answers.len() == REFERENCE.len() - && self - .answers - .iter() - .zip(REFERENCE) - .all(|(a, (best, score, nodes))| { - a.best == best && a.score == score && a.nodes == nodes - }) - } -} - -/// How long the probe may take: a search (Stockfish needs about 0.1 s) and all of it. -#[derive(Clone, Copy, Debug)] -pub struct ProbeLimits { - pub search: Duration, - pub total: Duration, -} - -impl Default for ProbeLimits { - fn default() -> Self { - ProbeLimits { - search: Duration::from_secs(10), - total: Duration::from_secs(30), - } - } -} - -/// What [`REFERENCE`] is a reference of — the positions, the nodes, the hash, the -/// answers — as a short text kept with the verdicts: a verdict of another probe is -/// not trusted. (FNV-1a of their text: the same in every build.) -pub fn reference_key() -> String { - let text = format!("{PROBE_POSITIONS:?}|{PROBE_NODES}|{SEARCH_HASH_MB}|{REFERENCE:?}"); - let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| { - (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3) - }); - format!("{hash:016x}") -} - -/// Runs the probe in a process of the engine; `halted` gives it up (the program -/// quits). An engine not called Stockfish 19 is not searched at all. The engine is -/// quit at the end (killed if it does not go). -pub fn probe( - config: uci::EngineConfig, - limits: ProbeLimits, - halted: &dyn Fn() -> bool, -) -> Result { - let started = Instant::now(); - let handle = uci::Engine::spawn_with(config, Box::new(|| {})) - .map_err(|e| JobFailure::Start(e.to_string()))?; - let mut probe = Probe { - name: handle.info().name.clone(), - answers: Vec::new(), - timed_out: false, - }; - if probe.name.as_deref() != Some(STOCKFISH_19) { - handle.quit(); - return Ok(probe); - } - let _ = handle.set_threads(1); - let _ = handle.set_hash_mb(SEARCH_HASH_MB); - let _ = handle.set_multipv(1); - let over = || halted() || started.elapsed() > limits.total; - for (i, fen) in PROBE_POSITIONS.iter().enumerate() { - let _ = handle.new_game(); - let pos = EnginePosition::fen(*fen, Vec::::new()); - let id = uci::SearchId(i as u64 + 1); - let search_started = Instant::now(); - let answer = search_once( - &handle, - &pos, - id, - Vec::new(), - PROBE_NODES, - limits.search, - &over, - )?; - if search_started.elapsed() > limits.search || started.elapsed() > limits.total { - probe.timed_out = true; - break; - } - let Some((info, best)) = answer else { break }; - let (Some(best), Some(score), Some(nodes)) = ( - best.or_else(|| info.pv.first().cloned()), - info.score, - info.nodes, - ) else { - break; - }; - probe.answers.push(ProbeAnswer { - best, - score: score.score, - nodes, - }); - } - handle.quit(); - Ok(probe) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn run(config: uci::EngineConfig) -> Result { - probe(config, ProbeLimits::default(), &|| false) - } - - fn fake() -> &'static str { - let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); - assert!( - std::path::Path::new(fake).exists(), - "build the fake engine first: cargo build -p uci --bin fake_uci" - ); - fake - } - - /// A fake engine answering every probe position as `answers` say. - fn engine(name: &str, answers: &[(&str, Score, u64)]) -> uci::EngineConfig { - let mut config = uci::EngineConfig::new(fake()); - config.args = vec!["--name".into(), name.into()]; - for (fen, (best, score, nodes)) in PROBE_POSITIONS.iter().zip(answers) { - let score = match score { - Score::Cp(cp) => format!("cp {cp}"), - Score::Mate(n) => format!("mate {n}"), - }; - let marker = fen.split(' ').next().unwrap_or_default(); - config.args.extend([ - "--answer".into(), - marker.into(), - format!("{score} nodes {nodes} pv {best}").into(), - ]); - } - config - } - - #[test] - fn the_reference_answers_pass() { - let p = run(engine(STOCKFISH_19, &REFERENCE)).expect("the probe runs"); - assert_eq!(p.name.as_deref(), Some(STOCKFISH_19)); - assert_eq!(p.answers.len(), 3); - assert!(p.same(), "{p:?}"); - } - - #[test] - fn other_answers_or_names_do_not() { - // Another network or version: one score differs. - let mut other = REFERENCE; - other[1].1 = Score::Cp(-117); - let p = run(engine(STOCKFISH_19, &other)).expect("the probe runs"); - assert!(!p.same()); - // The nodes differ (another search), the move and score the same. - let mut other = REFERENCE; - other[2].2 += 1; - assert!(!run(engine(STOCKFISH_19, &other)).unwrap().same()); - // Another best move. - let mut other = REFERENCE; - other[0].0 = "g8f6"; - assert!(!run(engine(STOCKFISH_19, &other)).unwrap().same()); - // The same answers under another name. - let p = run(engine("Stockfish 18", &REFERENCE)).unwrap(); - assert_eq!(p.name.as_deref(), Some("Stockfish 18")); - assert!(!p.same()); - // An engine that answers nothing of the kind (the fake's own lines). - let mut plain = uci::EngineConfig::new(fake()); - plain.args = vec!["--name".into(), STOCKFISH_19.into()]; - assert!(!run(plain).unwrap().same()); - } - - /// A real Stockfish 19 gives [`REFERENCE`] (run when the reference is taken again - /// or another build is checked): - /// `CP_PROBE_ENGINE=/path/to/stockfish cargo test -p game-review probe -- --ignored`. - #[test] - #[ignore = "needs a Stockfish 19 in CP_PROBE_ENGINE"] - fn a_real_stockfish_19_gives_the_reference() { - let path = std::env::var("CP_PROBE_ENGINE").expect("CP_PROBE_ENGINE"); - let p = run(uci::EngineConfig::new(path)).expect("the probe runs"); - println!("{p:?}"); - assert!(p.same(), "{p:?}"); - } - - /// An engine not called Stockfish 19 is not searched (Rodent searches on past - /// `go nodes`): its name is the verdict, at once. - #[test] - fn another_engine_is_not_searched() { - let mut config = uci::EngineConfig::new(fake()); - config.args = vec![ - "--name".into(), - "Rodent V 1.2".into(), - "--ignore-nodes".into(), - ]; - let started = Instant::now(); - let p = run(config).expect("the probe runs"); - assert_eq!(p.name.as_deref(), Some("Rodent V 1.2")); - assert!(p.answers.is_empty() && !p.timed_out && !p.same()); - assert!(started.elapsed() < Duration::from_secs(5)); - } - - /// A «Stockfish 19» that ignores `go nodes`: stopped by the guard, not the same. - #[test] - fn an_endless_search_is_cut_short() { - let mut config = uci::EngineConfig::new(fake()); - config.args = vec![ - "--name".into(), - STOCKFISH_19.into(), - "--ignore-nodes".into(), - ]; - let limits = ProbeLimits { - search: Duration::from_millis(300), - total: Duration::from_secs(2), - }; - let started = Instant::now(); - let p = probe(config, limits, &|| false).expect("the probe runs"); - assert!(p.timed_out && !p.same(), "{p:?}"); - assert!( - started.elapsed() < Duration::from_secs(5), - "{:?}", - started.elapsed() - ); - // Halted from outside (the program quits): at once. - let mut config = uci::EngineConfig::new(fake()); - config.args = vec![ - "--name".into(), - STOCKFISH_19.into(), - "--ignore-nodes".into(), - ]; - let started = Instant::now(); - let p = probe(config, ProbeLimits::default(), &|| true).expect("the probe runs"); - assert!(!p.same()); - assert!(started.elapsed() < Duration::from_secs(5)); - } - - #[test] - fn the_reference_key_is_stable() { - assert_eq!(reference_key(), reference_key()); - assert_eq!(reference_key().len(), 16); - } - - #[test] - fn an_engine_that_does_not_start_fails() { - assert!(matches!( - run(uci::EngineConfig::new("/nonexistent/engine")), - Err(JobFailure::Start(_)) - )); - } -} diff --git a/crates/game-review/src/job/work.rs b/crates/game-review/src/job/work.rs deleted file mode 100644 index bb1fb1a..0000000 --- a/crates/game-review/src/job/work.rs +++ /dev/null @@ -1,223 +0,0 @@ -//! What the job does for one target, as a machine without I/O: it names the next -//! search (the full one, the second best without the move played, the shallow ones) -//! and takes its answer; at the end it gives the target's [`JobEvent::Eval`]. Engine -//! processes on a computer and Web Workers in a browser drive the same machine, so the -//! evaluations — and the marks — are the same everywhere. - -use uci::{EnginePosition, SearchInfo, Side}; - -use super::{JobEvent, Target}; -use crate::{Eval, PosEval, Second, Shallow}; - -/// A search's answer: its last full line and the best move; `None` when it gave none. -pub(crate) type Answer = Option<(SearchInfo, Option)>; - -/// What the machine wants now. -pub(crate) enum Next { - /// A node-limited search of `pos` (among these moves only; empty: all), from a - /// clear hash. - Search { - pos: EnginePosition, - among: Vec, - nodes: u64, - }, - /// The target is done: its evaluation (`None`: the engine gave nothing to use). - Done(Option), -} - -enum Stage { - Full, - Second, - ShallowBest, - ShallowPlayed { best: String, best_eval: Eval }, - Finish, -} - -pub(crate) struct Work { - t: Target, - nodes: u64, - stage: Stage, - eval: Option, - nps: u64, - /// The move played, when it is the engine's best and worth a second search. - played: Option, -} - -impl Work { - pub(crate) fn new(t: Target, nodes: u64) -> Self { - let mut w = Work { - t, - nodes, - stage: Stage::Full, - eval: None, - nps: 0, - played: None, - }; - if let Some(e) = w.t.known.clone() { - w.got_eval(e, 0); - } - w - } - - fn eval_of(&self, info: &SearchInfo) -> Option { - info.score - .map(|s| Eval::from_white_eval(s.to_white(self.t.turn).eval)) - } - - /// The full evaluation is there: the second search, if it is worth one. - fn got_eval(&mut self, eval: PosEval, nps: u64) { - let t = &self.t; - // The move played is the engine's best: what the best of the others gives says - // whether it was the only good move, or a sacrifice when nothing else won. - let mover = match t.turn { - Side::White => chess_core::shakmaty::Color::White, - Side::Black => chess_core::shakmaty::Color::Black, - }; - self.played = t - .played - .as_ref() - .filter(|p| { - eval.pv.first() == Some(*p) - && !t.others.is_empty() - && crate::report::worth_second(eval.eval, mover) - }) - .cloned(); - let second_known = eval.second.as_ref().map(|s| &s.without) == self.played.as_ref(); - self.eval = Some(eval); - self.nps = nps; - self.stage = if self.played.is_some() && !second_known { - Stage::Second - } else { - Stage::ShallowBest - }; - if matches!(self.stage, Stage::ShallowBest) { - self.after_second(); - } - } - - /// The shallow search, when the rules want one and it is not there yet. - fn after_second(&mut self) { - let wanted = match (&self.played, self.t.shallow, &self.eval) { - (Some(played), Some(nodes), Some(eval)) => !eval - .shallow - .as_ref() - .is_some_and(|s| &s.played == played && s.nodes == nodes), - _ => false, - }; - self.stage = if wanted { - Stage::ShallowBest - } else { - Stage::Finish - }; - } - - pub(crate) fn next(&self) -> Next { - let t = &self.t; - match &self.stage { - Stage::Full => Next::Search { - pos: t.pos.clone(), - among: Vec::new(), - nodes: self.nodes, - }, - Stage::Second => Next::Search { - pos: t.pos.clone(), - among: t.others.clone(), - nodes: self.nodes, - }, - Stage::ShallowBest => Next::Search { - pos: t.pos.clone(), - among: Vec::new(), - nodes: t.shallow.unwrap_or_default(), - }, - Stage::ShallowPlayed { .. } => Next::Search { - pos: t.pos.clone(), - among: self.played.iter().cloned().collect(), - nodes: t.shallow.unwrap_or_default(), - }, - Stage::Finish => Next::Done(self.eval.clone().map(|eval| JobEvent::Eval { - key: t.key.clone(), - eval, - nps: self.nps, - })), - } - } - - /// The answer to the search [`Self::next`] asked for. - pub(crate) fn answer(&mut self, answer: Answer) { - match std::mem::replace(&mut self.stage, Stage::Finish) { - Stage::Full => { - let Some((info, best)) = answer else { return }; - let Some(score) = info.score else { return }; - let mut pv: Vec = info.pv.iter().take(12).cloned().collect(); - if let Some(b) = best - && pv.first() != Some(&b) - { - pv = vec![b]; - } - let eval = PosEval { - eval: Eval::from_white_eval(score.to_white(self.t.turn).eval), - pv, - depth: info.depth.unwrap_or(0), - second: None, - shallow: None, - }; - self.got_eval(eval, info.nps.unwrap_or(0)); - } - Stage::Second => { - let played = self.played.clone(); - // An engine that ignores `searchmoves` answers with the move played: no - // second move then. - if let Some((info, best)) = answer - && best.as_ref() != played.as_ref() - && info.pv.first() != played.as_ref() - && let (Some(score), Some(played), Some(eval)) = - (info.score, played, self.eval.as_mut()) - { - eval.second = Some(Second { - without: played, - eval: Eval::from_white_eval(score.to_white(self.t.turn).eval), - }); - } - self.after_second(); - } - Stage::ShallowBest => { - let Some((info, best)) = answer else { return }; - let (Some(best), Some(best_eval)) = ( - best.or_else(|| info.pv.first().cloned()), - self.eval_of(&info), - ) else { - return; - }; - if self.played.as_ref() == Some(&best) { - self.shallow(best, best_eval, best_eval); - } else { - self.stage = Stage::ShallowPlayed { best, best_eval }; - } - } - Stage::ShallowPlayed { best, best_eval } => { - if let Some((info, b)) = answer - && b.as_deref() - .is_none_or(|b| Some(b) == self.played.as_deref()) - && let Some(played_eval) = self.eval_of(&info) - { - self.shallow(best, best_eval, played_eval); - } - } - Stage::Finish => {} - } - } - - fn shallow(&mut self, best: String, best_eval: Eval, played_eval: Eval) { - if let (Some(eval), Some(played), Some(nodes)) = - (self.eval.as_mut(), self.played.clone(), self.t.shallow) - { - eval.shallow = Some(Shallow { - nodes, - played, - best, - best_eval, - played_eval, - }); - } - } -} diff --git a/crates/game-review/src/job/workers.rs b/crates/game-review/src/job/workers.rs deleted file mode 100644 index cb099f9..0000000 --- a/crates/game-review/src/job/workers.rs +++ /dev/null @@ -1,220 +0,0 @@ -//! The engine job in a browser: engines in Web Workers, each taking the next target, -//! driven from the page's frames by their messages — nothing here blocks. The search -//! of every target is the same machine as on a computer ([`super::work`]). - -use std::collections::HashSet; -use std::sync::Arc; -use std::time::Duration; - -use uci::{ - EngineEvent, EngineHandle, ScoreBound, SearchId, SearchInfo, SearchLimits, Starting, - WorkerConfig, -}; -use web_time::Instant; - -use super::work::{Next, Work}; -use super::{JobEvent, JobFailure, JobSettings, MAX_PROCESSES, SEARCH_HASH_MB, Target}; - -/// A node-limited search should never take this long; stop it if it does. -const SEARCH_GUARD: Duration = Duration::from_secs(300); - -/// How long an engine may take to start: a worker compiles the whole engine (≈ 100 MB -/// of WebAssembly), several at once. -const START_TIMEOUT: Duration = Duration::from_secs(120); - -enum Engine { - Starting(Starting), - Ready(EngineHandle), - Done, -} - -struct Running { - id: SearchId, - last: Option, - started: Instant, - stopping: bool, -} - -struct Slot { - engine: Engine, - work: Option, - search: Option, - next_id: u64, -} - -/// The job: started by [`Dispatcher::start`], driven by [`Dispatcher::poll`]. -pub struct Dispatcher { - slots: Vec, - targets: std::vec::IntoIter, - nodes: u64, - names: HashSet, - events: Vec, - failure: Option, - halted: bool, -} - -impl Dispatcher { - /// Starts `settings.processes` engines of the worker script `script`; `wake` is - /// called whenever one of them has something new. - pub fn start( - script: &str, - settings: &JobSettings, - targets: Vec, - wake: Arc, - ) -> Result { - let workers = settings - .processes - .clamp(1, MAX_PROCESSES) - .min(targets.len().max(1)); - let mut slots = Vec::with_capacity(workers); - if !targets.is_empty() { - for _ in 0..workers { - let mut config = WorkerConfig::new(script); - config.timeouts.uciok = START_TIMEOUT; - config.timeouts.readyok = START_TIMEOUT; - let wake = wake.clone(); - let starting = uci::Engine::start_worker(config, Box::new(move || wake())) - .map_err(|e| JobFailure::Start(e.to_string()))?; - slots.push(Slot { - engine: Engine::Starting(starting), - work: None, - search: None, - next_id: 0, - }); - } - } - Ok(Dispatcher { - slots, - targets: targets.into_iter(), - nodes: settings.nodes, - names: HashSet::new(), - events: Vec::new(), - failure: None, - halted: false, - }) - } - - /// Stops the job: the engines are stopped, what came stays. - pub fn cancel(&mut self) { - self.halted = true; - for s in &mut self.slots { - s.engine = Engine::Done; - } - } - - /// What came since the last call, and the end once the job is over (`Ok` also when - /// cancelled). Call it every frame and when woken. - pub fn poll(&mut self) -> (Vec, Option>) { - for i in 0..self.slots.len() { - if let Err(e) = self.step(i) { - self.failure.get_or_insert(e); - self.cancel(); - } - } - let events = std::mem::take(&mut self.events); - let over = self.slots.iter().all(|s| matches!(s.engine, Engine::Done)); - let end = over.then(|| match self.failure.take() { - Some(e) => Err(e), - None => Ok(()), - }); - (events, end) - } - - fn step(&mut self, i: usize) -> Result<(), JobFailure> { - let slot = &mut self.slots[i]; - if let Engine::Starting(s) = &mut slot.engine { - match s.poll() { - None => return Ok(()), - Some(Err(e)) => return Err(JobFailure::Start(e.to_string())), - Some(Ok(h)) => { - // Unknown options are not fatal: some engines lack Threads/Hash/MultiPV. - let _ = h.set_threads(1); - let _ = h.set_hash_mb(SEARCH_HASH_MB); - let _ = h.set_multipv(1); - if let Some(name) = &h.info().name - && self.names.insert(name.clone()) - { - self.events.push(JobEvent::Engine(name.clone())); - } - slot.engine = Engine::Ready(h); - } - } - } - let Engine::Ready(h) = &slot.engine else { - return Ok(()); - }; - // The answer of the running search, once it is there. - let mut answer = None; - for ev in h.drain_events() { - let Some(run) = slot.search.as_mut() else { - continue; - }; - match ev { - EngineEvent::Info { search_id, info } if search_id == run.id => { - if info.multipv_index() == 1 && info.score.is_some() { - let exact = info.score.is_some_and(|s| s.bound == ScoreBound::Exact); - if exact || run.last.is_none() { - run.last = Some(info); - } - } - } - EngineEvent::BestMove { - search_id, best, .. - } if search_id == run.id => { - let last = run.last.take(); - answer = Some(last.map(|info| (info, best))); - slot.search = None; - } - EngineEvent::Terminated(reason) => return Err(JobFailure::Terminated(reason)), - _ => {} - } - } - if let Some(run) = slot.search.as_mut() { - if !run.stopping && run.started.elapsed() > SEARCH_GUARD { - let _ = h.stop(); - run.stopping = true; - } - return Ok(()); - } - if let (Some(answer), Some(work)) = (answer, slot.work.as_mut()) { - work.answer(answer); - } - // The next search: of this target, or of the next one. - loop { - if slot.work.is_none() { - match self.targets.next().filter(|_| !self.halted) { - Some(t) => slot.work = Some(Work::new(t, self.nodes)), - None => { - slot.engine = Engine::Done; - return Ok(()); - } - } - } - let Some(work) = slot.work.as_ref() else { - continue; - }; - match work.next() { - Next::Search { pos, among, nodes } => { - slot.next_id += 1; - let id = SearchId(slot.next_id); - // Every search starts from a clear hash, so that it depends on its - // position alone. - let _ = h.new_game(); - h.search_among(pos, id, SearchLimits::Nodes(nodes), among) - .map_err(|e| JobFailure::Engine(e.to_string()))?; - slot.search = Some(Running { - id, - last: None, - started: Instant::now(), - stopping: false, - }); - return Ok(()); - } - Next::Done(event) => { - self.events.extend(event); - slot.work = None; - } - } - } - } -} diff --git a/crates/game-review/src/lib.rs b/crates/game-review/src/lib.rs index 76a2497..9af96f9 100644 --- a/crates/game-review/src/lib.rs +++ b/crates/game-review/src/lib.rs @@ -8,7 +8,7 @@ //! are used without an engine. use std::collections::HashMap; -use std::path::Path; +use std::path::{Path, PathBuf}; use chess_core::shakmaty::san::SanPlus; use chess_core::shakmaty::uci::UciMove; @@ -22,17 +22,8 @@ mod job; pub mod report; pub use features::{MoveFeatures, Rules}; -#[cfg(target_family = "wasm")] -pub use job::Dispatcher; -pub use job::{ - JobEvent, JobFailure, JobSettings, MAX_PROCESSES, PHONE_PROCESSES, SEARCH_HASH_MB, - SEARCH_NODES, SEARCH_VERSION, SHALLOW_NODES, Target, estimate_secs, processes, -}; -#[cfg(not(target_family = "wasm"))] -pub use job::{probe, run}; -pub use report::{ - Eval, Hardness, Judgement, Measure, Phase, Phases, Ply, Report, SideStats, judge, -}; +pub use job::{JobEvent, JobFailure, JobSettings, Target, run}; +pub use report::{Eval, Judgement, Phase, Phases, Ply, Report, SideStats}; /// Engine result for one position of the main line. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -47,26 +38,6 @@ pub struct PosEval { /// be brilliant or great (older analyses have none). #[serde(default, skip_serializing_if = "Option::is_none")] pub second: Option, - /// What a shallow search makes of the move played, for how hard it was to find - /// (when the rules ask for it, see [`Hardness`]; older analyses have none). - #[serde(default, skip_serializing_if = "Option::is_none")] - pub shallow: Option, -} - -/// The shallow search of a position whose move could be brilliant or great and was the -/// engine's best: the same fixed search as every other, to `nodes` nodes only. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Shallow { - /// Nodes of the search ([`SHALLOW_NODES`] in the programs). - pub nodes: u64, - /// The move played (UCI), as [`Second::without`]. - pub played: String, - /// The shallow search's best move (UCI) and its evaluation. - pub best: String, - pub best_eval: Eval, - /// The move played at the same nodes: `best_eval` when it is `best`, else a search - /// of the move played alone. - pub played_eval: Eval, } /// The best of the other moves: how the position stood without the move played. @@ -83,28 +54,6 @@ pub struct ReviewMeta { pub engine: String, /// Nodes per position; 0 = read from `[%eval]` comments of the PGN. pub nodes: u64, - /// The version of the fixed search the engine made ([`SEARCH_VERSION`]); 0 for an - /// analysis from before it, whose user-chosen engine settings gave other results. - #[serde(default)] - pub search: u32, -} - -impl ReviewMeta { - /// Evaluations of the fixed search of today (see [`run`]); the engine's name comes - /// with the job's [`JobEvent::Engine`]. - pub fn fixed_search() -> ReviewMeta { - ReviewMeta { - engine: String::new(), - nodes: SEARCH_NODES, - search: SEARCH_VERSION, - } - } - - /// Engine evaluations of another search than today's: shown, but never completed - /// with new ones — an update makes them all again. - pub fn is_stale(&self) -> bool { - self.nodes > 0 && self.search != SEARCH_VERSION - } } #[derive(Serialize, Deserialize)] @@ -153,30 +102,6 @@ pub struct GameAnalysis { pub marks: HashMap, /// The rules of !! and ! the report follows. rules: Rules, - /// How the difficulty of a move counts in them. - hardness: Hardness, - /// Nodes of the shallow search ([`SHALLOW_NODES`]; another only in an experiment). - shallow_nodes: u64, -} - -/// Where cached analyses are kept, one file per main line by name: a folder (`Path`), -/// or whatever else a program keeps files in (the web version's browser storage). -pub trait CacheStore { - fn read(&self, name: &str) -> Option>; - fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()>; -} - -/// The cache in a folder of the disk. -pub struct CacheDir<'a>(pub &'a Path); - -impl CacheStore for CacheDir<'_> { - fn read(&self, name: &str) -> Option> { - std::fs::read(self.0.join(name)).ok() - } - - fn write(&self, name: &str, bytes: &[u8]) -> std::io::Result<()> { - write_atomic(&self.0.join(name), bytes) - } } impl GameAnalysis { @@ -184,12 +109,6 @@ impl GameAnalysis { /// analyses) when this main line was analysed before, else from `[%eval]` comments /// when every move has one, else empty. pub fn new(game: &Game, cache_dir: Option<&Path>) -> Self { - let dir = cache_dir.map(CacheDir); - Self::with_store(game, dir.as_ref().map(|d| d as &dyn CacheStore)) - } - - /// [`Self::new`] with the cache in `store`. - pub fn with_store(game: &Game, store: Option<&dyn CacheStore>) -> Self { let mut a = GameAnalysis { evals: HashMap::new(), meta: None, @@ -205,11 +124,9 @@ impl GameAnalysis { report: Report::default(), marks: HashMap::new(), rules: Rules::default(), - hardness: Hardness::default(), - shallow_nodes: SHALLOW_NODES, }; a.rebuild(game); - if store.is_some_and(|s| a.load_cache(s)) || a.load_pgn_evals(game) { + if cache_dir.is_some_and(|d| a.load_cache(d)) || a.load_pgn_evals(game) { a.rebuild(game); } a @@ -219,12 +136,6 @@ impl GameAnalysis { !self.evals.is_empty() } - /// The evaluations come from another engine search than today's fixed one (an - /// analysis made before it): shown as they are until an update makes them again. - pub fn stale(&self) -> bool { - self.has_data() && self.meta.as_ref().is_some_and(ReviewMeta::is_stale) - } - /// Root and main-line nodes, in order: index `i` of [`Self::values`] belongs here. pub fn line(&self) -> &[NodeId] { &self.line @@ -264,7 +175,7 @@ impl GameAnalysis { .features .iter() .flatten() - .filter(|f| f.candidate(self.hardness.bans)) + .filter(|f| f.candidate()) .count(); self.positions() + candidates / 2 } @@ -278,25 +189,6 @@ impl GameAnalysis { } } - /// Counts the difficulty of a move as `hardness` says from the next - /// [`Self::refresh`] on; when it asks for it, [`Self::begin`] wants the shallow - /// searches. - pub fn set_hardness(&mut self, hardness: Hardness) { - if self.hardness != hardness { - self.hardness = hardness; - self.dirty = true; - } - } - - /// Shallow searches of `nodes` instead of [`SHALLOW_NODES`]: only for an experiment - /// (choosing the nodes); those of other nodes are made again. - pub fn set_shallow_nodes(&mut self, nodes: u64) { - if self.shallow_nodes != nodes { - self.shallow_nodes = nodes; - self.dirty = true; - } - } - /// Re-derives the report when the game or the evaluations changed. Cheap otherwise. pub fn refresh(&mut self, game: &Game) { if self.dirty || self.built_rev != Some(game.revision()) { @@ -304,32 +196,25 @@ impl GameAnalysis { } } - /// Prepares an engine run of the fixed search: `full` drops the earlier results, and - /// so does an analysis of another search ([`Self::stale`]), so that one report never - /// mixes two. Returns the positions without an evaluation, for [`run`]. - pub fn begin(&mut self, game: &Game, full: bool) -> Vec { - // Evaluations read from the PGN are no engine analysis to fill in: the engine - // analyses the whole game (else they would pass for the fixed search). - let from_pgn = self.meta.as_ref().is_some_and(|m| m.nodes == 0); - if full || from_pgn || self.stale() { + /// Prepares an engine run: `full` drops the earlier results. Returns the positions + /// without an evaluation, for [`run`]. Filling in an engine analysis keeps its + /// nodes per position, so that one report never mixes two qualities: the run must use + /// `self.meta`'s nodes, not the asked ones. + pub fn begin(&mut self, game: &Game, meta: ReviewMeta, full: bool) -> Vec { + if full { self.evals.clear(); } - let engine = self - .meta - .take() - .filter(|m| !m.is_stale() && m.nodes > 0) - .map(|m| m.engine) - .unwrap_or_default(); - self.meta = Some(ReviewMeta { - engine, - ..ReviewMeta::fixed_search() - }); + let nodes = match &self.meta { + Some(old) if !full && old.nodes > 0 && self.has_data() => old.nodes, + _ => meta.nodes, + }; + self.meta = Some(ReviewMeta { nodes, ..meta }); self.rebuild(game); (0..self.line.len()) .filter_map(|i| { let known = self.evals.get(&self.keys[i]).cloned(); - // Already evaluated: only the second or shallow search can be left. - if known.is_some() && !self.extra_missing(i) + // Already evaluated: only a missing second search can be left. + if known.is_some() && !self.second_missing(i) || known.is_none() && self.values[i].is_some() { return None; @@ -341,7 +226,7 @@ impl GameAnalysis { .get(i) .copied() .flatten() - .filter(|f| f.candidate(self.hardness.bans)) + .filter(|f| f.candidate()) .and_then(|_| self.played.get(i).cloned().flatten()); let others = match &played { Some(p) => here @@ -364,7 +249,6 @@ impl GameAnalysis { played, others, known, - shallow: self.hardness.uses_shallow().then_some(self.shallow_nodes), }) }) .collect() @@ -372,8 +256,8 @@ impl GameAnalysis { /// Position `i` is evaluated, its move could be brilliant or great and was the /// engine's best, but the best other move was never searched for (an analysis from - /// before !! and !), or the shallow search the rules ask for was not made. - fn extra_missing(&self, i: usize) -> bool { + /// before !! and !). + fn second_missing(&self, i: usize) -> bool { let (Some(e), Some(Some(played)), Some(Some(f))) = ( self.evals.get(&self.keys[i]), self.played.get(i), @@ -381,32 +265,21 @@ impl GameAnalysis { ) else { return false; }; - let shallow_missing = || { - self.hardness.uses_shallow() - && !e - .shallow - .as_ref() - .is_some_and(|s| &s.played == played && s.nodes == self.shallow_nodes) - }; - f.candidate(self.hardness.bans) + f.candidate() && e.pv.first() == Some(played) && report::worth_second(e.eval, self.movers[i]) - && (e.second.as_ref().map(|s| &s.without) != Some(played) || shallow_missing()) + && e.second.as_ref().map(|s| &s.without) != Some(played) } - /// Positions whose evaluation is there but which still want the second (or shallow) - /// search of !! and ! ("Update" fills them in without evaluating anything again). - /// None for evaluations from the PGN, which have no engine lines. + /// Positions whose evaluation is there but which still want the second search of + /// !! and ! ("Update" fills them in without evaluating anything again). None for + /// evaluations from the PGN, which have no engine lines. pub fn seconds_missing(&self) -> usize { - if self - .meta - .as_ref() - .is_none_or(|m| m.nodes == 0 || m.is_stale()) - { + if self.meta.as_ref().is_none_or(|m| m.nodes == 0) { return 0; } (0..self.played.len()) - .filter(|i| self.extra_missing(*i)) + .filter(|i| self.second_missing(*i)) .count() } @@ -460,8 +333,7 @@ impl GameAnalysis { .map(|i| { let (m, before) = (moves[i].as_ref()?, positions.get(i)?); let prev = i.checked_sub(1).and_then(|p| moves[p].as_ref()); - let own = i.checked_sub(2).and_then(|p| moves[p].as_ref()); - Some(MoveFeatures::of(before, m, prev, own)) + Some(MoveFeatures::of(before, m, prev)) }) .collect(); self.played = (1..self.line.len()) @@ -483,27 +355,11 @@ impl GameAnalysis { .and_then(|e| e.second.as_ref()) .filter(|s| Some(&s.without) == played.as_ref()) .map(|s| s.eval), - difficulty: e - .and_then(|e| Some((e.eval, e.shallow.as_ref()?))) - .filter(|(_, s)| { - Some(&s.played) == played.as_ref() && s.nodes == self.shallow_nodes - }) - .zip(positions.get(i - 1)) - .map(|((deep, s), p)| { - self.hardness - .measure - .difficulty(deep, s.best_eval, s.played_eval, p.turn()) - }), }); } self.movers = plies.iter().map(|p| p.mover).collect(); - self.report = Report::build_tuned( - &self.values, - &plies, - Phases::divide(&positions), - self.rules, - self.hardness, - ); + self.report = + Report::build_with(&self.values, &plies, Phases::divide(&positions), self.rules); self.marks.clear(); for (i, j) in self.report.judgements.iter().enumerate() { let Some(judgement) = *j else { continue }; @@ -584,14 +440,8 @@ impl GameAnalysis { // ----- cache ----------------------------------------------------------------- - /// The name of the cache file of this main line. - /// The name of this main line's file in the cache: equal for equal main lines (the - /// same positions), whatever the rest of the game. - pub fn cache_key(&self) -> String { - self.cache_name() - } - - fn cache_name(&self) -> String { + /// The cache file of this main line in `dir`. + fn cache_path(&self, dir: &Path) -> PathBuf { let mut h: u64 = 0xcbf2_9ce4_8422_2325; for k in &self.keys { for b in k.bytes().chain(std::iter::once(b'\n')) { @@ -599,16 +449,11 @@ impl GameAnalysis { h = h.wrapping_mul(0x0100_0000_01b3); } } - format!("{h:016x}.json") + dir.join(format!("{h:016x}.json")) } /// Keeps engine results in `dir` (nothing for evaluations read from the PGN). pub fn save_cache(&self, dir: &Path) -> std::io::Result<()> { - self.save_to(&CacheDir(dir)) - } - - /// Keeps engine results in `store` (nothing for evaluations read from the PGN). - pub fn save_to(&self, store: &dyn CacheStore) -> std::io::Result<()> { let Some(meta) = self.meta.clone().filter(|m| m.nodes > 0) else { return Ok(()); }; @@ -627,11 +472,11 @@ impl GameAnalysis { .collect(), }; let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?; - store.write(&self.cache_name(), &bytes) + write_atomic(&self.cache_path(dir), &bytes) } - fn load_cache(&mut self, store: &dyn CacheStore) -> bool { - let Some(bytes) = store.read(&self.cache_name()) else { + fn load_cache(&mut self, dir: &Path) -> bool { + let Ok(bytes) = std::fs::read(self.cache_path(dir)) else { return false; }; let Ok(file) = serde_json::from_slice::(&bytes) else { @@ -689,14 +534,12 @@ impl GameAnalysis { pv: Vec::new(), depth: 0, second: None, - shallow: None, }, ); } self.meta = Some(ReviewMeta { engine: "PGN".into(), nodes: 0, - search: 0, }); true } @@ -717,9 +560,8 @@ fn position_key(game: &Game, id: NodeId) -> Option<(String, EnginePosition)> { Some((key, pos)) } -/// Evaluation of a position without legal moves (checkmate or stalemate): no engine -/// is needed for it. -pub fn terminal_eval(pos: &Chess) -> Option { +/// Evaluation of a position without legal moves. +fn terminal_eval(pos: &Chess) -> Option { if pos.is_checkmate() { Some(Eval::Mate { white: pos.turn() == Color::Black, @@ -796,8 +638,19 @@ mod tests { assert_eq!(s.values()[1], Some(Eval::Cp(0))); } - /// Fake engine results for `targets`: the evaluations fall by 3 pawns a move. - fn fake_results(a: &mut GameAnalysis, targets: Vec) { + #[test] + fn engine_results_are_cached_per_main_line() { + let dir = std::env::temp_dir().join(format!("game-review-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let g = game("1. e4 e5 2. Nf3 *"); + let mut a = GameAnalysis::new(&g, Some(&dir)); + assert!(!a.has_data()); + let meta = ReviewMeta { + engine: "Fake".into(), + nodes: 1000, + }; + let targets = a.begin(&g, meta.clone(), false); + assert_eq!(targets.len(), 4); for (i, t) in targets.into_iter().enumerate() { a.apply(JobEvent::Eval { key: t.key, @@ -806,53 +659,59 @@ mod tests { pv: vec!["e2e4".into()], depth: 10, second: None, - shallow: None, }, nps: 0, }); } - } - - #[test] - fn engine_results_are_cached_per_main_line() { - let dir = std::env::temp_dir().join(format!("game-review-test-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let g = game("1. e4 e5 2. Nf3 *"); - let mut a = GameAnalysis::new(&g, Some(&dir)); - assert!(!a.has_data()); - let targets = a.begin(&g, false); - assert_eq!(targets.len(), 4); - a.apply(JobEvent::Engine("Fake".into())); - fake_results(&mut a, targets); a.refresh(&g); assert_eq!(a.missing(), 0); a.save_cache(&dir).expect("saved"); let b = GameAnalysis::new(&g, Some(&dir)); - let fixed = ReviewMeta { - engine: "Fake".into(), - ..ReviewMeta::fixed_search() - }; - assert_eq!(b.meta, Some(fixed.clone())); - assert!(!b.stale()); + assert_eq!(b.meta, Some(meta)); assert_eq!(b.values(), a.values()); // 1.e4 was the engine's own move: never an error, whatever the evaluations say. assert!(!b.marks.contains_key(&g.mainline()[0])); // Another main line has its own file. assert!(!GameAnalysis::new(&game("1. d4 *"), Some(&dir)).has_data()); - // Nothing left to evaluate; 1.e4, the engine's best, still wants the best other - // move (an analysis from before !! and !): filling in searches only that. + // Filling in keeps the quality of the first run. let mut c = GameAnalysis::new(&g, Some(&dir)); + let fast = ReviewMeta { + engine: "Fake".into(), + nodes: 250, + }; + // Nothing left to evaluate; 1.e4, the engine's best, still wants the best other + // move (an analysis from before !! and !). assert_eq!(c.seconds_missing(), 1); - let left = c.begin(&g, false); + let left = c.begin(&g, fast.clone(), false); assert_eq!(left.len(), 1); assert!(left[0].known.is_some() && left[0].played.as_deref() == Some("e2e4")); assert!(!left[0].others.is_empty() && !left[0].others.contains(&"e2e4".to_string())); - assert_eq!(c.meta, Some(fixed)); + assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(1000)); + c.begin(&g, fast, true); + assert_eq!(c.meta.as_ref().map(|m| m.nodes), Some(250)); // A game without moves is never cached. let empty = game("*"); let mut e = GameAnalysis::new(&empty, Some(&dir)); - let t = e.begin(&empty, false); - fake_results(&mut e, t); + let t = e.begin( + &empty, + ReviewMeta { + engine: "Fake".into(), + nodes: 1000, + }, + false, + ); + for t in t { + e.apply(JobEvent::Eval { + key: t.key, + eval: PosEval { + eval: Eval::Cp(20), + pv: vec![], + depth: 1, + second: None, + }, + nps: 0, + }); + } e.save_cache(&dir).expect("nothing to save is fine"); assert!( !GameAnalysis::new( @@ -864,43 +723,4 @@ mod tests { assert!(!GameAnalysis::new(&empty, Some(&dir)).has_data()); let _ = std::fs::remove_dir_all(&dir); } - - /// An analysis cached before the fixed search (its meta without `search`, the nodes - /// the user chose) is shown, but stale: an update makes every evaluation again. - #[test] - fn an_analysis_of_another_search_is_stale() { - let dir = std::env::temp_dir().join(format!("game-review-stale-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let g = game("1. e4 e5 2. Nf3 *"); - let mut a = GameAnalysis::new(&g, None); - let targets = a.begin(&g, false); - fake_results(&mut a, targets); - a.refresh(&g); - let path = dir.join(a.cache_name()); - a.save_cache(&dir).expect("saved"); - // The file as 1.x wrote it: no `search` in the meta, 3M nodes. - let mut json: serde_json::Value = - serde_json::from_slice(&std::fs::read(&path).expect("cache")).expect("json"); - let meta = json["meta"].as_object_mut().expect("meta"); - meta.remove("search"); - meta.insert("nodes".into(), 3_000_000.into()); - meta.insert("engine".into(), "Stockfish 17".into()); - std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written"); - - let mut old = GameAnalysis::new(&g, Some(&dir)); - assert!(old.has_data() && old.stale()); - assert_eq!(old.meta.as_ref().map(|m| m.search), Some(0)); - assert_eq!(old.missing(), 0); - assert!(old.report.complete, "the old report is still shown"); - assert_eq!(old.seconds_missing(), 0, "not filled in: made again"); - let targets = old.begin(&g, false); - assert_eq!(targets.len(), 4, "every position again"); - assert!(targets.iter().all(|t| t.known.is_none())); - assert!(!old.has_data() && !old.stale()); - assert_eq!(old.meta, Some(ReviewMeta::fixed_search())); - // Evaluations of the PGN are not an engine search: never stale. - let pgn = game("1. e4 {[%eval 0.3]} e5 {[%eval 0.32]} *"); - assert!(!GameAnalysis::new(&pgn, None).stale()); - let _ = std::fs::remove_dir_all(&dir); - } } diff --git a/crates/game-review/src/report.rs b/crates/game-review/src/report.rs index 543aa8b..e797627 100644 --- a/crates/game-review/src/report.rs +++ b/crates/game-review/src/report.rs @@ -114,7 +114,7 @@ fn move_accuracy(before: f64, after: f64) -> f64 { (raw + 1.0).clamp(0.0, 100.0) } -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Judgement { Inaccuracy, Mistake, @@ -141,20 +141,13 @@ mod good { pub const NEAR_BEST: f64 = 2.0; /// !!: the position after the sacrifice is at least this good. pub const SOUND_AFTER: f64 = 45.0; - /// !! ([`Rules::Strict`]): without the move the game was not won anyway. + /// !!: without the move the game was not won anyway. pub const WON_ANYWAY: f64 = 90.0; /// !: every other move loses at least this much. pub const GAP: f64 = 10.0; - /// [`Rules::ChessCom`]: stricter — the owner wants few ! and right ones (2026-10-28): - /// with 25 the check set's ! are chess.com's 87 % of the time (54 % of theirs found). - pub const GAP_CHESSCOM: f64 = 25.0; /// !: the position after the move is not lost, and the best other move did not win. pub const GREAT_AFTER: f64 = 40.0; pub const GREAT_ALT: f64 = 75.0; - /// [`Rules::ChessCom`]: nor keep a clear edge. chess.com's ! in the check set - /// (`chesscom/`, 2026-10-28) all have the best other move at 59 % or less; above it - /// it gives none (18.Nd4, 23.Rf7+, 25.Rxh7+ of Steinitz — von Bardeleben). - pub const GREAT_ALT_CHESSCOM: f64 = 60.0; /// [`Rules::Strict`]: lost below, won above; a great move changes which. pub const LOST: f64 = 33.0; pub const WON: f64 = 67.0; @@ -166,78 +159,6 @@ mod good { pub const SECOND_FROM: f64 = GREAT_AFTER - NEAR_BEST; } -/// How hard a move is to find, in the mover's win %, from a shallow search -/// ([`crate::SHALLOW_NODES`]) of the engine's own best move. A move the strong search -/// plays and a weak one underrates is what people call brilliant (Zaidi & Guerzhoy 2024, -/// arXiv 2406.11895); an obvious only move (10.Be2 of an online game, 32.Kd2 of Tal — -/// Larsen) the shallow search finds too. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum Measure { - /// How much worse than its own best move the shallow search finds the move played - /// (0 when it finds this move best). - #[default] - Choice, - /// How much worse the shallow search finds the move played than the deep one. - Depth, -} - -impl Measure { - /// The difficulty of a move the deep search finds `deep`, the shallow search - /// `played` and its own best move `best`. - pub fn difficulty(self, deep: Eval, best: Eval, played: Eval, mover: Color) -> f64 { - let top = match self { - Measure::Choice => best, - Measure::Depth => deep, - }; - (top.win_percent(mover) - played.win_percent(mover)).max(0.0) - } -} - -/// The say of a move's difficulty ([`Measure`]) in !! and ! ([`Rules::ChessCom`] only), -/// being tried out (2026-10-29) and off by default: the default is the rules without it, -/// and no shallow search is made for them. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Hardness { - /// !: only a move at least this hard to find (win %). - pub great: Option, - /// !: every other move loses at least this much (win %). - pub gap: f64, - /// !: never a capture nor an attacked piece stepping quietly away (the rules of - /// 2026-10-28 and 2026-10-29 against obvious !). - pub bans: bool, - /// !!: also the only good move (as for !, with [`Self::brilliant_gap`]) at least this - /// hard to find, sacrifice or not (in the check set at 5 000 nodes: 17…Be6!! of - /// Byrne — Fischer, 33.c3+!! of Kasparov — Topalov). - pub brilliant: Option, - /// !! of a hard move: every other move loses at least this much (win %). - pub brilliant_gap: f64, - /// How the difficulty is measured. - pub measure: Measure, -} - -impl Default for Hardness { - fn default() -> Hardness { - Hardness { - great: None, - gap: good::GAP_CHESSCOM, - bans: true, - // On by the owner's word (2026-10-29): +2 !! of chess.com's in the check set - // (90 % found, 95 % right), no wrong one added; the same over 2 000–5 000 - // nodes and thresholds 20–40 %. - brilliant: Some(30.0), - brilliant_gap: 10.0, - measure: Measure::Choice, - } - } -} - -impl Hardness { - /// The rules ask how hard a move was to find: the shallow search is wanted. - pub fn uses_shallow(&self) -> bool { - self.great.is_some() || self.brilliant.is_some() - } -} - /// Whether the best other move is worth searching for: the move played was the engine's /// best (`eval` the position's evaluation), and the position is good enough for !! or !. pub fn worth_second(eval: Eval, mover: Color) -> bool { @@ -257,101 +178,33 @@ fn outcome(win: f64) -> u8 { /// Brilliant or great, from the evaluations around the move (before the combination rule /// of [`Rules::Strict`]). -fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules, hard: Hardness) -> Option { +fn note(before: Eval, after: Eval, ply: &Ply, rules: Rules) -> Option { let f = ply.features?; let (wb, wa) = (before.win_percent(ply.mover), after.win_percent(ply.mover)); let loss = wb - wa; let second = ply.second.map(|e| e.win_percent(ply.mover)); // Without the move: the best other move, or the best move when another was played. let without = if ply.best { second } else { Some(wb) }; - // With [`Rules::ChessCom`] a sacrifice that mates sooner than any other move was not - // won anyway: 22.Qf6+!! of the Immortal game mates in 2, 22.Qf7 only in 4 (chess.com - // marks it; win % cannot tell the two apart). - let mates_sooner = rules == Rules::ChessCom - && ply.best - && ply - .second - .is_some_and(|s| mates_sooner(after, s, ply.mover)); - // Won anyway without the move: [`Rules::Strict`] by win %, [`Rules::ChessCom`] only - // with a forced mate there — every sacrifice of the check set whose best other move - // still won (to 93 %) is chess.com's !! (23…Qg3 of Levitsky — Marshall, 22…Rxc3 of - // Rotlewi — Rubinstein). - let without_eval = if ply.best { ply.second } else { Some(before) }; - let won_anyway = match rules { - Rules::Strict => without.is_none_or(|w| w >= good::WON_ANYWAY), - Rules::ChessCom => without_eval.is_none_or(|e| e.mate_for(ply.mover) == Some(true)), - }; if f.brilliant_shape(rules) && (ply.best || loss <= good::NEAR_BEST) && wa >= good::SOUND_AFTER - && (!won_anyway || mates_sooner) + && without.is_some_and(|w| w < good::WON_ANYWAY) { return Some(Judgement::Brilliant); } - if f.pawn_shape(rules) && mates_sooner { - return Some(Judgement::Brilliant); - } let w2 = second?; - let bans = rules == Rules::Strict || hard.bans; - // [`Rules::ChessCom`]: a capture is the natural move, never great (12…Nxc3, 13…Nxe4 of - // Byrne — Fischer, 22…Nbxd5, 26.Qxd4+ of Kasparov — Topalov are not chess.com's !; the - // few captures it marks — 20.Rxe7+, 18.fxe6 — are given up for fewer wrong ones). - if rules == Rules::ChessCom && bans && f.capture { - return None; - } - // The engine's own best move loses nothing: a drop to the next position is the noise - // of two searches (9.Nf5! of the Immortal game, −0.51 then −0.82 at 3M nodes); the - // first rules still count it. - let only_move = |gap: f64| { - ply.best - && (rules == Rules::ChessCom || loss <= good::NEAR_BEST) - && wb - w2 >= gap - && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) - && wa >= good::GREAT_AFTER - && w2 - < match rules { - Rules::Strict => good::GREAT_ALT, - Rules::ChessCom => good::GREAT_ALT_CHESSCOM, - } - }; - // Tried and dropped (2026-10-28): a pawn offered as the only good move brilliant too — - // finds 33.c3+!! of Kasparov — Topalov, but also marks 17.d5 of Steinitz — von - // Bardeleben, which chess.com leaves unmarked. - if !f.great_shape(rules, bans) { - return None; - } - if rules == Rules::Strict { - return only_move(good::GAP).then_some(Judgement::Great); - } - // How hard the move was to find: unknown (no shallow search) is not hard. - let at_least = |t: Option| t.is_some_and(|t| ply.difficulty.is_some_and(|d| d >= t)); - if at_least(hard.brilliant) && only_move(hard.brilliant_gap) { - Some(Judgement::Brilliant) - } else if only_move(hard.gap) && (hard.great.is_none() || at_least(hard.great)) { - Some(Judgement::Great) - } else { - None - } + (f.great_shape(rules) + && ply.best + && loss <= good::NEAR_BEST + && wb - w2 >= good::GAP + && (rules == Rules::ChessCom || outcome(wa) > outcome(w2)) + && wa >= good::GREAT_AFTER + && w2 < good::GREAT_ALT) + .then_some(Judgement::Great) } -/// `after` (the move played) mates `mover`'s opponent in fewer moves than `other` (the -/// best other move), or `other` does not mate at all. -fn mates_sooner(after: Eval, other: Eval, mover: Color) -> bool { - let mine = |e: Eval| match e { - Eval::Mate { white, moves } if white == (mover == Color::White) => Some(moves), - _ => None, - }; - match (mine(after), mine(other)) { - (Some(a), Some(o)) => a < o, - (Some(_), None) => true, - _ => false, - } -} - -/// Judgement of a move from the evaluations before and after it: an inaccuracy, a -/// mistake or a blunder by the drop of the mover's winning chances (never for the -/// engine's own best move: the caller rules that out). -pub fn judge(before: Eval, after: Eval, mover: Color) -> Option { +/// Judgement of a move from the evaluations before and after it. +fn judge(before: Eval, after: Eval, mover: Color) -> Option { use Judgement::*; let (mb, ma) = (before.mate_for(mover), after.mate_for(mover)); if ma == Some(false) && mb != Some(false) { @@ -456,9 +309,6 @@ pub struct Ply { pub features: Option, /// The best other move's evaluation, when the move played was the best. pub second: Option, - /// How hard the move was to find ([`Hardness::measure`]), when a shallow search was - /// made. - pub difficulty: Option, } #[derive(Clone, Debug, Default, PartialEq)] @@ -505,17 +355,6 @@ impl Report { plies: &[Ply], phases: Phases, rules: Rules, - ) -> Report { - Self::build_tuned(evals, plies, phases, rules, Hardness::default()) - } - - /// [`Report::build_with`] where the difficulty of a move counts as `hard` says. - pub fn build_tuned( - evals: &[Option], - plies: &[Ply], - phases: Phases, - rules: Rules, - hard: Hardness, ) -> Report { let n = plies.len().min(evals.len().saturating_sub(1)); let mut report = Report { @@ -530,16 +369,7 @@ impl Report { let mut noted = vec![false; n]; let mut lost = vec![0.0; n]; for i in 0..n { - let mut ply = plies[i]; - // Winning back after the opponent took the mover's sacrifice goes on with the - // combination: no trade (18…Bxc4+ of Byrne — Fischer after 17…Be6 18.Bxb6). - if let (Some(f), Some(own)) = ( - ply.features.as_mut(), - i.checked_sub(2).and_then(|k| plies[k].features), - ) && own.sacrifice - { - f.takes_back = false; - } + let ply = plies[i]; let (Some(before), Some(after)) = (evals[i], evals[i + 1]) else { continue; }; @@ -553,7 +383,7 @@ impl Report { judge(before, after, ply.mover) }; let good = if error.is_none() { - note(before, after, &ply, rules, hard) + note(before, after, &ply, rules) } else { None }; @@ -695,7 +525,6 @@ mod tests { best: false, features: None, second: None, - difficulty: None, } } @@ -876,7 +705,6 @@ mod tests { ..Default::default() }), second, - difficulty: None, } } @@ -891,26 +719,12 @@ mod tests { ); assert_eq!(r.judgements[0], Some(Judgement::Brilliant)); assert_eq!(r.white.brilliant, 1); - // Another move won as well: still !! by chess.com's marks, no !! by the first - // rules; with a forced mate there: no !! either way. + // Another move won as well: no !!. let r = Report::build( &evals, &[noted(w, true, Some(Eval::Cp(800)))], Phases::default(), ); - assert_eq!(r.judgements[0], Some(Judgement::Brilliant)); - let r = Report::build_with( - &evals, - &[noted(w, true, Some(Eval::Cp(800)))], - Phases::default(), - Rules::Strict, - ); - assert_eq!(r.judgements[0], None); - let mate = Some(Eval::Mate { - white: true, - moves: 5, - }); - let r = Report::build(&evals, &[noted(w, true, mate)], Phases::default()); assert_eq!(r.judgements[0], None); // No best other move known (an older analysis): nothing said. let r = Report::build(&evals, &[noted(w, true, None)], Phases::default()); @@ -975,14 +789,9 @@ mod tests { let (w, b) = (Color::White, Color::Black); // The only good move of an equal position: great by chess.com, not by the first rules. let equal = [Some(Eval::Cp(0)), Some(Eval::Cp(0))]; - let only = || noted(w, false, Some(Eval::Cp(-400))); - let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::ChessCom); - assert_eq!(r.judgements[0], Some(Judgement::Great)); - // Others still equal-ish (−1.5): no turn of the game for the first rules, and - // short of the stricter gap of chess.com's rules. let only = || noted(w, false, Some(Eval::Cp(-150))); let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::ChessCom); - assert_eq!(r.judgements[0], None); + assert_eq!(r.judgements[0], Some(Judgement::Great)); let r = Report::build_with(&equal, &[only()], Phases::default(), Rules::Strict); assert_eq!(r.judgements[0], None); // A combination: marked once by the first rules. diff --git a/crates/mobile-api/src/lib.rs b/crates/mobile-api/src/lib.rs index 73ffb39..f409152 100644 --- a/crates/mobile-api/src/lib.rs +++ b/crates/mobile-api/src/lib.rs @@ -15,7 +15,6 @@ use shakmaty::Position; mod engine; mod online; mod play; -mod prep; mod review; mod session; mod train; @@ -31,10 +30,6 @@ pub use play::{ RodentStyle, computer_game_tags, hopeless_turns, maia_range, move_pause_ms, rival_label, rival_name, rodent_book_pack, rodent_range, rodent_styles, rodent_version, }; -pub use prep::{ - PlayerSuggestion, PlayerSuggestions, PrepContinuation, PrepMatch, PrepPhase, PrepResult, - PrepSearch, PrepState, -}; pub use review::{GameReview, MoveJudgement, ReviewMove, ReviewPoint, ReviewState, SideReview}; pub use session::{Edited, GameSession, own_create, own_remove, own_save}; pub use train::{TrainState, TrainStats, TrainVerdict, Trainer, trainer_set_file}; @@ -76,11 +71,6 @@ impl From for ApiError { E::Io { source, .. } => ApiError::Io { detail: source.to_string(), }, - // A .cbh alone: reported as before (the app opens a ChessBase database - // by all its files, `open_chessbase`). - E::Unsupported(u @ chess_import::Unsupported::ChessBaseFiles) => ApiError::Corrupt { - detail: u.to_string(), - }, E::Unsupported(u) => ApiError::Unsupported { detail: u.to_string(), }, @@ -96,11 +86,9 @@ impl From for ApiError { /// An open database. #[derive(uniffi::Object)] pub struct Database { - db: Arc, + db: chess_import::Database, format: String, notes: Vec, - /// At most one opponent-preparation worker per open database. - prep: std::sync::Mutex>>, } /// One line of the game list. @@ -189,10 +177,9 @@ fn never() -> AtomicBool { fn wrap(opened: chess_import::Opened) -> Arc { Arc::new(Database { - db: Arc::new(opened.db), + db: opened.db, format: opened.format.label().to_owned(), notes: opened.notes, - prep: std::sync::Mutex::new(None), }) } @@ -674,10 +661,7 @@ mod tests { fn comments_and_variations_come_along() { // The Opera game of the samples has comments and a variation. let db = classics(); - let g = (0..db.len()) - .map(|i| db.game(i).expect("a game")) - .find(|g| g.nodes.iter().any(|n| n.san == "Qb8+")) - .expect("the Opera game"); + let g = db.game(0).expect("a game"); assert!( g.nodes .iter() diff --git a/crates/mobile-api/src/prep.rs b/crates/mobile-api/src/prep.rs deleted file mode 100644 index d373f96..0000000 --- a/crates/mobile-api/src/prep.rs +++ /dev/null @@ -1,812 +0,0 @@ -//! Simple opponent preparation: exact players, their games on one colour, and the -//! continuations from the first main-line occurrence of a position. Searches run on -//! one worker per database and never start an engine or change the source database. - -use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; - -use chess_core::StartPosition; -use chess_import::chessbase::base::{Filter, NameFilter, Side, SortKey}; -use chess_import::position::{GameResult, PositionOutcome, PositionQuery}; -use shakmaty::uci::UciMove; -use shakmaty::{Chess, Color, Position, san::SanPlus}; - -use crate::{ApiError, Database, GameRow}; - -/// Keeps a search response bounded even when the position occurs in a whole book. -const MATCH_LIMIT: usize = 100; -const SUGGESTION_LIMIT: u32 = 200; - -/// One exact player name from the database catalogue. -#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] -pub struct PlayerSuggestion { - /// Stable within this open database; used by [`Database::prepare_position`]. - pub id: u32, - pub name: String, - /// Distinct games. A game with this name on both sides counts once here. - pub games: u32, - pub white_games: u32, - pub black_games: u32, -} - -/// A page of [`PlayerSuggestion`] and the total number of matching names. -#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] -pub struct PlayerSuggestions { - pub players: Vec, - pub total: u32, -} - -/// A move played next, with the selected player's results (not the mover's). -#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)] -pub struct PrepContinuation { - pub uci: String, - pub san: String, - pub count: u32, - pub wins: u32, - pub draws: u32, - pub losses: u32, - /// Games with `Result "*"` (or another unknown result); not a loss. - pub unknown: u32, -} - -/// One matching game. `ply` opens its first main-line occurrence of the position. -#[derive(Debug, Clone, PartialEq, uniffi::Record)] -pub struct PrepMatch { - pub index: u32, - pub ply: u32, - pub row: GameRow, -} - -/// Continuations and results at one position. -#[derive(Debug, Clone, PartialEq, uniffi::Record)] -pub struct PrepResult { - /// Matching games, each counted once at its first main-line occurrence. - pub games: u32, - pub wins: u32, - pub draws: u32, - pub losses: u32, - pub unknown: u32, - /// Whether the selected player (rather than their opponents) moves here. - pub player_to_move: bool, - /// By count descending, then SAN ascending. - pub continuations: Vec, - pub ended: u32, - /// A teaching null move or a continuation that is not a normal legal move. - pub no_normal_continuation: u32, - /// At most 100 rows in record order; `matches_total` is the unpaginated count. - pub matches: Vec, - pub matches_total: u32, -} - -/// The phase of a [`PrepSearch`]. Terminal phases are `Ready`, `Cancelled`, -/// `NoMemory` and `Failed`. -#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)] -pub enum PrepPhase { - Games, - Index, - Search, - Ready, - Cancelled, - NoMemory, - Failed, -} - -/// A snapshot of a preparation worker. -#[derive(Debug, Clone, PartialEq, uniffi::Record)] -pub struct PrepState { - pub phase: PrepPhase, - /// Progress inside the current phase (`total == 0` means not applicable). - pub done: u32, - pub total: u32, - pub running: bool, - pub result: Option, - /// Empty except for `Failed` and `NoMemory`. - pub failure: String, -} - -#[derive(Clone, Default)] -struct Score { - count: u32, - wins: u32, - draws: u32, - losses: u32, - unknown: u32, -} - -impl Score { - fn add(&mut self, result: &str, selected_white: bool) { - self.count = self.count.saturating_add(1); - match GameResult::from_tag(result) { - GameResult::WhiteWins => { - if selected_white { - self.wins = self.wins.saturating_add(1); - } else { - self.losses = self.losses.saturating_add(1); - } - } - GameResult::BlackWins => { - if selected_white { - self.losses = self.losses.saturating_add(1); - } else { - self.wins = self.wins.saturating_add(1); - } - } - GameResult::Draw => self.draws = self.draws.saturating_add(1), - GameResult::Unknown => self.unknown = self.unknown.saturating_add(1), - } - } -} - -#[derive(Clone)] -struct Snapshot { - phase: PrepPhase, - total: u32, - result: Option, - failure: String, -} - -pub(crate) struct Shared { - cancel: AtomicBool, - progress: AtomicUsize, - snapshot: Mutex, -} - -impl Shared { - fn new(total: usize) -> Self { - Self { - cancel: AtomicBool::new(false), - progress: AtomicUsize::new(0), - snapshot: Mutex::new(Snapshot { - phase: PrepPhase::Games, - total: as_u32(total), - result: None, - failure: String::new(), - }), - } - } - - fn phase(&self, phase: PrepPhase, total: usize) { - if self.cancel.load(Ordering::Relaxed) { - return; - } - self.progress.store(0, Ordering::Relaxed); - let mut snapshot = lock(&self.snapshot); - snapshot.phase = phase; - snapshot.total = as_u32(total); - } - - fn ready(&self, result: PrepResult) { - if self.cancel.load(Ordering::Relaxed) { - self.cancelled(); - return; - } - let mut snapshot = lock(&self.snapshot); - self.progress - .store(snapshot.total as usize, Ordering::Relaxed); - snapshot.phase = PrepPhase::Ready; - snapshot.result = Some(result); - } - - fn cancelled(&self) { - let mut snapshot = lock(&self.snapshot); - if matches!( - snapshot.phase, - PrepPhase::Games | PrepPhase::Index | PrepPhase::Search - ) { - snapshot.phase = PrepPhase::Cancelled; - snapshot.result = None; - } - } - - fn failed(&self, phase: PrepPhase, failure: String) { - if self.cancel.load(Ordering::Relaxed) { - self.cancelled(); - return; - } - let mut snapshot = lock(&self.snapshot); - snapshot.phase = phase; - snapshot.failure = failure; - snapshot.result = None; - } - - fn cancel(&self) { - self.cancel.store(true, Ordering::Relaxed); - self.cancelled(); - } - - fn state(&self) -> PrepState { - let snapshot = lock(&self.snapshot).clone(); - let running = matches!( - snapshot.phase, - PrepPhase::Games | PrepPhase::Index | PrepPhase::Search - ); - PrepState { - phase: snapshot.phase, - done: as_u32( - self.progress - .load(Ordering::Relaxed) - .min(snapshot.total as usize), - ), - total: snapshot.total, - running, - result: snapshot.result, - failure: snapshot.failure, - } - } -} - -/// One running or finished position search. Dropping it requests cancellation. -#[derive(uniffi::Object)] -pub struct PrepSearch { - shared: Arc, -} - -#[uniffi::export] -impl PrepSearch { - pub fn state(&self) -> PrepState { - self.shared.state() - } - - /// Stops soon; an old worker cannot publish its result afterwards. - pub fn cancel(&self) { - self.shared.cancel(); - } -} - -impl Drop for PrepSearch { - fn drop(&mut self) { - self.shared.cancel(); - } -} - -impl Drop for Database { - fn drop(&mut self) { - if let Some(shared) = lock(&self.prep).as_ref().and_then(|old| old.upgrade()) { - shared.cancel(); - } - } -} - -fn lock(mutex: &Mutex) -> std::sync::MutexGuard<'_, T> { - mutex.lock().unwrap_or_else(|e| e.into_inner()) -} - -fn as_u32(n: usize) -> u32 { - u32::try_from(n).unwrap_or(u32::MAX) -} - -#[uniffi::export] -impl Database { - /// Exact-name suggestions, `count` at most 200. An empty query lists all named - /// players alphabetically; a non-empty one keeps the catalogue's prefix/games order. - pub fn suggest_players(&self, query: String, start: u32, count: u32) -> PlayerSuggestions { - let limit = count.min(SUGGESTION_LIMIT) as usize; - let (list, total) = match self.db.as_ref() { - chess_import::Database::Pgn(db) => { - db.catalog() - .suggest_players_page(&query, start as usize, limit) - } - chess_import::Database::ChessBase(db) => { - db.suggest_players_page(&query, start as usize, limit) - } - }; - let players = list - .into_iter() - .map(|suggestion| { - let (games, white_games, black_games) = match self.db.as_ref() { - chess_import::Database::Pgn(db) => db.catalog().player_counts(suggestion.id), - chess_import::Database::ChessBase(db) => db.player_counts(suggestion.id), - }; - PlayerSuggestion { - id: suggestion.id, - name: suggestion.name, - games, - white_games, - black_games, - } - }) - .collect(); - PlayerSuggestions { - players, - total: as_u32(total), - } - } - - /// Starts preparation for an exact player and colour at `query_fen` (empty means - /// the usual initial position). Only the first main-line occurrence in each game - /// counts; transpositions count and variations in the database do not. The thread - /// is bounded to one active request per database: a new request cancels the old one. - pub fn prepare_position( - &self, - player_id: u32, - white: bool, - query_fen: String, - ) -> Result, ApiError> { - let position = parse_position(&query_fen)?; - let shared = Arc::new(Shared::new(self.db.len())); - let previous = lock(&self.prep).replace(Arc::downgrade(&shared)); - if let Some(previous) = previous.and_then(|old| old.upgrade()) { - previous.cancel(); - } - - let worker = shared.clone(); - let db = self.db.clone(); - let spawned = std::thread::Builder::new() - .name("opponent-prep".into()) - .spawn(move || run(db, player_id, white, position, worker)); - if let Err(error) = spawned { - shared.failed(PrepPhase::Failed, error.to_string()); - } - Ok(Arc::new(PrepSearch { shared })) - } -} - -fn parse_position(fen: &str) -> Result { - if fen.trim().is_empty() { - return Ok(Chess::default()); - } - StartPosition::from_fen(fen) - .map(|start| start.position().clone()) - .map_err(|error| ApiError::Edit { - detail: error.to_string(), - }) -} - -fn player_games( - db: &chess_import::Database, - player_id: u32, - white: bool, - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Option> { - let side = if white { Side::White } else { Side::Black }; - match db { - chess_import::Database::Pgn(db) => { - db.catalog().player_games(player_id, side, progress, cancel) - } - chess_import::Database::ChessBase(db) => db.query( - &Filter { - player: NameFilter { - text: String::new(), - exact: Some(player_id), - }, - side, - games_only: true, - ..Filter::default() - }, - SortKey::Number, - true, - progress, - cancel, - ), - } -} - -fn run( - db: Arc, - player_id: u32, - white: bool, - position: Chess, - shared: Arc, -) { - if shared.cancel.load(Ordering::Relaxed) { - shared.cancelled(); - return; - } - // This may build the PGN catalogue; it deliberately runs here, not on the caller's - // thread. An invalid id is a failed request, not a valid empty repertoire. - if db.player_name(player_id).trim().is_empty() { - shared.failed(PrepPhase::Failed, format!("unknown player {player_id}")); - return; - } - let Some(games) = player_games(&db, player_id, white, &shared.progress, &shared.cancel) else { - shared.cancelled(); - return; - }; - if games.is_empty() { - shared.phase(PrepPhase::Search, 0); - shared.ready(result(&db, &position, white, PositionOutcome::default())); - return; - } - if let Some(needed) = db.positions_blocked() { - shared.failed( - PrepPhase::NoMemory, - format!("not enough memory for the position index ({needed} bytes needed)"), - ); - return; - } - - let preparing = !db.positions_ready(); - shared.phase( - if preparing { - PrepPhase::Index - } else { - PrepPhase::Search - }, - if preparing { db.len() } else { games.len() }, - ); - let query = PositionQuery::new(position.clone(), None); - let outcome = db.search_position_first(Some(&games), &query, &shared.progress, &shared.cancel); - match outcome { - Some(outcome) => shared.ready(result(&db, &position, white, outcome)), - None if shared.cancel.load(Ordering::Relaxed) => shared.cancelled(), - None => shared.failed( - PrepPhase::Failed, - "position search ended without a result".into(), - ), - } -} - -fn result( - db: &chess_import::Database, - position: &Chess, - selected_white: bool, - outcome: PositionOutcome, -) -> PrepResult { - let mut total = Score::default(); - let mut continuations: HashMap = HashMap::new(); - let mut ended = 0u32; - let mut no_normal = 0u32; - let mut matches = Vec::with_capacity(outcome.matches.len().min(MATCH_LIMIT)); - - for (place, found) in outcome.matches.iter().enumerate() { - let row = game_row(db, found.index); - total.add(&row.result, selected_white); - match found.next { - None => ended = ended.saturating_add(1), - Some(UciMove::Null) => no_normal = no_normal.saturating_add(1), - Some(uci) => match uci.to_move(position) { - Ok(_) => continuations - .entry(uci) - .or_default() - .add(&row.result, selected_white), - Err(_) => no_normal = no_normal.saturating_add(1), - }, - } - if place < MATCH_LIMIT { - matches.push(PrepMatch { - index: found.index, - ply: found.ply, - row, - }); - } - } - - let mut continuations: Vec = continuations - .into_iter() - .filter_map(|(uci, score)| { - let mv = uci.to_move(position).ok()?; - let san = SanPlus::from_move(position.clone(), mv).to_string(); - Some(PrepContinuation { - uci: uci.to_string(), - san, - count: score.count, - wins: score.wins, - draws: score.draws, - losses: score.losses, - unknown: score.unknown, - }) - }) - .collect(); - continuations.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.san.cmp(&b.san))); - let continuation_games = continuations.iter().fold(0u32, |sum, continuation| { - sum.saturating_add(continuation.count) - }); - debug_assert_eq!( - continuation_games - .saturating_add(ended) - .saturating_add(no_normal), - total.count - ); - PrepResult { - games: total.count, - wins: total.wins, - draws: total.draws, - losses: total.losses, - unknown: total.unknown, - player_to_move: position.turn() - == if selected_white { - Color::White - } else { - Color::Black - }, - continuations, - ended, - no_normal_continuation: no_normal, - matches_total: total.count, - matches, - } -} - -fn game_row(db: &chess_import::Database, index: u32) -> GameRow { - let row = db.row(index as usize); - let elo = |value: u16| { - if value == 0 { - String::new() - } else { - value.to_string() - } - }; - GameRow { - index, - white: row.white, - black: row.black, - result: row.result.to_owned(), - date: row.date, - event: row.event, - eco: row.eco.unwrap_or_default(), - white_elo: elo(row.white_elo), - black_elo: elo(row.black_elo), - } -} - -#[cfg(test)] -mod tests { - use super::*; - use shakmaty::EnPassantMode; - use shakmaty::fen::Fen; - use shakmaty::san::San; - - use crate::open_bytes; - - fn database(pgn: &str) -> Arc { - open_bytes("prep.pgn".into(), pgn.as_bytes().to_vec()).expect("fixture opens") - } - - fn fen(line: &[&str]) -> String { - let mut position = Chess::default(); - for san in line { - let mv = san - .parse::() - .expect("fixture SAN") - .to_move(&position) - .expect("legal fixture move"); - position.play_unchecked(mv); - } - Fen::from_position(&position, EnPassantMode::Legal).to_string() - } - - fn player(db: &Database, name: &str) -> PlayerSuggestion { - db.suggest_players(name.into(), 0, SUGGESTION_LIMIT) - .players - .into_iter() - .find(|player| player.name == name) - .expect("exact fixture player") - } - - fn search(db: &Database, player_id: u32, white: bool, fen: String) -> PrepState { - let search = db - .prepare_position(player_id, white, fen) - .expect("search starts"); - for _ in 0..1000 { - let state = search.state(); - if !state.running { - return state; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - } - panic!("preparation did not finish") - } - - fn ready(state: PrepState) -> PrepResult { - assert_eq!(state.phase, PrepPhase::Ready, "{}", state.failure); - assert_eq!(state.done, state.total); - state.result.expect("ready result") - } - - #[test] - fn suggestions_are_paged_normalized_and_count_each_colour() { - let db = database(concat!( - "[White \"Vafin Radel\"][Black \"Other A\"][Result \"1-0\"]\n\n1. e4 c5 1-0\n\n", - "[White \"Other B\"][Black \"Vafin Radel\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n", - "[White \"Vafin Radel\"][Black \"Vafin Radel\"][Result \"0-1\"]\n\n1. e4 e5 0-1\n\n", - "[White \"Vafina Rayana\"][Black \"Other C\"][Result \"*\"]\n\n1. e4 c5 *\n", - )); - let first = db.suggest_players("vafin".into(), 0, 1); - assert_eq!(first.total, 2); - assert_eq!(first.players.len(), 1); - let vafin = &first.players[0]; - assert_eq!(vafin.name, "Vafin Radel"); - assert_eq!( - (vafin.games, vafin.white_games, vafin.black_games), - (3, 2, 2) - ); - let second = db.suggest_players("vafin".into(), 1, 1); - assert_eq!(second.players[0].name, "Vafina Rayana"); - assert!(db.suggest_players("vafin".into(), 2, 1).players.is_empty()); - let all = db.suggest_players(String::new(), 0, 200); - assert_eq!(all.total, 5); - assert!( - all.players - .windows(2) - .all(|pair| pair[0].name <= pair[1].name) - ); - - let after_e4 = fen(&["e4"]); - let white = ready(search(&db, vafin.id, true, after_e4.clone())); - assert_eq!((white.games, white.wins, white.losses), (2, 1, 1)); - assert_eq!( - white.matches.iter().map(|m| m.index).collect::>(), - [0, 2] - ); - let black = ready(search(&db, vafin.id, false, after_e4)); - assert_eq!((black.games, black.wins, black.losses), (2, 2, 0)); - assert_eq!( - black.matches.iter().map(|m| m.index).collect::>(), - [1, 2] - ); - } - - #[test] - fn first_main_line_occurrence_wins_over_repetition_and_rav() { - let db = database(concat!( - "[White \"Repeat\"][Black \"X\"][Result \"1-0\"]\n\n", - "1. Nf3 (1. e4 e5) Nf6 2. Ng1 Ng8 3. d4 d5 1-0\n", - )); - let id = player(&db, "Repeat").id; - let result = ready(search(&db, id, true, fen(&[]))); - assert_eq!(result.games, 1); - assert_eq!(result.matches[0].ply, 0); - assert_eq!(result.continuations.len(), 1); - assert_eq!(result.continuations[0].san, "Nf3"); - assert_eq!(result.continuations[0].count, 1); - assert_eq!(result.ended, 0); - - let db = database(concat!( - "[White \"Main\"][Black \"X\"][Result \"1-0\"]\n\n", - "1. e4 c5 (1... e5) 2. Nf3 1-0\n\n", - "[White \"Main\"][Black \"X\"][Result \"0-1\"]\n\n", - "1. e4 e5 (1... c5 2. Nf3) 2. Nf3 0-1\n", - )); - let id = player(&db, "Main").id; - let result = ready(search(&db, id, true, fen(&["e4", "c5"]))); - assert_eq!( - result.games, 1, - "a RAV-only occurrence is not a played game" - ); - assert_eq!(result.matches[0].index, 0); - assert_eq!(result.matches[0].ply, 2); - assert_eq!(result.continuations.len(), 1); - assert_eq!(result.continuations[0].san, "Nf3"); - assert_eq!((result.wins, result.losses), (1, 0)); - } - - #[test] - fn transpositions_have_the_same_games_and_continuations() { - let db = database(concat!( - "[White \"T\"][Black \"X\"][Result \"1-0\"]\n\n1. Nf3 d5 2. d4 e6 1-0\n\n", - "[White \"T\"][Black \"X\"][Result \"0-1\"]\n\n1. d4 d5 2. Nf3 c6 0-1\n", - )); - let id = player(&db, "T").id; - let a = ready(search(&db, id, true, fen(&["Nf3", "d5", "d4"]))); - let b = ready(search(&db, id, true, fen(&["d4", "d5", "Nf3"]))); - assert_eq!(a, b); - assert_eq!(a.games, 2); - assert_eq!(a.matches.iter().map(|m| m.ply).collect::>(), [3, 3]); - assert_eq!( - a.continuations - .iter() - .map(|m| m.san.as_str()) - .collect::>(), - ["c6", "e6"] - ); - assert_eq!((a.wins, a.losses), (1, 1)); - } - - #[test] - fn continuation_results_belong_to_the_selected_player() { - let db = database(concat!( - "[White \"W1\"][Black \"B\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n", - "[White \"W2\"][Black \"B\"][Result \"0-1\"]\n\n1. e4 c5 0-1\n\n", - "[White \"W3\"][Black \"B\"][Result \"1-0\"]\n\n1. e4 c5 1-0\n\n", - "[White \"W4\"][Black \"B\"][Result \"*\"]\n\n1. e4 c5 *\n", - )); - let id = player(&db, "B").id; - let result = ready(search(&db, id, false, fen(&["e4"]))); - assert_eq!( - ( - result.games, - result.wins, - result.draws, - result.losses, - result.unknown - ), - (4, 2, 0, 1, 1) - ); - let c5 = &result.continuations[0]; - assert_eq!(c5.san, "c5"); - assert_eq!( - (c5.count, c5.wins, c5.draws, c5.losses, c5.unknown), - (4, 2, 0, 1, 1) - ); - assert!( - result.player_to_move, - "Black moves after 1.e4, so the selected player moves here" - ); - } - - #[test] - fn a_fen_game_starts_at_ply_zero_with_black_to_move() { - let query = "8/3k4/8/3K4/3P4/8/8/8 b - - 0 0"; - let pgn = format!( - "[White \"X\"][Black \"FEN player\"][Result \"*\"][SetUp \"1\"][FEN \"{query}\"]\n\n1... Kc7 *\n" - ); - let db = database(&pgn); - let id = player(&db, "FEN player").id; - let result = ready(search(&db, id, false, query.into())); - assert_eq!(result.games, 1); - assert_eq!(result.matches[0].ply, 0); - assert_eq!(result.continuations[0].san, "Kc7"); - assert!(result.player_to_move); - assert_eq!( - (result.wins, result.draws, result.losses, result.unknown), - (0, 0, 0, 1) - ); - } - - #[test] - fn ended_and_teaching_null_moves_balance_the_game_count() { - let db = database(concat!( - "[White \"N\"][Black \"X\"][Result \"*\"]\n\n1. e4 *\n\n", - "[White \"N\"][Black \"X\"][Result \"*\"]\n\n1. e4 -- *\n", - )); - let id = player(&db, "N").id; - let result = ready(search(&db, id, true, fen(&["e4"]))); - assert_eq!(result.games, 2); - assert!(result.continuations.is_empty()); - assert_eq!(result.ended, 1); - assert_eq!(result.no_normal_continuation, 1); - assert_eq!(result.unknown, 2); - } - - #[test] - fn matches_are_bounded_and_a_new_request_cancels_the_old_one() { - let pgn = std::iter::repeat_n( - "[White \"Many\"][Black \"X\"][Result \"*\"]\n\n1. e4 *\n\n", - 105, - ) - .collect::(); - let db = database(&pgn); - let id = player(&db, "Many").id; - let first = db - .prepare_position(id, true, fen(&[])) - .expect("first starts"); - let second = db - .prepare_position(id, true, fen(&[])) - .expect("second starts"); - assert!(first.shared.cancel.load(Ordering::Relaxed)); - let mut state = second.state(); - for _ in 0..1000 { - if !state.running { - break; - } - std::thread::sleep(std::time::Duration::from_millis(5)); - state = second.state(); - } - let result = ready(state); - assert_eq!(result.games, 105); - assert_eq!(result.matches_total, 105); - assert_eq!(result.matches.len(), MATCH_LIMIT); - assert_eq!(result.unknown, 105); - - let cancelled = Arc::new(Shared::new(db.db.len())); - cancelled.cancel(); - run(db.db.clone(), id, true, Chess::default(), cancelled.clone()); - assert_eq!(cancelled.state().phase, PrepPhase::Cancelled); - assert!(cancelled.state().result.is_none()); - } - - #[test] - fn invalid_fen_is_an_input_error_not_a_worker_panic() { - let db = database("[White \"P\"][Black \"X\"] *\n"); - let id = player(&db, "P").id; - assert!(matches!( - db.prepare_position(id, true, "not a fen".into()), - Err(ApiError::Edit { .. }) - )); - let unknown = search(&db, u32::MAX, true, fen(&[])); - assert_eq!(unknown.phase, PrepPhase::Failed); - assert!(unknown.failure.contains("unknown player")); - } -} diff --git a/crates/mobile-api/src/review.rs b/crates/mobile-api/src/review.rs index 523a779..822408f 100644 --- a/crates/mobile-api/src/review.rs +++ b/crates/mobile-api/src/review.rs @@ -14,7 +14,9 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use chess_core::{Game, NodeId}; -use game_review::{Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, SideStats}; +use game_review::{ + Eval, GameAnalysis, JobEvent, JobFailure, JobSettings, Judgement, ReviewMeta, SideStats, +}; use shakmaty::Color; use crate::EngineLine; @@ -109,9 +111,6 @@ pub struct ReviewState { pub engine: String, /// Nodes per position; 0 for evaluations from the PGN. pub nodes: u64, - /// The evaluations come from another engine search than today's fixed one (an - /// analysis made before it): shown, but "update" makes them all again. - pub stale: bool, /// Positions of the main line without an evaluation. pub missing: u32, /// Evaluated positions still waiting for the second search of !! and ! (an analysis @@ -122,8 +121,8 @@ pub struct ReviewState { /// Engine searches a full analysis is expected to make (for the time estimate: a /// second search for moves that could be brilliant or great). pub searches: u32, - /// The speed of one engine process in the last run (0 when unknown). - pub nps_per_process: u64, + /// The engine's speed in the last run, per thread (0 when unknown). + pub nps_per_thread: u64, /// The start position and the position after every main-line move. pub points: Vec, /// Where the middlegame and the endgame begin, as indices of `points`. @@ -144,6 +143,7 @@ enum Msg { struct Job { rx: Receiver, cancel: Arc, + threads: u32, } impl Drop for Job { @@ -162,7 +162,7 @@ struct Inner { done: u32, total: u32, failure: Option, - nps_per_process: u64, + nps_per_thread: u64, /// When the cache was last written: a long run is kept now and then, so that a /// crash or a killed app loses little of it. saved: Instant, @@ -196,7 +196,7 @@ impl GameReview { done: 0, total: 0, failure: None, - nps_per_process: 0, + nps_per_thread: 0, saved: Instant::now(), }), }) @@ -206,23 +206,37 @@ impl GameReview { #[uniffi::export] impl GameReview { /// Starts the engine at `path` (with its network `eval_file`, if not empty) on the - /// positions without an evaluation, or on all of them when `full` (or when the - /// analysis is stale). The search is the fixed one of every game analysis, the same - /// as on the desktop. Returns false when there is nothing to analyse. Returns at - /// once: the engine starts on its own thread. - pub fn start(&self, path: String, eval_file: String, full: bool) -> bool { + /// positions without an evaluation, or on all of them when `full`. Returns false when + /// there is nothing to analyse. Returns at once: the engine starts on its own thread. + pub fn start( + &self, + path: String, + eval_file: String, + threads: u32, + hash_mb: u32, + nodes: u64, + full: bool, + ) -> bool { let mut st = lock(&self.inner); stop(&mut st); st.failure = None; + let meta = ReviewMeta { + engine: "Stockfish".into(), + nodes, + }; let Inner { game, analysis, .. } = &mut *st; - let targets = analysis.begin(game, full); + let targets = analysis.begin(game, meta, full); if targets.is_empty() { return false; } - let settings = JobSettings::new( - phone_processes(), - (!eval_file.is_empty()).then_some(eval_file), - ); + // Filling in keeps the quality of the earlier run (see `GameAnalysis::begin`). + let nodes = analysis.meta.as_ref().map_or(nodes, |m| m.nodes); + let settings = JobSettings { + threads: threads.max(1), + hash_mb: hash_mb.max(1), + nodes, + eval_file: (!eval_file.is_empty()).then_some(eval_file), + }; // Below the app (nice 10), as the live engine: the phone stays smooth. let config = uci::EngineConfig { nice: 10, @@ -233,6 +247,7 @@ impl GameReview { let stop = cancel.clone(); st.total = targets.len() as u32; st.done = 0; + let threads = settings.threads; let spawned = std::thread::Builder::new() .name("game-review".into()) .spawn(move || { @@ -249,7 +264,11 @@ impl GameReview { st.failure = Some(e.to_string()); return false; } - st.job = Some(Job { rx, cancel }); + st.job = Some(Job { + rx, + cancel, + threads, + }); true } @@ -297,12 +316,13 @@ fn drain(st: &mut Inner) { Msg::Failed(e) => ended = Some(Some(e)), } } + let threads = u64::from(job.threads.max(1)); let got = !events.is_empty(); for e in events { if let JobEvent::Eval { nps, .. } = &e { st.done += 1; if *nps > 0 { - st.nps_per_process = *nps; + st.nps_per_thread = nps / threads; } } st.analysis.apply(e); @@ -316,22 +336,6 @@ fn drain(st: &mut Inner) { } } -/// Seconds `searches` engine searches of the game analysis take at `nps_per_process` -/// nodes per second of one engine process (measured before, or a guess), in this -/// phone's engine processes. -#[uniffi::export] -pub fn review_estimate_secs(searches: u32, nps_per_process: u64) -> u32 { - game_review::estimate_secs(searches as usize, nps_per_process as f64, phone_processes()).ceil() - as u32 -} - -/// Engine processes of a game analysis on a phone: one per core, at most -/// [`game_review::PHONE_PROCESSES`] and what the free memory holds; all below the app -/// (nice 10). -fn phone_processes() -> usize { - game_review::processes(game_review::PHONE_PROCESSES) -} - fn save(st: &mut Inner) { st.saved = Instant::now(); if let Some(dir) = &st.cache_dir { @@ -433,12 +437,11 @@ fn snapshot(st: &Inner) -> ReviewState { has_data: a.has_data(), engine: meta.engine, nodes: meta.nodes, - stale: a.stale(), missing: a.missing() as u32, seconds_missing: a.seconds_missing() as u32, positions: a.positions() as u32, searches: a.searches() as u32, - nps_per_process: st.nps_per_process, + nps_per_thread: st.nps_per_thread, points, middlegame: a.report.phases.middlegame.map(|i| i as u32), endgame: a.report.phases.endgame.map(|i| i as u32), @@ -474,8 +477,8 @@ mod tests { // Evaluations from the PGN have no lines: nothing to show on the board. assert!(ke7.best.is_none() && ke7.reply_from.is_none()); assert!(s.white.accuracy.is_some()); - // The engine never fills in evaluations from the PGN: it would analyse the whole - // game (GameAnalysis::begin), so nothing is started here. + // Nothing to analyse: every position has an evaluation. + assert!(!review.start("/nonexistent".into(), String::new(), 1, 16, 1000, false)); } /// With the fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). @@ -492,7 +495,7 @@ mod tests { let db = open_bytes("t.pgn".into(), b"1. e4 e5 2. Nf3 Nc6 *\n".to_vec()).unwrap(); let review = db.review(0, cache.clone()).unwrap(); assert!(!review.state().has_data); - assert!(review.start(fake.into(), String::new(), false)); + assert!(review.start(fake.into(), String::new(), 1, 16, 1000, false)); let mut s = review.state(); for _ in 0..200 { if !s.running { @@ -508,8 +511,7 @@ mod tests { drop(review); // The next time the game opens, the results are there without the engine. let again = db.review(0, cache).unwrap().state(); - assert!(again.has_data && again.missing == 0 && !again.stale); - assert_eq!(again.nodes, game_review::SEARCH_NODES); + assert!(again.has_data && again.missing == 0 && again.nodes == 1000); let _ = std::fs::remove_dir_all(&dir); } @@ -517,7 +519,14 @@ mod tests { fn a_failing_engine_is_reported() { let db = open_bytes("t.pgn".into(), b"1. e4 e5 *\n".to_vec()).unwrap(); let review = db.review(0, String::new()).unwrap(); - assert!(review.start("/nonexistent/engine".into(), String::new(), false)); + assert!(review.start( + "/nonexistent/engine".into(), + String::new(), + 1, + 16, + 1000, + false + )); let mut s = review.state(); for _ in 0..200 { if !s.running { diff --git a/crates/online-games/Cargo.toml b/crates/online-games/Cargo.toml index da2d8d7..2443f57 100644 --- a/crates/online-games/Cargo.toml +++ b/crates/online-games/Cargo.toml @@ -11,9 +11,6 @@ publish = false [dependencies] serde.workspace = true serde_json.workspace = true - -# Requests that block a thread: not in a browser (net.rs). -[target.'cfg(not(target_family = "wasm"))'.dependencies] ureq = "3.4" [dev-dependencies] diff --git a/crates/online-games/src/lib.rs b/crates/online-games/src/lib.rs index a287ab2..8fb77e7 100644 --- a/crates/online-games/src/lib.rs +++ b/crates/online-games/src/lib.rs @@ -8,14 +8,14 @@ //! `since`; anonymous requests are throttled to 20 games a second. Chess.com: the list of //! monthly archives, then each month's games as JSON (their PGN inside), from the last //! month already fetched. Only standard chess is kept (variants are not supported). -//! -//! The network part (`net.rs`: lookups, downloads) is built where requests can block -//! a thread: not in a browser. +use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; -use std::sync::atomic::AtomicUsize; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; use serde::{Deserialize, Serialize}; +use serde_json::Value; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Platform { @@ -44,10 +44,24 @@ impl Platform { /// Lichess's anonymous export rate (games per second), for the time estimate. pub const LICHESS_RATE: u64 = 20; -#[cfg(not(target_family = "wasm"))] -mod net; -#[cfg(not(target_family = "wasm"))] -pub use net::{download, lookup, probe, probe_all}; +fn agent(stream: bool) -> ureq::Agent { + let config = ureq::Agent::config_builder() + .user_agent(format!( + "ChessPenguin/{} (+https://chess.vrubel.xyz)", + env!("CARGO_PKG_VERSION") + )) + .http_status_as_error(false) + .timeout_connect(Some(Duration::from_secs(10))) + .timeout_recv_response(Some(Duration::from_secs(30))) + // A long export is one response: hours for the body (a stalled one ends). + .timeout_recv_body(if stream { + Some(Duration::from_secs(4 * 3600)) + } else { + Some(Duration::from_secs(60)) + }) + .build(); + ureq::Agent::new_with_config(config) +} /// What went wrong talking to a platform. #[derive(Debug, Clone, PartialEq, Eq)] @@ -76,6 +90,104 @@ impl std::fmt::Display for Failure { } } +/// Makes a request again when the connection broke (Lichess drops connections for a +/// minute or so after an export was cut short), waiting `waits` seconds in between; +/// stops waiting when cancelled. +fn retrying( + waits: &[u64], + cancel: &AtomicBool, + mut request: impl FnMut() -> Result, +) -> Result { + let mut waits = waits.iter(); + loop { + match request() { + Ok(r) => return Ok(r), + Err(e) => { + let Some(&secs) = waits.next() else { + return Err(Failure::Network(e.to_string())); + }; + for _ in 0..secs * 10 { + if cancel.load(Ordering::Relaxed) { + return Err(Failure::Network(e.to_string())); + } + std::thread::sleep(Duration::from_millis(100)); + } + } + } + } +} + +/// Waits before the attempts of a download request: about a minute in all. +const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; + +/// GET returning (status, body); the body of an error status is not read. +fn get(url: &str) -> Result<(u16, String), Failure> { + let never = AtomicBool::new(false); + // The whole exchange is repeated: a connection may also break in the body. + retrying(&[2, 5], &never, || { + let mut resp = agent(false) + .get(url) + .header("Accept", "application/json") + .call()?; + let status = resp.status().as_u16(); + if status != 200 { + return Ok((status, String::new())); + } + let body = resp + .body_mut() + .with_config() + .limit(64 << 20) + .read_to_string()?; + Ok((status, body)) + }) + .and_then(|(status, body)| { + if status == 429 { + Err(Failure::RateLimited) + } else { + Ok((status, body)) + } + }) +} + +fn json(url: &str) -> Result, Failure> { + match get(url)? { + (200, body) => serde_json::from_str(&body) + .map(Some) + .map_err(|e| Failure::Unexpected(e.to_string())), + (404, _) => Ok(None), + (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), + } +} + +/// Whether the platform answers the way this code expects: the profile of an account +/// that has always existed (Lichess's own, Chess.com's founder's). +pub fn probe(p: Platform) -> bool { + let url = match p { + Platform::Lichess => "https://lichess.org/api/user/lichess", + Platform::ChessCom => "https://api.chess.com/pub/player/erik", + }; + matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) +} + +/// The probe's answer has the fields this code relies on. +fn probe_answer_ok(p: Platform, v: &Value) -> bool { + match p { + Platform::Lichess => { + v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() + } + Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", + } +} + +/// Both platforms probed (in parallel); `[lichess, chess.com]`. +pub fn probe_all() -> [bool; 2] { + std::thread::scope(|s| { + let l = s.spawn(|| probe(Platform::Lichess)); + let c = s.spawn(|| probe(Platform::ChessCom)); + [l.join().unwrap_or(false), c.join().unwrap_or(false)] + }) +} + /// A nickname both platforms could have: 2–30 letters, digits, `_` or `-`. pub fn valid_nick(nick: &str) -> bool { (2..=30).contains(&nick.len()) @@ -103,6 +215,68 @@ pub enum Lookup { Failed(Failure), } +/// Looks the nickname up on the platform. +pub fn lookup(p: Platform, nick: &str) -> Lookup { + let nick = nick.trim(); + if !valid_nick(nick) { + return Lookup::NotFound; + } + let result = match p { + Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { + v.filter(|v| v["disabled"] != true).and_then(|v| { + Some(Account { + platform: p, + username: v["username"].as_str()?.to_owned(), + games: v["count"]["all"].as_u64(), + months: None, + }) + }) + }), + Platform::ChessCom => { + let lower = nick.to_ascii_lowercase(); + json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { + let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) + else { + return Ok(None); + }; + // Chess.com answers in lower case; the user's spelling reads better. + let username = if username.eq_ignore_ascii_case(nick) { + nick.to_owned() + } else { + username + }; + let months = archives(&lower)?.len(); + Ok(Some(Account { + platform: p, + username, + games: None, + months: Some(months), + })) + }) + } + }; + match result { + Ok(Some(a)) => Lookup::Found(a), + Ok(None) => Lookup::NotFound, + Err(e) => Lookup::Failed(e), + } +} + +/// Chess.com's monthly archive URLs of a player, oldest first. +fn archives(lower: &str) -> Result, Failure> { + let v = json(&format!( + "https://api.chess.com/pub/player/{lower}/games/archives" + ))? + .ok_or_else(|| Failure::Unexpected("no archives".into()))?; + let list = v["archives"] + .as_array() + .ok_or_else(|| Failure::Unexpected("archives".into()))?; + Ok(list + .iter() + .filter_map(|u| u.as_str().map(str::to_owned)) + .collect()) +} + /// The database file of one account in `dir`: "Name (Lichess).pgn". pub fn database_path(dir: &Path, p: Platform, username: &str) -> PathBuf { dir.join(format!("{username} ({}).pgn", p.name())) @@ -196,6 +370,9 @@ pub struct State { pub tail: Vec, } +/// How many last bytes of the file the state remembers. +const TAIL: usize = 64; + impl State { pub fn load(pgn: &Path) -> Option { let text = std::fs::read_to_string(state_path(pgn)).ok()?; @@ -204,6 +381,15 @@ impl State { .filter(|s| !s.accounts.is_empty() && s.accounts.iter().all(|a| a.platform.is_some())) } + fn save(&self, pgn: &Path) -> Result<(), Failure> { + let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; + let path = state_path(pgn); + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, text) + .and_then(|_| std::fs::rename(&tmp, &path)) + .map_err(|e| Failure::Disk(e.to_string())) + } + fn holds(&self, a: &Account) -> bool { self.accounts.iter().any(|s| s.is(a)) } @@ -297,3 +483,778 @@ pub struct Done { /// Stopped by the user; what was fetched is kept and the next update continues. pub cancelled: bool, } + +/// The databases being written now: one download per file at a time. +static WRITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +/// Holds a database for one download; released when dropped. +struct Claim(PathBuf); + +impl Claim { + fn take(path: &Path) -> Option { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + if w.iter().any(|p| p == path) { + return None; + } + w.push(path.to_owned()); + Some(Claim(path.to_owned())) + } +} + +impl Drop for Claim { + fn drop(&mut self) { + let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); + w.retain(|p| *p != self.0); + } +} + +/// Appends games to the database file and keeps the state in step. +struct Writer { + path: PathBuf, + file: std::io::BufWriter, + state: State, + added: u64, + /// The file's length and last bytes as written (flushed or not). + len: u64, + tail: Vec, +} + +impl Writer { + /// Opens the database for appending; a state that does not match the file (the file + /// is gone, or a crash left games after the state) is put right first. + fn open(path: &Path, mut state: State) -> Result { + let disk = |e: std::io::Error| Failure::Disk(e.to_string()); + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(disk)?; + } + let file = std::fs::OpenOptions::new() + .create(true) + .read(true) + .append(true) + .open(path) + .map_err(disk)?; + let mut len = file.metadata().map_err(disk)?.len(); + if let Some(b) = state.bytes + && len > b + && b as usize >= state.tail.len() + { + let mut end = vec![0; state.tail.len()]; + use std::io::{Read, Seek, SeekFrom}; + let mut f = &file; + f.seek(SeekFrom::Start(b - state.tail.len() as u64)) + .and_then(|_| f.read_exact(&mut end)) + .map_err(disk)?; + if end == state.tail { + file.set_len(b).map_err(disk)?; + len = b; + } + } + let tail = if len == state.bytes.unwrap_or(u64::MAX) { + std::mem::take(&mut state.tail) + } else { + Vec::new() + }; + Ok(Writer { + path: path.to_owned(), + file: std::io::BufWriter::new(file), + state, + added: 0, + len, + tail, + }) + } + + fn game(&mut self, pgn: &str) -> Result<(), Failure> { + let pgn = pgn.trim(); + if pgn.is_empty() { + return Ok(()); + } + for part in [pgn.as_bytes(), b"\n\n"] { + self.file + .write_all(part) + .map_err(|e| Failure::Disk(e.to_string()))?; + self.len += part.len() as u64; + self.tail.extend_from_slice(part); + } + if self.tail.len() > TAIL { + self.tail.drain(..self.tail.len() - TAIL); + } + self.added += 1; + self.state.games += 1; + Ok(()) + } + + /// Makes what was written durable, the state last (it never runs ahead of the file). + fn commit(&mut self) -> Result<(), Failure> { + self.file + .flush() + .map_err(|e| Failure::Disk(e.to_string()))?; + self.state.bytes = Some(self.len); + self.state.tail = self.tail.clone(); + self.state.save(&self.path) + } + + fn done(mut self, cancelled: bool) -> Result { + if !cancelled { + self.state.updated = Some(now_secs()); + } + self.commit()?; + Ok(Done { + path: self.path, + added: self.added, + total: self.state.games, + cancelled, + }) + } +} + +/// Fetches the games of `accounts` new since the last run into the database at `path` +/// (one database for all of them); `progress` counts the games added, `status` tells +/// what is being fetched. Cancelling keeps what was fetched. One download per database +/// at a time ([`Failure::Busy`] otherwise). +pub fn download( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let _claim = Claim::take(path).ok_or(Failure::Busy)?; + // Another ChessPenguin running may download into the same database: a file lock + // (released when the file closes, also if the process dies). + if let Some(d) = path.parent() { + std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; + } + let lock = std::fs::File::create(path.with_extension("online.lock")) + .map_err(|e| Failure::Disk(e.to_string()))?; + if let Err(e) = lock.try_lock() { + return Err(match e { + std::fs::TryLockError::WouldBlock => Failure::Busy, + std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), + }); + } + let path = path.to_owned(); + let mut state = State::load(&path) + // The games are gone (the file was deleted): fetch them again. + .filter(|s| path.exists() || s.games == 0) + .unwrap_or_else(|| { + // A database without its state: start it anew rather than append duplicates. + let _ = std::fs::remove_file(&path); + State::default() + }); + // Accounts not in the database yet start from their first game. + for a in accounts { + if !state.holds(a) { + state.accounts.push(AccountState { + platform: Some(a.platform), + username: a.username.clone(), + ..AccountState::default() + }); + } + } + let mut w = Writer::open(&path, state)?; + let mut result = Ok(false); + for i in 0..w.state.accounts.len() { + let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else { + continue; + }; + status.account.store(k, Ordering::Relaxed); + status.games.store(0, Ordering::Relaxed); + result = match w.state.accounts[i].platform { + Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status), + Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), + None => Ok(false), + }; + if !matches!(result, Ok(false)) { + break; + } + } + match result { + Ok(c) => w.done(c), + Err(e) => { + // Keep what arrived before the failure; the next update continues. + let _ = w.commit(); + Err(e) + } + } +} + +#[cfg(test)] +fn download_to( + accounts: &[Account], + path: &Path, + progress: &AtomicUsize, + cancel: &AtomicBool, +) -> Result { + download(accounts, path, progress, cancel, &Progress::default()) +} + +/// Lichess's answer for one game, as far as the download cares. +struct LichessGame<'a> { + id: &'a str, + created: i64, + /// Still being played (not exported as a game yet). + playing: bool, + standard: bool, + /// Present for finished games (an unfinished one may come without it). + pgn: Option<&'a str>, +} + +fn lichess_game(v: &Value) -> Option> { + let g = LichessGame { + id: v["id"].as_str()?, + created: v["createdAt"].as_i64()?, + playing: matches!(v["status"].as_str(), Some("created" | "started")), + standard: v["variant"] + .as_str() + .is_none_or(|x| x == "standard" || x == "fromPosition"), + pgn: v["pgn"].as_str(), + }; + (g.playing || g.pgn.is_some()).then_some(g) +} + +/// Whether to write a game of the Lichess export; an unfinished one is remembered as +/// pending instead (asked about by id next time), a pending one that ended is written. +fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> bool { + let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); + if g.playing { + if pending.is_none() && g.standard { + a.lichess_pending.push((g.id.to_owned(), g.created)); + } + return false; + } + if let Some(k) = pending { + a.lichess_pending.remove(k); + } + g.standard +} + +/// A pending game Lichess no longer returns is given up after a year. +const PENDING_DAYS: i64 = 365; + +/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. +fn lichess_lines( + resp: ureq::http::Response, + cancel: &AtomicBool, + mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, +) -> Result { + match resp.status().as_u16() { + 200 => {} + 429 => return Err(Failure::RateLimited), + code => return Err(Failure::Unexpected(format!("HTTP {code}"))), + } + let reader = BufReader::new(resp.into_body().into_reader()); + for (n, line) in reader.lines().enumerate() { + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let line = line.map_err(|e| Failure::Network(e.to_string()))?; + if line.trim().is_empty() { + continue; + } + let v: Value = + serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; + each(n, &v)?; + } + Ok(false) +} + +const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; + +/// The games of account `i` of the writer's database from Lichess: first the pending +/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. +fn lichess( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let write = |w: &mut Writer, v: &Value| -> Result { + let g = lichess_game(v) + .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; + if lichess_keep(&mut w.state.accounts[i], &g) + && let Some(pgn) = g.pgn + { + let pgn = pgn.to_owned(); + w.game(&pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + } + Ok(g.created) + }; + let pending: Vec = w.state.accounts[i] + .lichess_pending + .iter() + .map(|(id, _)| id.clone()) + .collect(); + for chunk in pending.chunks(300) { + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .post(&format!( + "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" + )) + .header("Accept", "application/x-ndjson") + .send(chunk.join(",")) + })?; + if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { + return Ok(true); + } + } + let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; + w.state.accounts[i] + .lichess_pending + .retain(|(_, created)| *created > year_ago); + w.commit()?; + + let a = &w.state.accounts[i]; + let mut url = format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", + a.username + ); + if let Some(last) = a.lichess_last { + url.push_str(&format!("&since={}", last + 1)); + } + let resp = retrying(DOWNLOAD_WAITS, cancel, || { + agent(true) + .get(&url) + .header("Accept", "application/x-ndjson") + .call() + })?; + lichess_lines(resp, cancel, |n, v| { + let created = write(w, v)?; + let a = &mut w.state.accounts[i]; + a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); + if n % 100 == 99 { + w.commit()?; + } + Ok(()) + }) +} + +/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when +/// cancelled. +fn chesscom( + w: &mut Writer, + i: usize, + progress: &AtomicUsize, + cancel: &AtomicBool, + status: &Progress, +) -> Result { + let lower = w.state.accounts[i].username.to_ascii_lowercase(); + let months = archives(&lower)?; + status.months_total.store(months.len(), Ordering::Relaxed); + status.months_done.store(0, Ordering::Relaxed); + for url in months { + status.months_done.fetch_add(1, Ordering::Relaxed); + // ".../games/2026/10" → "2026/10"; months before the last fetched are done. + let month = url.rsplitn(3, '/').take(2).collect::>(); + let month = format!( + "{}/{}", + month.get(1).unwrap_or(&""), + month.first().unwrap_or(&"") + ); + let a = &w.state.accounts[i]; + if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { + continue; + } + if cancel.load(Ordering::Relaxed) { + return Ok(true); + } + let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; + let games = v["games"] + .as_array() + .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; + let mut list: Vec<(i64, &str)> = games + .iter() + .filter(|g| g["rules"] == "chess") + .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) + .collect(); + list.sort_by_key(|(t, _)| *t); + let a = &w.state.accounts[i]; + let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); + let last = if same_month { + a.chesscom_last_end + } else { + None + }; + for (end, pgn) in list { + if last.is_some_and(|l| end <= l) { + continue; + } + w.game(pgn)?; + progress.fetch_add(1, Ordering::Relaxed); + status.games.fetch_add(1, Ordering::Relaxed); + w.state.accounts[i].chesscom_last_end = Some(end); + } + // The mark moves to this month even when it had no standard games (the end + // time then still belongs to an earlier month and is not compared). + w.state.accounts[i].chesscom_month = Some(month); + w.commit()?; + } + Ok(false) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + fn account(p: Platform, name: &str) -> Account { + Account { + platform: p, + username: name.into(), + games: None, + months: None, + } + } + + const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0"; + + #[test] + fn a_crash_leaves_no_duplicates() { + let dir = temp_dir("crash"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + ..AccountState::default() + }], + ..State::default() + }; + let mut w = Writer::open(&path, state).unwrap(); + w.game(GAME).unwrap(); + w.game(GAME).unwrap(); + w.commit().unwrap(); + let good = std::fs::read(&path).unwrap(); + // Games written after the last commit, then the process died. + w.game(GAME).unwrap(); + w.file.flush().unwrap(); + drop(w); + assert!(std::fs::read(&path).unwrap().len() > good.len()); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + assert_eq!(w.state.games, 2); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state"); + + // Somebody else changed the file: it is left alone. + let mut other = good.clone(); + other[0] = b' '; + other.extend_from_slice(GAME.as_bytes()); + std::fs::write(&path, &other).unwrap(); + let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); + drop(w); + assert_eq!(std::fs::read(&path).unwrap(), other); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_deleted_database_is_downloaded_again() { + let dir = temp_dir("deleted"); + let path = dir.join("db.pgn"); + let state = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "a".into(), + lichess_last: Some(5), + ..AccountState::default() + }], + games: 7, + ..State::default() + }; + state.save(&path).unwrap(); + let never = AtomicBool::new(false); + // No account asked for: nothing fetched, only the state put right. + let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap(); + assert_eq!(d.total, 0); + let s = State::load(&path).unwrap_or_default(); + assert!(s.accounts.iter().all(|a| a.lichess_last.is_none())); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn one_download_per_database() { + let path = PathBuf::from("/nonexistent/cp-claim.pgn"); + let first = Claim::take(&path).expect("free"); + assert!(Claim::take(&path).is_none()); + let never = AtomicBool::new(false); + assert_eq!( + download_to(&[], &path, &AtomicUsize::new(0), &never), + Err(Failure::Busy) + ); + drop(first); + assert!(Claim::take(&path).is_some()); + } + + #[test] + fn names_of_merged_databases() { + let name = |a: &[Account]| { + combined_path(Path::new("/online"), a) + .unwrap() + .file_name() + .unwrap() + .to_string_lossy() + .into_owned() + }; + let li = account(Platform::Lichess, "Magnus"); + assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn"); + let cc = account(Platform::ChessCom, "magnus"); + assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn"); + let other = account(Platform::ChessCom, "MagnusCarlsen"); + assert_eq!( + name(&[li, other]), + "Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn" + ); + } + + #[test] + fn unfinished_lichess_games_come_later() { + let mut a = AccountState::default(); + let g = |id: &'static str, playing: bool| LichessGame { + id, + created: 10, + playing, + standard: true, + pgn: (!playing).then_some("1. e4 *"), + }; + // First run: a correspondence game is still on, another one is over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert!(lichess_keep(&mut a, &g("blitz", false))); + assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); + // Asked about by id: still on, then over. + assert!(!lichess_keep(&mut a, &g("corr", true))); + assert_eq!(a.lichess_pending.len(), 1); + assert!(lichess_keep(&mut a, &g("corr", false))); + assert!(a.lichess_pending.is_empty()); + // A variant game is neither kept nor waited for. + let mut v = g("960", true); + v.standard = false; + assert!(!lichess_keep(&mut a, &v)); + assert!(a.lichess_pending.is_empty()); + // An unfinished game may come without its PGN, a finished one may not. + let json = |s: &str| serde_json::from_str::(s).unwrap(); + let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); + assert!(lichess_game(&on).is_some_and(|g| g.playing)); + let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); + assert!(lichess_game(&over).is_none()); + } + + /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of + /// the repository): lookup, an interrupted Lichess download continued without gaps + /// or duplicates, a full Chess.com download, and an update that adds nothing. Run + /// with `CP_ONLINE_NICK= cargo test -p online-games online_live -- --ignored --nocapture`. + #[test] + #[ignore] + fn online_live() { + let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { + eprintln!("skipped: no CP_ONLINE_NICK"); + return; + }; + assert_eq!(probe_all(), [true, true], "both platforms answer"); + assert_eq!( + lookup(Platform::Lichess, "no-such-player-cp-x9"), + Lookup::NotFound + ); + let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let read_db = |path: &Path| { + let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) + .expect("opens"); + let mut sites = Vec::new(); + let mut problems = 0; + for i in 0..db.len() { + let g = db.load_game(i).expect("game"); + problems += usize::from(!g.diagnostics.is_empty()); + let e = &db.entries()[i]; + let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); + sites.push(site.to_owned()); + } + (db.len(), sites, problems) + }; + + // Lichess: stop after about 150 games, twice, then compare with what the + // site says about those games: no gaps, no duplicates. + let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { + panic!("not on Lichess"); + }; + let path = dir.join("li.pgn"); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let done = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("lichess round {round}: {done:?}"); + assert!(done.cancelled && done.added >= 150); + } + let (n, sites, problems) = read_db(&path); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + assert_eq!(State::load(&path).unwrap().games as usize, n); + eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); + // The same games as one uninterrupted request for that many. + let (code, body) = get(&format!( + "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ + &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", + li.username + )) + .expect("answers"); + assert_eq!(code, 200); + // Asked for JSON, Lichess answers one game per line. + let expected: Vec = body + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) + .collect(); + // Ours are the reference's first games, in its order (the reference may hold a + // few more: Lichess does not count `max` exactly as we count games). + if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { + let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); + let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); + let first = sites.iter().zip(&expected).position(|(a, b)| a != b); + panic!( + "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", + sites.len(), + expected.len() + ); + } + + // Chess.com: everything, then an update that finds nothing new. + let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { + panic!("not on Chess.com"); + }; + let path = dir.join("cc.pgn"); + let never = AtomicBool::new(false); + let done = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("downloads"); + eprintln!("chess.com: {done:?}"); + assert!(!done.cancelled && done.total > 0); + let again = download_to( + std::slice::from_ref(&cc), + &path, + &AtomicUsize::new(0), + &never, + ) + .expect("updates"); + assert_eq!((again.added, again.total), (0, done.total)); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, done.total); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + eprintln!("chess.com: {n} games, {problems} with diagnostics"); + + // Both into one database: Chess.com whole, then Lichess stopped twice; the + // second run adds Lichess games only, without duplicates. + let path = dir.join("both.pgn"); + let accounts = [cc.clone(), li.clone()]; + let mut totals = Vec::new(); + for round in 1..=2 { + let progress = AtomicUsize::new(0); + let cancel = AtomicBool::new(false); + let over = AtomicBool::new(false); + let goal = if round == 1 { + done.total as usize + 100 + } else { + 100 + }; + let d = std::thread::scope(|s| { + s.spawn(|| { + while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { + std::thread::sleep(Duration::from_millis(50)); + } + cancel.store(true, Ordering::Relaxed); + }); + let r = download_to(&accounts, &path, &progress, &cancel); + over.store(true, Ordering::Relaxed); + r.expect("downloads") + }); + eprintln!("both, round {round}: {d:?}"); + assert!(d.cancelled); + totals.push(d.total); + } + let state = State::load(&path).unwrap(); + assert_eq!(state.accounts.len(), 2); + assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); + assert!(state.accounts[0].chesscom_month.is_some()); + assert!(state.accounts[1].lichess_last.is_some()); + let (n, sites, problems) = read_db(&path); + assert_eq!(n as u64, totals[1]); + let unique: std::collections::HashSet<_> = sites.iter().collect(); + assert_eq!(unique.len(), n, "no duplicates"); + let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; + assert_eq!(chesscom, done.total, "all of Chess.com, once"); + eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn probe_answers() { + let li: Value = serde_json::from_str( + r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, + ) + .unwrap(); + assert!(probe_answer_ok(Platform::Lichess, &li)); + // A changed API (renamed or missing fields) is not offered. + let changed: Value = + serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); + assert!(!probe_answer_ok(Platform::Lichess, &changed)); + let cc: Value = + serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); + assert!(probe_answer_ok(Platform::ChessCom, &cc)); + let html = Value::String("maintenance".into()); + assert!(!probe_answer_ok(Platform::ChessCom, &html)); + assert!(!probe_answer_ok(Platform::Lichess, &html)); + } + + #[test] + fn nicknames() { + assert!(valid_nick("Magnus_C-1")); + assert!(!valid_nick("a")); + assert!(!valid_nick("bad nick")); + assert!(!valid_nick("../etc")); + assert!(!valid_nick(&"x".repeat(31))); + } + + #[test] + fn state_round_trip() { + let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let pgn = dir.join("Someone (Lichess).pgn"); + let s = State { + accounts: vec![AccountState { + platform: Some(Platform::Lichess), + username: "Someone".into(), + lichess_last: Some(1_700_000_000_000), + ..AccountState::default() + }], + games: 3, + ..State::default() + }; + s.save(&pgn).unwrap(); + assert_eq!(State::load(&pgn), Some(s)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/online-games/src/net.rs b/crates/online-games/src/net.rs deleted file mode 100644 index d20cfff..0000000 --- a/crates/online-games/src/net.rs +++ /dev/null @@ -1,978 +0,0 @@ -//! Talking to Lichess and Chess.com: lookups, probes, downloads into the database. - -use std::io::{BufRead, BufReader, Write}; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::time::Duration; - -use serde_json::Value; - -use super::*; - -/// How many last bytes of the file the state remembers. -const TAIL: usize = 64; - -impl State { - fn save(&self, pgn: &Path) -> Result<(), Failure> { - let text = serde_json::to_string_pretty(self).map_err(|e| Failure::Disk(e.to_string()))?; - let path = state_path(pgn); - let tmp = path.with_extension("tmp"); - std::fs::write(&tmp, text) - .and_then(|_| std::fs::rename(&tmp, &path)) - .map_err(|e| Failure::Disk(e.to_string())) - } -} - -fn agent(stream: bool) -> ureq::Agent { - let config = ureq::Agent::config_builder() - .user_agent(format!( - "ChessPenguin/{} (+https://chess.vrubel.xyz)", - env!("CARGO_PKG_VERSION") - )) - .http_status_as_error(false) - .timeout_connect(Some(Duration::from_secs(10))) - .timeout_recv_response(Some(Duration::from_secs(30))) - // A long export is one response: hours for the body (a stalled one ends). - .timeout_recv_body(if stream { - Some(Duration::from_secs(4 * 3600)) - } else { - Some(Duration::from_secs(60)) - }) - .build(); - ureq::Agent::new_with_config(config) -} - -/// Makes a request again when the connection broke (Lichess drops connections for a -/// minute or so after an export was cut short), waiting `waits` seconds in between; -/// stops waiting when cancelled. -fn retrying( - waits: &[u64], - cancel: &AtomicBool, - mut request: impl FnMut() -> Result, -) -> Result { - let mut waits = waits.iter(); - loop { - match request() { - Ok(r) => return Ok(r), - Err(e) => { - let Some(&secs) = waits.next() else { - return Err(Failure::Network(e.to_string())); - }; - for _ in 0..secs * 10 { - if cancel.load(Ordering::Relaxed) { - return Err(Failure::Network(e.to_string())); - } - std::thread::sleep(Duration::from_millis(100)); - } - } - } - } -} - -/// Waits before the attempts of a download request: about a minute in all. -const DOWNLOAD_WAITS: &[u64] = &[3, 10, 20, 30]; - -/// GET returning (status, body); the body of an error status is not read. -fn get(url: &str) -> Result<(u16, String), Failure> { - let never = AtomicBool::new(false); - // The whole exchange is repeated: a connection may also break in the body. - retrying(&[2, 5], &never, || { - let mut resp = agent(false) - .get(url) - .header("Accept", "application/json") - .call()?; - let status = resp.status().as_u16(); - if status != 200 { - return Ok((status, String::new())); - } - let body = resp - .body_mut() - .with_config() - .limit(64 << 20) - .read_to_string()?; - Ok((status, body)) - }) - .and_then(|(status, body)| { - if status == 429 { - Err(Failure::RateLimited) - } else { - Ok((status, body)) - } - }) -} - -fn json(url: &str) -> Result, Failure> { - match get(url)? { - (200, body) => serde_json::from_str(&body) - .map(Some) - .map_err(|e| Failure::Unexpected(e.to_string())), - (404, _) => Ok(None), - (code, _) => Err(Failure::Unexpected(format!("HTTP {code}"))), - } -} - -/// Whether the platform answers the way this code expects: the profile of an account -/// that has always existed (Lichess's own, Chess.com's founder's). -pub fn probe(p: Platform) -> bool { - let url = match p { - Platform::Lichess => "https://lichess.org/api/user/lichess", - Platform::ChessCom => "https://api.chess.com/pub/player/erik", - }; - matches!(json(url), Ok(Some(v)) if probe_answer_ok(p, &v)) -} - -/// The probe's answer has the fields this code relies on. -fn probe_answer_ok(p: Platform, v: &Value) -> bool { - match p { - Platform::Lichess => { - v["id"] == "lichess" && v["username"].is_string() && v["count"]["all"].is_u64() - } - Platform::ChessCom => v["player_id"].is_u64() && v["username"] == "erik", - } -} - -/// Both platforms probed (in parallel); `[lichess, chess.com]`. -pub fn probe_all() -> [bool; 2] { - std::thread::scope(|s| { - let l = s.spawn(|| probe(Platform::Lichess)); - let c = s.spawn(|| probe(Platform::ChessCom)); - [l.join().unwrap_or(false), c.join().unwrap_or(false)] - }) -} - -/// Looks the nickname up on the platform. -pub fn lookup(p: Platform, nick: &str) -> Lookup { - let nick = nick.trim(); - if !valid_nick(nick) { - return Lookup::NotFound; - } - let result = match p { - Platform::Lichess => json(&format!("https://lichess.org/api/user/{nick}")).map(|v| { - v.filter(|v| v["disabled"] != true).and_then(|v| { - Some(Account { - platform: p, - username: v["username"].as_str()?.to_owned(), - games: v["count"]["all"].as_u64(), - months: None, - }) - }) - }), - Platform::ChessCom => { - let lower = nick.to_ascii_lowercase(); - json(&format!("https://api.chess.com/pub/player/{lower}")).and_then(|v| { - let Some(username) = v.and_then(|v| v["username"].as_str().map(str::to_owned)) - else { - return Ok(None); - }; - // Chess.com answers in lower case; the user's spelling reads better. - let username = if username.eq_ignore_ascii_case(nick) { - nick.to_owned() - } else { - username - }; - let months = archives(&lower)?.len(); - Ok(Some(Account { - platform: p, - username, - games: None, - months: Some(months), - })) - }) - } - }; - match result { - Ok(Some(a)) => Lookup::Found(a), - Ok(None) => Lookup::NotFound, - Err(e) => Lookup::Failed(e), - } -} - -/// Chess.com's monthly archive URLs of a player, oldest first. -fn archives(lower: &str) -> Result, Failure> { - let v = json(&format!( - "https://api.chess.com/pub/player/{lower}/games/archives" - ))? - .ok_or_else(|| Failure::Unexpected("no archives".into()))?; - let list = v["archives"] - .as_array() - .ok_or_else(|| Failure::Unexpected("archives".into()))?; - Ok(list - .iter() - .filter_map(|u| u.as_str().map(str::to_owned)) - .collect()) -} - -/// The databases being written now: one download per file at a time. -static WRITING: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); - -/// Holds a database for one download; released when dropped. -struct Claim(PathBuf); - -impl Claim { - fn take(path: &Path) -> Option { - let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); - if w.iter().any(|p| p == path) { - return None; - } - w.push(path.to_owned()); - Some(Claim(path.to_owned())) - } -} - -impl Drop for Claim { - fn drop(&mut self) { - let mut w = WRITING.lock().unwrap_or_else(|e| e.into_inner()); - w.retain(|p| *p != self.0); - } -} - -/// Appends games to the database file and keeps the state in step. -struct Writer { - path: PathBuf, - file: std::io::BufWriter, - state: State, - added: u64, - /// The file's length and last bytes as written (flushed or not). - len: u64, - tail: Vec, -} - -impl Writer { - /// Opens the database for appending; a state that does not match the file (the file - /// is gone, or a crash left games after the state) is put right first. - fn open(path: &Path, mut state: State) -> Result { - let disk = |e: std::io::Error| Failure::Disk(e.to_string()); - if let Some(d) = path.parent() { - std::fs::create_dir_all(d).map_err(disk)?; - } - let file = std::fs::OpenOptions::new() - .create(true) - .read(true) - .append(true) - .open(path) - .map_err(disk)?; - let mut len = file.metadata().map_err(disk)?.len(); - if let Some(b) = state.bytes - && len > b - && b as usize >= state.tail.len() - { - let mut end = vec![0; state.tail.len()]; - use std::io::{Read, Seek, SeekFrom}; - let mut f = &file; - f.seek(SeekFrom::Start(b - state.tail.len() as u64)) - .and_then(|_| f.read_exact(&mut end)) - .map_err(disk)?; - if end == state.tail { - file.set_len(b).map_err(disk)?; - len = b; - } - } - let tail = if len == state.bytes.unwrap_or(u64::MAX) { - std::mem::take(&mut state.tail) - } else { - Vec::new() - }; - Ok(Writer { - path: path.to_owned(), - file: std::io::BufWriter::new(file), - state, - added: 0, - len, - tail, - }) - } - - fn game(&mut self, pgn: &str) -> Result<(), Failure> { - let pgn = pgn.trim(); - if pgn.is_empty() { - return Ok(()); - } - for part in [pgn.as_bytes(), b"\n\n"] { - self.file - .write_all(part) - .map_err(|e| Failure::Disk(e.to_string()))?; - self.len += part.len() as u64; - self.tail.extend_from_slice(part); - } - if self.tail.len() > TAIL { - self.tail.drain(..self.tail.len() - TAIL); - } - self.added += 1; - self.state.games += 1; - Ok(()) - } - - /// Makes what was written durable, the state last (it never runs ahead of the file). - fn commit(&mut self) -> Result<(), Failure> { - self.file - .flush() - .map_err(|e| Failure::Disk(e.to_string()))?; - self.state.bytes = Some(self.len); - self.state.tail = self.tail.clone(); - self.state.save(&self.path) - } - - fn done(mut self, cancelled: bool) -> Result { - if !cancelled { - self.state.updated = Some(now_secs()); - } - self.commit()?; - Ok(Done { - path: self.path, - added: self.added, - total: self.state.games, - cancelled, - }) - } -} - -/// Fetches the games of `accounts` new since the last run into the database at `path` -/// (one database for all of them); `progress` counts the games added, `status` tells -/// what is being fetched. Cancelling keeps what was fetched. One download per database -/// at a time ([`Failure::Busy`] otherwise). -pub fn download( - accounts: &[Account], - path: &Path, - progress: &AtomicUsize, - cancel: &AtomicBool, - status: &Progress, -) -> Result { - let _claim = Claim::take(path).ok_or(Failure::Busy)?; - // Another ChessPenguin running may download into the same database: a file lock - // (released when the file closes, also if the process dies). - if let Some(d) = path.parent() { - std::fs::create_dir_all(d).map_err(|e| Failure::Disk(e.to_string()))?; - } - let lock = std::fs::File::create(path.with_extension("online.lock")) - .map_err(|e| Failure::Disk(e.to_string()))?; - if let Err(e) = lock.try_lock() { - return Err(match e { - std::fs::TryLockError::WouldBlock => Failure::Busy, - std::fs::TryLockError::Error(e) => Failure::Disk(e.to_string()), - }); - } - let path = path.to_owned(); - let mut state = State::load(&path) - // The games are gone (the file was deleted): fetch them again. - .filter(|s| path.exists() || s.games == 0) - .unwrap_or_else(|| { - // A database without its state: start it anew rather than append duplicates. - let _ = std::fs::remove_file(&path); - State::default() - }); - // Accounts not in the database yet start from their first game. - for a in accounts { - if !state.holds(a) { - state.accounts.push(AccountState { - platform: Some(a.platform), - username: a.username.clone(), - ..AccountState::default() - }); - } - } - let mut w = Writer::open(&path, state)?; - let mut result = Ok(false); - for i in 0..w.state.accounts.len() { - let Some(k) = accounts.iter().position(|a| w.state.accounts[i].is(a)) else { - continue; - }; - status.account.store(k, Ordering::Relaxed); - status.games.store(0, Ordering::Relaxed); - result = match w.state.accounts[i].platform { - Some(Platform::Lichess) => lichess(&mut w, i, progress, cancel, status), - Some(Platform::ChessCom) => chesscom(&mut w, i, progress, cancel, status), - None => Ok(false), - }; - if !matches!(result, Ok(false)) { - break; - } - } - match result { - Ok(c) => w.done(c), - Err(e) => { - // Keep what arrived before the failure; the next update continues. - let _ = w.commit(); - Err(e) - } - } -} - -#[cfg(test)] -fn download_to( - accounts: &[Account], - path: &Path, - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Result { - download(accounts, path, progress, cancel, &Progress::default()) -} - -/// Lichess's answer for one game, as far as the download cares. -struct LichessGame<'a> { - id: &'a str, - created: i64, - /// Still being played (not exported as a game yet). - playing: bool, - standard: bool, - /// Present for finished games (an unfinished one may come without it). - pgn: Option<&'a str>, -} - -fn lichess_game(v: &Value) -> Option> { - let g = LichessGame { - id: v["id"].as_str()?, - created: v["createdAt"].as_i64()?, - playing: matches!(v["status"].as_str(), Some("created" | "started")), - standard: v["variant"] - .as_str() - .is_none_or(|x| x == "standard" || x == "fromPosition"), - pgn: v["pgn"].as_str(), - }; - (g.playing || g.pgn.is_some()).then_some(g) -} - -/// Whether to write a game of the Lichess export; an unfinished one is remembered as -/// pending instead (asked about by id next time), a pending one that ended is written. -fn lichess_keep(a: &mut AccountState, g: &LichessGame) -> bool { - let pending = a.lichess_pending.iter().position(|(id, _)| id == g.id); - if g.playing { - if pending.is_none() && g.standard { - a.lichess_pending.push((g.id.to_owned(), g.created)); - } - return false; - } - if let Some(k) = pending { - a.lichess_pending.remove(k); - } - g.standard -} - -/// A pending game Lichess no longer returns is given up after a year. -const PENDING_DAYS: i64 = 365; - -/// Reads a Lichess NDJSON answer line by line. `Ok(true)` when cancelled. -fn lichess_lines( - resp: ureq::http::Response, - cancel: &AtomicBool, - mut each: impl FnMut(usize, &Value) -> Result<(), Failure>, -) -> Result { - match resp.status().as_u16() { - 200 => {} - 429 => return Err(Failure::RateLimited), - code => return Err(Failure::Unexpected(format!("HTTP {code}"))), - } - let reader = BufReader::new(resp.into_body().into_reader()); - for (n, line) in reader.lines().enumerate() { - if cancel.load(Ordering::Relaxed) { - return Ok(true); - } - let line = line.map_err(|e| Failure::Network(e.to_string()))?; - if line.trim().is_empty() { - continue; - } - let v: Value = - serde_json::from_str(&line).map_err(|e| Failure::Unexpected(e.to_string()))?; - each(n, &v)?; - } - Ok(false) -} - -const LICHESS_PARAMS: &str = "pgnInJson=true&clocks=false&evals=false&opening=true"; - -/// The games of account `i` of the writer's database from Lichess: first the pending -/// (unfinished last time) ones by id, then the new ones. `Ok(true)` when cancelled. -fn lichess( - w: &mut Writer, - i: usize, - progress: &AtomicUsize, - cancel: &AtomicBool, - status: &Progress, -) -> Result { - let write = |w: &mut Writer, v: &Value| -> Result { - let g = lichess_game(v) - .ok_or_else(|| Failure::Unexpected("a game without id, pgn or createdAt".into()))?; - if lichess_keep(&mut w.state.accounts[i], &g) - && let Some(pgn) = g.pgn - { - let pgn = pgn.to_owned(); - w.game(&pgn)?; - progress.fetch_add(1, Ordering::Relaxed); - status.games.fetch_add(1, Ordering::Relaxed); - } - Ok(g.created) - }; - let pending: Vec = w.state.accounts[i] - .lichess_pending - .iter() - .map(|(id, _)| id.clone()) - .collect(); - for chunk in pending.chunks(300) { - let resp = retrying(DOWNLOAD_WAITS, cancel, || { - agent(true) - .post(&format!( - "https://lichess.org/api/games/export/_ids?{LICHESS_PARAMS}" - )) - .header("Accept", "application/x-ndjson") - .send(chunk.join(",")) - })?; - if lichess_lines(resp, cancel, |_, v| write(w, v).map(|_| ()))? { - return Ok(true); - } - } - let year_ago = now_secs() * 1000 - PENDING_DAYS * 86_400_000; - w.state.accounts[i] - .lichess_pending - .retain(|(_, created)| *created > year_ago); - w.commit()?; - - let a = &w.state.accounts[i]; - let mut url = format!( - "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=false\ - &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&{LICHESS_PARAMS}", - a.username - ); - if let Some(last) = a.lichess_last { - url.push_str(&format!("&since={}", last + 1)); - } - let resp = retrying(DOWNLOAD_WAITS, cancel, || { - agent(true) - .get(&url) - .header("Accept", "application/x-ndjson") - .call() - })?; - lichess_lines(resp, cancel, |n, v| { - let created = write(w, v)?; - let a = &mut w.state.accounts[i]; - a.lichess_last = Some(a.lichess_last.map_or(created, |l| l.max(created))); - if n % 100 == 99 { - w.commit()?; - } - Ok(()) - }) -} - -/// The games of account `i` of the writer's database from Chess.com. `Ok(true)` when -/// cancelled. -fn chesscom( - w: &mut Writer, - i: usize, - progress: &AtomicUsize, - cancel: &AtomicBool, - status: &Progress, -) -> Result { - let lower = w.state.accounts[i].username.to_ascii_lowercase(); - let months = archives(&lower)?; - status.months_total.store(months.len(), Ordering::Relaxed); - status.months_done.store(0, Ordering::Relaxed); - for url in months { - status.months_done.fetch_add(1, Ordering::Relaxed); - // ".../games/2026/10" → "2026/10"; months before the last fetched are done. - let month = url.rsplitn(3, '/').take(2).collect::>(); - let month = format!( - "{}/{}", - month.get(1).unwrap_or(&""), - month.first().unwrap_or(&"") - ); - let a = &w.state.accounts[i]; - if a.chesscom_month.as_ref().is_some_and(|m| month < *m) { - continue; - } - if cancel.load(Ordering::Relaxed) { - return Ok(true); - } - let v = json(&url)?.ok_or_else(|| Failure::Unexpected(format!("{month}: not found")))?; - let games = v["games"] - .as_array() - .ok_or_else(|| Failure::Unexpected(format!("{month}: no games")))?; - let mut list: Vec<(i64, &str)> = games - .iter() - .filter(|g| g["rules"] == "chess") - .filter_map(|g| Some((g["end_time"].as_i64()?, g["pgn"].as_str()?))) - .collect(); - list.sort_by_key(|(t, _)| *t); - let a = &w.state.accounts[i]; - let same_month = a.chesscom_month.as_deref() == Some(month.as_str()); - let last = if same_month { - a.chesscom_last_end - } else { - None - }; - for (end, pgn) in list { - if last.is_some_and(|l| end <= l) { - continue; - } - w.game(pgn)?; - progress.fetch_add(1, Ordering::Relaxed); - status.games.fetch_add(1, Ordering::Relaxed); - w.state.accounts[i].chesscom_last_end = Some(end); - } - // The mark moves to this month even when it had no standard games (the end - // time then still belongs to an earlier month and is not compared). - w.state.accounts[i].chesscom_month = Some(month); - w.commit()?; - } - Ok(false) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn temp_dir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("cp-online-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); - std::fs::create_dir_all(&d).unwrap(); - d - } - - fn account(p: Platform, name: &str) -> Account { - Account { - platform: p, - username: name.into(), - games: None, - months: None, - } - } - - const GAME: &str = "[Event \"x\"]\n\n1. e4 e5 1-0"; - - #[test] - fn a_crash_leaves_no_duplicates() { - let dir = temp_dir("crash"); - let path = dir.join("db.pgn"); - let state = State { - accounts: vec![AccountState { - platform: Some(Platform::Lichess), - username: "a".into(), - ..AccountState::default() - }], - ..State::default() - }; - let mut w = Writer::open(&path, state).unwrap(); - w.game(GAME).unwrap(); - w.game(GAME).unwrap(); - w.commit().unwrap(); - let good = std::fs::read(&path).unwrap(); - // Games written after the last commit, then the process died. - w.game(GAME).unwrap(); - w.file.flush().unwrap(); - drop(w); - assert!(std::fs::read(&path).unwrap().len() > good.len()); - let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); - assert_eq!(w.state.games, 2); - drop(w); - assert_eq!(std::fs::read(&path).unwrap(), good, "cut back to the state"); - - // Somebody else changed the file: it is left alone. - let mut other = good.clone(); - other[0] = b' '; - other.extend_from_slice(GAME.as_bytes()); - std::fs::write(&path, &other).unwrap(); - let w = Writer::open(&path, State::load(&path).unwrap()).unwrap(); - drop(w); - assert_eq!(std::fs::read(&path).unwrap(), other); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn a_deleted_database_is_downloaded_again() { - let dir = temp_dir("deleted"); - let path = dir.join("db.pgn"); - let state = State { - accounts: vec![AccountState { - platform: Some(Platform::Lichess), - username: "a".into(), - lichess_last: Some(5), - ..AccountState::default() - }], - games: 7, - ..State::default() - }; - state.save(&path).unwrap(); - let never = AtomicBool::new(false); - // No account asked for: nothing fetched, only the state put right. - let d = download_to(&[], &path, &AtomicUsize::new(0), &never).unwrap(); - assert_eq!(d.total, 0); - let s = State::load(&path).unwrap_or_default(); - assert!(s.accounts.iter().all(|a| a.lichess_last.is_none())); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn one_download_per_database() { - let path = PathBuf::from("/nonexistent/cp-claim.pgn"); - let first = Claim::take(&path).expect("free"); - assert!(Claim::take(&path).is_none()); - let never = AtomicBool::new(false); - assert_eq!( - download_to(&[], &path, &AtomicUsize::new(0), &never), - Err(Failure::Busy) - ); - drop(first); - assert!(Claim::take(&path).is_some()); - } - - #[test] - fn names_of_merged_databases() { - let name = |a: &[Account]| { - combined_path(Path::new("/online"), a) - .unwrap() - .file_name() - .unwrap() - .to_string_lossy() - .into_owned() - }; - let li = account(Platform::Lichess, "Magnus"); - assert_eq!(name(std::slice::from_ref(&li)), "Magnus (Lichess).pgn"); - let cc = account(Platform::ChessCom, "magnus"); - assert_eq!(name(&[li.clone(), cc]), "Magnus (Lichess + Chess.com).pgn"); - let other = account(Platform::ChessCom, "MagnusCarlsen"); - assert_eq!( - name(&[li, other]), - "Magnus (Lichess) + MagnusCarlsen (Chess.com).pgn" - ); - } - - #[test] - fn unfinished_lichess_games_come_later() { - let mut a = AccountState::default(); - let g = |id: &'static str, playing: bool| LichessGame { - id, - created: 10, - playing, - standard: true, - pgn: (!playing).then_some("1. e4 *"), - }; - // First run: a correspondence game is still on, another one is over. - assert!(!lichess_keep(&mut a, &g("corr", true))); - assert!(lichess_keep(&mut a, &g("blitz", false))); - assert_eq!(a.lichess_pending, vec![("corr".to_owned(), 10)]); - // Asked about by id: still on, then over. - assert!(!lichess_keep(&mut a, &g("corr", true))); - assert_eq!(a.lichess_pending.len(), 1); - assert!(lichess_keep(&mut a, &g("corr", false))); - assert!(a.lichess_pending.is_empty()); - // A variant game is neither kept nor waited for. - let mut v = g("960", true); - v.standard = false; - assert!(!lichess_keep(&mut a, &v)); - assert!(a.lichess_pending.is_empty()); - // An unfinished game may come without its PGN, a finished one may not. - let json = |s: &str| serde_json::from_str::(s).unwrap(); - let on = json(r#"{"id":"a","createdAt":1,"status":"started"}"#); - assert!(lichess_game(&on).is_some_and(|g| g.playing)); - let over = json(r#"{"id":"a","createdAt":1,"status":"mate"}"#); - assert!(lichess_game(&over).is_none()); - } - - /// Against the real sites, with an account given by `CP_ONLINE_NICK` (kept out of - /// the repository): lookup, an interrupted Lichess download continued without gaps - /// or duplicates, a full Chess.com download, and an update that adds nothing. Run - /// with `CP_ONLINE_NICK= cargo test -p online-games online_live -- --ignored --nocapture`. - #[test] - #[ignore] - fn online_live() { - let Ok(nick) = std::env::var("CP_ONLINE_NICK") else { - eprintln!("skipped: no CP_ONLINE_NICK"); - return; - }; - assert_eq!(probe_all(), [true, true], "both platforms answer"); - assert_eq!( - lookup(Platform::Lichess, "no-such-player-cp-x9"), - Lookup::NotFound - ); - let dir = std::env::temp_dir().join(format!("cp-online-live-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let read_db = |path: &Path| { - let db = chess_core::PgnDatabase::open(path, &mut |_| {}, &AtomicBool::new(false)) - .expect("opens"); - let mut sites = Vec::new(); - let mut problems = 0; - for i in 0..db.len() { - let g = db.load_game(i).expect("game"); - problems += usize::from(!g.diagnostics.is_empty()); - let e = &db.entries()[i]; - let site = e.tag("Link").or_else(|| e.tag("Site")).unwrap_or_default(); - sites.push(site.to_owned()); - } - (db.len(), sites, problems) - }; - - // Lichess: stop after about 150 games, twice, then compare with what the - // site says about those games: no gaps, no duplicates. - let Lookup::Found(li) = lookup(Platform::Lichess, &nick) else { - panic!("not on Lichess"); - }; - let path = dir.join("li.pgn"); - for round in 1..=2 { - let progress = AtomicUsize::new(0); - let cancel = AtomicBool::new(false); - let over = AtomicBool::new(false); - let done = std::thread::scope(|s| { - s.spawn(|| { - while progress.load(Ordering::Relaxed) < 150 && !over.load(Ordering::Relaxed) { - std::thread::sleep(Duration::from_millis(50)); - } - cancel.store(true, Ordering::Relaxed); - }); - let r = download_to(std::slice::from_ref(&li), &path, &progress, &cancel); - over.store(true, Ordering::Relaxed); - r.expect("downloads") - }); - eprintln!("lichess round {round}: {done:?}"); - assert!(done.cancelled && done.added >= 150); - } - let (n, sites, problems) = read_db(&path); - let unique: std::collections::HashSet<_> = sites.iter().collect(); - assert_eq!(unique.len(), n, "no duplicates"); - assert_eq!(State::load(&path).unwrap().games as usize, n); - eprintln!("lichess: {n} games after two interrupted runs, {problems} with diagnostics"); - // The same games as one uninterrupted request for that many. - let (code, body) = get(&format!( - "https://lichess.org/api/games/user/{}?sort=dateAsc&finished=true&max={n}\ - &perfType=ultraBullet,bullet,blitz,rapid,classical,correspondence&moves=false", - li.username - )) - .expect("answers"); - assert_eq!(code, 200); - // Asked for JSON, Lichess answers one game per line. - let expected: Vec = body - .lines() - .filter_map(|l| serde_json::from_str::(l).ok()) - .filter_map(|v| Some(format!("https://lichess.org/{}", v["id"].as_str()?))) - .collect(); - // Ours are the reference's first games, in its order (the reference may hold a - // few more: Lichess does not count `max` exactly as we count games). - if expected.len() < sites.len() || sites[..] != expected[..sites.len()] { - let only_ours: Vec<_> = sites.iter().filter(|x| !expected.contains(x)).collect(); - let only_ref: Vec<_> = expected.iter().filter(|x| !sites.contains(x)).collect(); - let first = sites.iter().zip(&expected).position(|(a, b)| a != b); - panic!( - "differ: first at {first:?}, ours {} ref {}, only ours {only_ours:?}, only in the reference {only_ref:?}", - sites.len(), - expected.len() - ); - } - - // Chess.com: everything, then an update that finds nothing new. - let Lookup::Found(cc) = lookup(Platform::ChessCom, &nick) else { - panic!("not on Chess.com"); - }; - let path = dir.join("cc.pgn"); - let never = AtomicBool::new(false); - let done = download_to( - std::slice::from_ref(&cc), - &path, - &AtomicUsize::new(0), - &never, - ) - .expect("downloads"); - eprintln!("chess.com: {done:?}"); - assert!(!done.cancelled && done.total > 0); - let again = download_to( - std::slice::from_ref(&cc), - &path, - &AtomicUsize::new(0), - &never, - ) - .expect("updates"); - assert_eq!((again.added, again.total), (0, done.total)); - let (n, sites, problems) = read_db(&path); - assert_eq!(n as u64, done.total); - let unique: std::collections::HashSet<_> = sites.iter().collect(); - assert_eq!(unique.len(), n, "no duplicates"); - eprintln!("chess.com: {n} games, {problems} with diagnostics"); - - // Both into one database: Chess.com whole, then Lichess stopped twice; the - // second run adds Lichess games only, without duplicates. - let path = dir.join("both.pgn"); - let accounts = [cc.clone(), li.clone()]; - let mut totals = Vec::new(); - for round in 1..=2 { - let progress = AtomicUsize::new(0); - let cancel = AtomicBool::new(false); - let over = AtomicBool::new(false); - let goal = if round == 1 { - done.total as usize + 100 - } else { - 100 - }; - let d = std::thread::scope(|s| { - s.spawn(|| { - while progress.load(Ordering::Relaxed) < goal && !over.load(Ordering::Relaxed) { - std::thread::sleep(Duration::from_millis(50)); - } - cancel.store(true, Ordering::Relaxed); - }); - let r = download_to(&accounts, &path, &progress, &cancel); - over.store(true, Ordering::Relaxed); - r.expect("downloads") - }); - eprintln!("both, round {round}: {d:?}"); - assert!(d.cancelled); - totals.push(d.total); - } - let state = State::load(&path).unwrap(); - assert_eq!(state.accounts.len(), 2); - assert_eq!(state.accounts[0].platform, Some(Platform::ChessCom)); - assert!(state.accounts[0].chesscom_month.is_some()); - assert!(state.accounts[1].lichess_last.is_some()); - let (n, sites, problems) = read_db(&path); - assert_eq!(n as u64, totals[1]); - let unique: std::collections::HashSet<_> = sites.iter().collect(); - assert_eq!(unique.len(), n, "no duplicates"); - let chesscom = sites.iter().filter(|s| s.contains("chess.com")).count() as u64; - assert_eq!(chesscom, done.total, "all of Chess.com, once"); - eprintln!("both: {n} games ({chesscom} from Chess.com), {problems} with diagnostics"); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn probe_answers() { - let li: Value = serde_json::from_str( - r#"{"id":"lichess","username":"Lichess","count":{"all":0,"rated":0}}"#, - ) - .unwrap(); - assert!(probe_answer_ok(Platform::Lichess, &li)); - // A changed API (renamed or missing fields) is not offered. - let changed: Value = - serde_json::from_str(r#"{"id":"lichess","username":"Lichess","games":0}"#).unwrap(); - assert!(!probe_answer_ok(Platform::Lichess, &changed)); - let cc: Value = - serde_json::from_str(r#"{"player_id":41,"username":"erik","status":"staff"}"#).unwrap(); - assert!(probe_answer_ok(Platform::ChessCom, &cc)); - let html = Value::String("maintenance".into()); - assert!(!probe_answer_ok(Platform::ChessCom, &html)); - assert!(!probe_answer_ok(Platform::Lichess, &html)); - } - - #[test] - fn nicknames() { - assert!(valid_nick("Magnus_C-1")); - assert!(!valid_nick("a")); - assert!(!valid_nick("bad nick")); - assert!(!valid_nick("../etc")); - assert!(!valid_nick(&"x".repeat(31))); - } - - #[test] - fn state_round_trip() { - let dir = std::env::temp_dir().join(format!("cp-online-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let pgn = dir.join("Someone (Lichess).pgn"); - let s = State { - accounts: vec![AccountState { - platform: Some(Platform::Lichess), - username: "Someone".into(), - lichess_last: Some(1_700_000_000_000), - ..AccountState::default() - }], - games: 3, - ..State::default() - }; - s.save(&pgn).unwrap(); - assert_eq!(State::load(&pgn), Some(s)); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/openings/Cargo.toml b/crates/openings/Cargo.toml deleted file mode 100644 index d54a971..0000000 --- a/crates/openings/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "chess-openings" -description = "Opening names of ChessPenguin: the Lichess chess-openings table (CC0), looked up by position; also tells a book move" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[dependencies] -shakmaty.workspace = true -serde.workspace = true - -[dev-dependencies] -chess-import.workspace = true diff --git a/crates/openings/data/a.tsv b/crates/openings/data/a.tsv deleted file mode 100644 index 5610998..0000000 --- a/crates/openings/data/a.tsv +++ /dev/null @@ -1,824 +0,0 @@ -eco name pgn -A00 Amar Opening 1. Nh3 -A00 Amar Opening: Paris Gambit 1. Nh3 d5 2. g3 e5 3. f4 -A00 Amar Opening: Paris Gambit, Gent Gambit 1. Nh3 d5 2. g3 e5 3. f4 Bxh3 4. Bxh3 exf4 5. O-O fxg3 6. hxg3 -A00 Amsterdam Attack 1. e3 e5 2. c4 d6 3. Nc3 Nc6 4. b3 Nf6 -A00 Anderssen's Opening 1. a3 -A00 Anderssen's Opening: Polish Gambit 1. a3 a5 2. b4 -A00 Barnes Opening 1. f3 -A00 Barnes Opening: Fool's Mate 1. f3 e5 2. g4 Qh4# -A00 Barnes Opening: Gedult Gambit 1. f3 d5 2. e4 g6 3. d4 dxe4 4. c3 -A00 Barnes Opening: Gedult Gambit 1. f3 f5 2. e4 fxe4 3. Nc3 -A00 Barnes Opening: Hammerschlag 1. f3 e5 2. Kf2 -A00 Clemenz Opening 1. h3 -A00 Clemenz Opening: Spike Lee Gambit 1. h3 h5 2. g4 -A00 Creepy Crawly Formation: Classical Defense 1. h3 d5 2. a3 e5 -A00 Formation: Hippopotamus Attack 1. a3 e5 2. b3 d5 3. c3 Nf6 4. d3 Nc6 5. e3 Bd6 6. f3 O-O 7. g3 -A00 Formation: Shy Attack 1. a3 e5 2. g3 d5 3. Bg2 Nf6 4. d3 Nc6 5. Nd2 Bd6 6. e3 O-O 7. h3 -A00 Global Opening 1. h3 e5 2. a3 -A00 Grob Opening 1. g4 -A00 Grob Opening: Alessi Gambit 1. g4 f5 -A00 Grob Opening: Double Grob 1. g4 g5 -A00 Grob Opening: Double Grob, Coca-Cola Gambit 1. g4 g5 2. f4 -A00 Grob Opening: Grob Gambit 1. g4 d5 2. Bg2 -A00 Grob Opening: Grob Gambit Declined 1. g4 d5 2. Bg2 c6 -A00 Grob Opening: Grob Gambit, Basman Gambit 1. g4 d5 2. Bg2 h5 3. gxh5 -A00 Grob Opening: Grob Gambit, Fritz Gambit 1. g4 d5 2. Bg2 Bxg4 3. c4 -A00 Grob Opening: Grob Gambit, Fritz Gambit, Romford Countergambit 1. g4 d5 2. Bg2 Bxg4 3. c4 d4 4. Bxb7 Nd7 5. Bxa8 Qxa8 -A00 Grob Opening: Grob Gambit, Keres Gambit 1. g4 d5 2. Bg2 e5 3. d4 exd4 4. c3 -A00 Grob Opening: Grob Gambit, Richter-Grob Gambit 1. g4 d5 2. Bg2 c6 3. c4 dxc4 4. b3 -A00 Grob Opening: Keene Defense 1. g4 d5 2. h3 e5 3. Bg2 c6 -A00 Grob Opening: Keene Defense, Main Line 1. g4 d5 2. h3 e5 3. Bg2 c6 4. d4 e4 5. c4 Bd6 6. Nc3 Ne7 -A00 Grob Opening: London Defense 1. g4 e5 2. h3 Nc6 -A00 Grob Opening: Romford Countergambit 1. g4 d5 2. Bg2 Bxg4 3. c4 d4 -A00 Grob Opening: Spike Attack 1. g4 d5 2. Bg2 c6 3. g5 -A00 Grob Opening: Spike, Hurst Attack 1. g4 e5 2. Bg2 d5 3. c4 -A00 Grob Opening: Zilbermints Gambit 1. g4 d5 2. e4 dxe4 3. Nc3 -A00 Grob Opening: Zilbermints Gambit, Schiller Defense 1. g4 d5 2. e4 dxe4 3. Nc3 h5 -A00 Grob Opening: Zilbermints Gambit, Zilbermints-Hartlaub Gambit 1. g4 d5 2. e4 dxe4 3. Nc3 e5 4. d3 -A00 Hungarian Opening 1. g3 -A00 Hungarian Opening: Asten Gambit 1. g3 Nc6 2. Nc3 d5 3. d4 e5 4. dxe5 d4 5. Ne4 f5 -A00 Hungarian Opening: Burk Gambit 1. g3 e5 2. a3 d5 3. Nf3 e4 4. Nh4 Be7 5. d3 -A00 Hungarian Opening: Bücker Gambit 1. g3 d5 2. Bg2 e5 3. b4 -A00 Hungarian Opening: Catalan Formation 1. g3 d5 2. Bg2 e6 -A00 Hungarian Opening: Dutch Defense 1. g3 f5 -A00 Hungarian Opening: Indian Defense 1. g3 Nf6 -A00 Hungarian Opening: Myers Defense 1. g3 g5 -A00 Hungarian Opening: Pachman Gambit 1. g3 f5 2. e4 fxe4 3. Qh5+ g6 -A00 Hungarian Opening: Paris Gambit 1. g3 e5 2. Nh3 d5 3. f4 Bxh3 4. Bxh3 exf4 5. O-O -A00 Hungarian Opening: Reversed Alekhine 1. g3 e5 2. Nf3 -A00 Hungarian Opening: Reversed Brooklyn Defense, Brooklyn Benko Gambit 1. g3 e5 2. Nf3 e4 3. Ng1 Nf6 4. b4 -A00 Hungarian Opening: Reversed Modern Defense 1. g3 d5 2. Bg2 c5 -A00 Hungarian Opening: Reversed Norwegian Defense 1. g3 e5 2. Nf3 e4 3. Nh4 -A00 Hungarian Opening: Sicilian Invitation 1. g3 c5 -A00 Hungarian Opening: Slav Formation 1. g3 d5 2. Bg2 c6 -A00 Hungarian Opening: Symmetrical Variation 1. g3 g6 -A00 Hungarian Opening: Van Kuijk Gambit 1. g3 h5 2. Nf3 h4 -A00 Hungarian Opening: Winterberg Gambit 1. g3 d5 2. Bg2 e5 3. c4 dxc4 4. b3 -A00 Kádas Opening 1. h4 -A00 Kádas Opening: Beginner's Trap 1. h4 d5 2. Rh3 -A00 Kádas Opening: Koola-Koola Variation 1. h4 a5 -A00 Kádas Opening: Kádas Gambit 1. h4 c5 2. b4 -A00 Kádas Opening: Kádas Gambit 1. h4 d5 2. d4 c5 3. Nf3 cxd4 4. c3 -A00 Kádas Opening: Kádas Gambit 1. h4 e5 2. d4 exd4 3. c3 -A00 Kádas Opening: Myers Variation 1. h4 d5 2. d4 c5 3. e4 -A00 Kádas Opening: Schneider Gambit 1. h4 g5 -A00 Kádas Opening: Steinbok Gambit 1. h4 f5 2. e4 fxe4 3. d3 -A00 Lasker Simul Special 1. g3 h5 -A00 Mieses Opening 1. d3 -A00 Mieses Opening: Myers Spike Attack 1. d3 g6 2. g4 -A00 Mieses Opening: Reversed Rat 1. d3 e5 -A00 Mieses Opening: Venezolana Variation 1. d3 c5 2. Nc3 Nc6 3. g3 -A00 Polish Opening 1. b4 -A00 Polish Opening, with d5 1. b4 d5 -A00 Polish Opening, with d5 1. b4 d5 2. Bb2 Nf6 3. Nf3 -A00 Polish Opening: Baltic Defense 1. b4 d5 2. Bb2 Bf5 -A00 Polish Opening: Birmingham Gambit 1. b4 c5 -A00 Polish Opening: Bugayev Advance Variation 1. b4 e5 2. Bb2 f6 3. b5 -A00 Polish Opening: Bugayev Attack 1. b4 e5 2. a3 -A00 Polish Opening: Czech Defense 1. b4 e5 2. Bb2 d6 -A00 Polish Opening: Dutch Defense 1. b4 f5 -A00 Polish Opening: German Defense 1. b4 d5 2. Bb2 Qd6 -A00 Polish Opening: Grigorian Variation 1. b4 Nc6 -A00 Polish Opening: Karniewski Variation 1. b4 Nh6 -A00 Polish Opening: King's Indian Variation 1. b4 Nf6 2. Bb2 g6 -A00 Polish Opening: King's Indian Variation, Schiffler Attack 1. b4 Nf6 2. Bb2 g6 3. e4 -A00 Polish Opening: King's Indian Variation, Sokolsky Attack 1. b4 Nf6 2. Bb2 g6 3. c4 Bg7 4. e3 d6 5. Nf3 O-O 6. d4 -A00 Polish Opening: Myers Variation 1. b4 d5 2. Bb2 c6 3. a4 -A00 Polish Opening: Outflank Variation 1. b4 c6 -A00 Polish Opening: Outflank Variation, Schuehler Gambit 1. b4 c6 2. Bb2 a5 3. b5 -A00 Polish Opening: Queen's Indian Variation 1. b4 e6 2. Bb2 Nf6 3. b5 b6 -A00 Polish Opening: Queenside Defense 1. b4 e6 2. Bb2 Nf6 3. b5 a6 -A00 Polish Opening: Rooks Swap Line 1. b4 e6 2. Bb2 Nf6 3. b5 a6 4. a4 axb5 5. axb5 Rxa1 6. Bxa1 -A00 Polish Opening: Schiffler-Sokolsky Variation 1. b4 e6 2. Bb2 Nf6 3. b5 d5 4. e3 -A00 Polish Opening: Schuehler Gambit 1. b4 c6 2. Bb2 a5 3. b5 cxb5 4. e4 -A00 Polish Opening: Symmetrical Variation 1. b4 b5 -A00 Polish Opening: Tartakower Gambit 1. b4 e5 2. Bb2 f6 3. e4 -A00 Polish Opening: Wolferts Gambit 1. b4 e5 2. Bb2 c5 -A00 Saragossa Opening 1. c3 -A00 Sodium Attack 1. Na3 -A00 Sodium Attack: Celadon Variation 1. Na3 e5 2. d3 Bxa3 3. bxa3 d5 4. e3 c5 5. Rb1 -A00 Sodium Attack: Chenoboskion Variation 1. Na3 g6 2. g4 -A00 Sodium Attack: Durkin Gambit 1. Na3 e5 2. Nc4 Nc6 3. e4 f5 -A00 Valencia Opening 1. d3 e5 2. Nd2 -A00 Van Geet Opening 1. Nc3 -A00 Van Geet Opening: Battambang Variation 1. a3 e5 2. Nc3 -A00 Van Geet Opening: Billockus-Johansen Gambit 1. Nc3 e5 2. Nf3 Bc5 -A00 Van Geet Opening: Damhaug Gambit 1. Nc3 d5 2. f4 e5 -A00 Van Geet Opening: Dougherty Gambit 1. Nc3 d5 2. e4 dxe4 3. f3 -A00 Van Geet Opening: Dunst-Perrenet Gambit 1. Nc3 d5 2. e4 dxe4 3. d3 -A00 Van Geet Opening: Düsseldorf Gambit 1. Nc3 c5 2. b4 -A00 Van Geet Opening: Gladbacher Gambit 1. Nc3 e5 2. b3 d5 3. e4 dxe4 4. d3 -A00 Van Geet Opening: Hector Gambit 1. Nc3 d5 2. e4 dxe4 3. Bc4 -A00 Van Geet Opening: Hergert Gambit 1. Nc3 d6 2. f4 e5 3. fxe5 Nc6 -A00 Van Geet Opening: Hulsemann Gambit 1. Nc3 e5 2. e3 d5 3. Qh5 Be6 -A00 Van Geet Opening: Jendrossek Gambit 1. Nc3 d5 2. f4 d4 3. Ne4 f5 4. Nf2 Nf6 5. Nf3 c5 6. b4 -A00 Van Geet Opening: Kluever Gambit 1. Nc3 f5 2. e4 fxe4 3. d3 -A00 Van Geet Opening: Laroche Gambit 1. Nc3 b5 -A00 Van Geet Opening: Liebig Gambit 1. Nc3 e5 2. e3 d5 3. Qh5 Nf6 -A00 Van Geet Opening: Melleby Gambit 1. Nc3 d5 2. f4 d4 3. Ne4 c5 -A00 Van Geet Opening: Myers Attack 1. Nc3 g6 2. h4 -A00 Van Geet Opening: Napoleon Attack 1. Nc3 e5 2. Nf3 Nc6 3. d4 -A00 Van Geet Opening: Novosibirsk Variation 1. Nc3 c5 2. d4 cxd4 3. Qxd4 Nc6 4. Qh4 -A00 Van Geet Opening: Nowokunski Gambit 1. Nc3 e5 2. f4 exf4 3. e4 -A00 Van Geet Opening: Pfeiffer Gambit 1. Nc3 d5 2. f4 d4 3. Ne4 e5 -A00 Van Geet Opening: Pfeiffer Gambit, Sleipnir Countergambit 1. Nc3 d5 2. f4 d4 3. Ne4 e5 4. Nf3 -A00 Van Geet Opening: Reversed Nimzowitsch 1. Nc3 e5 -A00 Van Geet Opening: Reversed Scandinavian 1. Nc3 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qa4 -A00 Van Geet Opening: Sicilian Two Knights 1. Nc3 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 -A00 Van Geet Opening: Sleipnir Gambit 1. Nc3 d5 2. e3 e5 3. d4 Bb4 -A00 Van Geet Opening: Twyble Attack 1. Nc3 c5 2. Rb1 -A00 Van Geet Opening: Tübingen Gambit 1. Nc3 Nf6 2. g4 -A00 Van Geet Opening: Venezolana Variation 1. Nc3 d5 2. d3 Nf6 3. g3 -A00 Van Geet Opening: Warsteiner Gambit 1. Nc3 d5 2. f4 g5 -A00 Van't Kruijs Opening 1. e3 -A00 Van't Kruijs Opening: Bouncing Bishop Variation 1. e3 e5 2. Bc4 b5 3. Bb3 -A00 Van't Kruijs Opening: Keoni-Hiva Gambit, Akahi Variation 1. e3 e5 2. Nc3 Nf6 3. f4 exf4 4. Nf3 -A00 Van't Kruijs Opening: Keoni-Hiva Gambit, Alua Variation 1. e3 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 -A00 Van't Kruijs Opening: Keoni-Hiva Gambit, Ekolu Variation 1. e3 e5 2. Nc3 d5 3. f4 exf4 4. Nf3 -A00 Ware Opening 1. a4 -A00 Ware Opening: Cologne Gambit 1. a4 b6 2. d4 d5 3. Nc3 Nd7 -A00 Ware Opening: Crab Variation 1. a4 e5 2. h4 -A00 Ware Opening: Meadow Hay Trap 1. a4 e5 2. Ra3 -A00 Ware Opening: Symmetric Variation 1. a4 a5 -A00 Ware Opening: Ware Gambit 1. a4 e5 2. a5 d5 3. e3 f5 4. a6 -A00 Ware Opening: Wing Gambit 1. a4 b5 2. axb5 Bb7 -A01 Nimzo-Larsen Attack 1. b3 -A01 Nimzo-Larsen Attack: Classical Variation 1. b3 d5 -A01 Nimzo-Larsen Attack: Dutch Variation 1. b3 f5 -A01 Nimzo-Larsen Attack: English Variation 1. b3 c5 -A01 Nimzo-Larsen Attack: Graz Attack 1. b3 d5 2. Ba3 -A01 Nimzo-Larsen Attack: Indian Variation 1. b3 Nf6 -A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 -A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 2. Bb2 Nc6 -A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 2. Bb2 Nc6 3. e3 -A01 Nimzo-Larsen Attack: Modern Variation 1. b3 e5 2. Bb2 Nc6 3. c4 Nf6 -A01 Nimzo-Larsen Attack: Pachman Gambit 1. b3 e5 2. Bb2 Nc6 3. f4 -A01 Nimzo-Larsen Attack: Polish Variation 1. b3 b5 -A01 Nimzo-Larsen Attack: Ringelbach Gambit 1. b3 f5 2. Bb2 e6 3. e4 -A01 Nimzo-Larsen Attack: Spike Variation 1. b3 Nf6 2. Bb2 g6 3. g4 -A01 Nimzo-Larsen Attack: Symmetrical Variation 1. b3 b6 -A02 Bird Opening 1. f4 -A02 Bird Opening: Batavo-Polish Attack 1. f4 Nf6 2. Nf3 g6 3. b4 -A02 Bird Opening: Double Duck Formation 1. f4 f5 2. d4 d5 -A02 Bird Opening: From's Gambit 1. f4 e5 -A02 Bird Opening: From's Gambit, Bahr Gambit 1. f4 e5 2. Nc3 -A02 Bird Opening: From's Gambit, Langheld Gambit 1. f4 e5 2. fxe5 d6 3. exd6 Nf6 -A02 Bird Opening: From's Gambit, Lasker Variation 1. f4 e5 2. fxe5 d6 3. exd6 Bxd6 4. Nf3 g5 -A02 Bird Opening: From's Gambit, Lipke Variation 1. f4 e5 2. fxe5 d6 3. exd6 Bxd6 4. Nf3 Nh6 5. d4 -A02 Bird Opening: Hobbs Gambit 1. f4 g5 -A02 Bird Opening: Hobbs-Zilbermints Gambit 1. f4 h6 2. Nf3 g5 -A02 Bird Opening: Horsefly Defense 1. f4 Nh6 -A02 Bird Opening: Lasker Gambit 1. f4 e5 2. fxe5 f6 -A02 Bird Opening: Mujannah 1. f4 Nf6 2. c4 -A02 Bird Opening: Myers Defense 1. f4 b5 -A02 Bird Opening: Platz Gambit 1. f4 e5 2. fxe5 Ne7 -A02 Bird Opening: Schlechter Gambit 1. f4 e5 2. fxe5 Nc6 -A02 Bird Opening: Siegener Gambit 1. f4 e5 2. d4 exd4 3. Nf3 c5 4. c3 -A02 Bird Opening: Swiss Gambit 1. f4 f5 2. e4 fxe4 3. Nc3 Nf6 4. g4 -A02 Bird Opening: Wagner-Zwitersch Gambit 1. f4 f5 2. e4 -A03 Bird Opening: Dutch Variation 1. f4 d5 -A03 Bird Opening: Dutch Variation, Dudweiler Gambit 1. f4 d5 2. g4 -A03 Bird Opening: Lasker Variation 1. f4 d5 2. Nf3 Nf6 3. e3 c5 -A03 Bird Opening: Sturm Gambit 1. f4 d5 2. c4 -A03 Bird Opening: Thomas Gambit 1. f4 d5 2. b3 Nf6 3. Bb2 d4 4. Nf3 c5 5. e3 -A03 Bird Opening: Williams Gambit 1. f4 d5 2. e4 -A03 Bird Opening: Williams Gambit 1. f4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Qe2 -A03 Bird Opening: Williams-Zilbermints Gambit 1. f4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Nge2 -A04 Colle System: Rhamphorhynchus Variation 1. Nf3 c5 2. e3 g6 3. d4 Bg7 4. dxc5 Qa5+ -A04 Modern Defense: Semi-Averbakh Variation, Polish Variation 1. Nf3 c5 2. c4 g6 3. d4 Bg7 4. e4 Qb6 -A04 Modern Defense: Semi-Averbakh Variation, Pterodactyl Variation 1. Nf3 c5 2. c4 g6 3. d4 Bg7 4. e4 Qa5+ -A04 Modern Defense: Semi-Averbakh Variation, Pterodactyl Variation Accepted 1. Nf3 g6 2. d4 Bg7 3. e4 d6 4. c4 c5 5. dxc5 Qa5+ -A04 Zukertort Defense: Kingside Variation 1. Nf3 Nh6 2. d4 g6 -A04 Zukertort Defense: Sicilian Knight Variation 1. Nf3 Na6 2. e4 c5 -A04 Zukertort Opening 1. Nf3 -A04 Zukertort Opening: Arctic Defense 1. Nf3 f6 -A04 Zukertort Opening: Arctic Defense, Drunken Knight Variation 1. Nf3 f6 2. e4 Nh6 3. d4 Nf7 -A04 Zukertort Opening: Basman Defense 1. Nf3 h6 -A04 Zukertort Opening: Black Mustang Defense 1. Nf3 Nc6 -A04 Zukertort Opening: Drunken Cavalry Variation 1. Nf3 Na6 2. e4 Nh6 -A04 Zukertort Opening: Dutch Variation 1. Nf3 f5 -A04 Zukertort Opening: Herrstrom Gambit 1. Nf3 g5 -A04 Zukertort Opening: Kingside Fianchetto 1. Nf3 g6 -A04 Zukertort Opening: Lisitsyn Gambit 1. Nf3 f5 2. e4 -A04 Zukertort Opening: Lisitsyn Gambit Deferred 1. Nf3 f5 2. d3 Nf6 3. e4 -A04 Zukertort Opening: Pirc Invitation 1. Nf3 d6 -A04 Zukertort Opening: Polish Defense 1. Nf3 b5 -A04 Zukertort Opening: Queen's Gambit Invitation 1. Nf3 e6 -A04 Zukertort Opening: Queenside Fianchetto Variation 1. Nf3 b6 -A04 Zukertort Opening: Ross Gambit 1. Nf3 e5 -A04 Zukertort Opening: Shabalov Gambit 1. Nf3 e6 2. c4 a6 3. Nc3 c5 4. g3 b5 -A04 Zukertort Opening: Sicilian Invitation 1. Nf3 c5 -A04 Zukertort Opening: Slav Invitation 1. Nf3 c6 -A04 Zukertort Opening: Speelsmet Gambit 1. Nf3 c5 2. d4 cxd4 3. e3 -A04 Zukertort Opening: St. George Defense 1. Nf3 a6 -A04 Zukertort Opening: The Walrus 1. Nf3 e5 2. Nxe5 Nc6 3. Nxc6 dxc6 -A04 Zukertort Opening: Vos Gambit 1. Nf3 d6 2. d4 e5 -A04 Zukertort Opening: Wade Defense 1. Nf3 d6 2. e4 Bg4 -A04 Zukertort Opening: Ware Defense 1. Nf3 a5 -A05 King's Indian Attack 1. Nf3 Nf6 2. g3 d5 -A05 King's Indian Attack: Smyslov Variation 1. Nf3 Nf6 2. g3 g6 3. b4 -A05 King's Indian Attack: Spassky Variation 1. Nf3 Nf6 2. g3 b5 -A05 King's Indian Attack: Symmetrical Defense 1. Nf3 Nf6 2. g3 g6 -A05 King's Indian Attack: Wahls Defense 1. Nf3 Nf6 2. g3 g6 3. Bg2 Bg7 4. O-O O-O 5. d3 d5 -A05 Polish Opening: Zukertort System 1. Nf3 Nf6 2. b4 g6 3. Bb2 -A05 Zukertort Opening 1. Nf3 Nf6 -A05 Zukertort Opening 1. Nf3 Nf6 2. Nc3 Nc6 -A05 Zukertort Opening: Double Fianchetto Attack 1. Nf3 Nf6 2. g3 g6 3. b3 Bg7 4. Bb2 O-O 5. Bg2 d6 6. O-O -A05 Zukertort Opening: Lemberger Gambit 1. Nf3 Nf6 2. e4 -A05 Zukertort Opening: Myers Polish Attack 1. Nf3 Nf6 2. a4 g6 3. b4 -A05 Zukertort Opening: Nimzo-Larsen Variation 1. Nf3 Nf6 2. b3 -A05 Zukertort Opening: Quiet System 1. Nf3 Nf6 2. e3 -A06 Nimzo-Larsen Attack: Classical Variation 1. Nf3 d5 2. b3 -A06 Nimzo-Larsen Attack: Norfolk Gambit 1. Nf3 d5 2. b3 c5 3. e4 -A06 Nimzo-Larsen Attack: Norfolk Gambit 1. Nf3 d5 2. b3 Nf6 3. Bb2 c5 4. e4 -A06 Zukertort Opening 1. Nf3 d5 -A06 Zukertort Opening: Ampel Variation 1. Nf3 d5 2. Rg1 -A06 Zukertort Opening: Old Indian Attack 1. Nf3 d5 2. d3 -A06 Zukertort Opening: Pachman Gambit 1. Nf3 d5 2. e3 c5 3. c4 dxc4 4. b3 -A06 Zukertort Opening: Regina-Nu Gambit 1. Nf3 d5 2. b3 c5 3. c4 dxc4 4. Nc3 -A06 Zukertort Opening: Reversed Mexican Defense 1. Nf3 d5 2. Nc3 -A06 Zukertort Opening: Santasiere's Folly 1. b4 d5 2. Nf3 -A06 Zukertort Opening: Tennison Gambit 1. e4 d5 2. Nf3 -A06 Zukertort Opening: Tennison Gambit, Brigg's Trap 1. e4 d5 2. Nf3 dxe4 3. Ng5 Nf6 4. Nc3 Bf5 5. Qe2 Qd4 -A06 Zukertort Opening: The Potato 1. Nf3 d5 2. a4 -A07 Hungarian Opening: Wiedenhagen-Beta Gambit 1. g3 d5 2. Nf3 g5 -A07 King's Indian Attack 1. Nf3 d5 2. g3 -A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 -A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 h6 -A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 h6 6. c4 dxc4 -A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 e6 6. Nbd2 -A07 King's Indian Attack, with Bf5 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 e6 6. Nh4 -A07 King's Indian Attack, with e6 1. Nf3 Nf6 2. g3 d5 3. Bg2 e6 -A07 King's Indian Attack, with e6 1. Nf3 Nf6 2. g3 d5 3. Bg2 e6 4. O-O Be7 -A07 King's Indian Attack: Double Fianchetto 1. Nf3 d5 2. g3 g6 -A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 Bg4 -A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 Bg4 3. Bg2 Nd7 -A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 c6 3. Bg2 Bg4 4. O-O Nd7 -A07 King's Indian Attack: Keres Variation 1. Nf3 d5 2. g3 c6 3. Bg2 Bg4 4. O-O Nd7 5. d4 Ngf6 6. c4 e6 7. cxd5 exd5 8. Nc3 Bd6 -A07 King's Indian Attack: Omega-Delta Gambit 1. Nf3 d5 2. g3 e5 -A07 King's Indian Attack: Pachman System 1. Nf3 d5 2. g3 g6 3. Bg2 Bg7 4. O-O e5 5. d3 Ne7 -A07 King's Indian Attack: Sicilian Variation 1. Nf3 d5 2. g3 c5 -A07 King's Indian Attack: Yugoslav Variation 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bg4 -A07 King's Indian Attack: Yugoslav Variation 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 b6 5. O-O -A08 King's Indian Attack: French Variation 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 -A08 King's Indian Attack: Sicilian Variation 1. e4 e6 2. d3 d5 3. Nd2 Nf6 4. Ngf3 c5 5. g3 Nc6 6. Bg2 Be7 7. O-O O-O 8. Re1 -A08 King's Indian Attack: Sicilian Variation 1. Nf3 d5 2. g3 c5 3. Bg2 -A08 King's Indian Attack: Sicilian Variation 1. Nf3 d5 2. g3 c5 3. Bg2 Nf6 4. O-O e6 5. d3 -A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 -A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 Nf6 -A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 Nf6 5. O-O -A08 Zukertort Opening: Reversed Grünfeld 1. Nf3 d5 2. g3 c5 3. Bg2 Nc6 4. d4 e6 5. O-O -A09 Réti Opening 1. Nf3 d5 2. c4 -A09 Réti Opening: Advance Variation 1. Nf3 d5 2. c4 d4 -A09 Réti Opening: Advance Variation, Michel Gambit 1. Nf3 d5 2. c4 d4 3. b4 c5 -A09 Réti Opening: Advance Variation, Navara Gambit 1. Nf3 d5 2. c4 d4 3. b4 g5 -A09 Réti Opening: Penguin Variation 1. Nf3 d5 2. c4 d4 3. Rg1 -A09 Réti Opening: Reversed Blumenfeld Gambit 1. Nf3 d5 2. c4 d4 3. e3 c5 4. b4 -A09 Réti Opening: Réti Accepted 1. Nf3 d5 2. c4 dxc4 -A09 Réti Opening: Réti Gambit, Keres Variation 1. Nf3 d5 2. c4 dxc4 3. e3 Be6 -A09 Réti Opening: Zilbermints Gambit 1. Nf3 d5 2. c4 b5 -A10 English Opening 1. c4 -A10 English Opening: Achilles-Omega Gambit 1. c4 Nf6 2. e4 -A10 English Opening: Adorjan Defense 1. c4 g6 2. e4 e5 -A10 English Opening: Anglo-Dutch Defense 1. c4 f5 -A10 English Opening: Anglo-Dutch Defense, Hickmann Gambit 1. c4 f5 2. e4 -A10 English Opening: Anglo-Dutch Variation, Chabanon Gambit 1. c4 f5 2. Nf3 d6 3. e4 -A10 English Opening: Anglo-Dutch Variation, Ferenc Gambit 1. c4 f5 2. Nc3 Nf6 3. e4 -A10 English Opening: Anglo-Lithuanian Variation 1. c4 Nc6 -A10 English Opening: Anglo-Scandinavian Defense 1. c4 d5 -A10 English Opening: Anglo-Scandinavian Defense, Löhn Gambit 1. c4 d5 2. cxd5 e6 -A10 English Opening: Anglo-Scandinavian Defense, Malvinas Variation 1. c4 d5 2. cxd5 Qxd5 3. Nc3 Qa5 -A10 English Opening: Anglo-Scandinavian Defense, Schulz Gambit 1. c4 d5 2. cxd5 Nf6 -A10 English Opening: Great Snake Variation 1. c4 g6 -A10 English Opening: Jaenisch Gambit 1. c4 b5 -A10 English Opening: King's English Variation, Botvinnik System, Prickly Pawn Pass System 1. c4 g6 2. Nc3 Bg7 3. g3 Nf6 4. Bg2 O-O 5. e4 d6 6. Nge2 e5 7. O-O c6 8. d3 a6 -A10 English Opening: Myers Defense 1. c4 g5 -A10 English Opening: Myers Gambit 1. c4 g5 2. d4 Bg7 -A10 English Opening: Porcupine Variation 1. c4 f5 2. Nc3 Nf6 3. e4 fxe4 4. g4 -A10 English Opening: Wade Gambit 1. c4 f5 2. g4 -A10 English Opening: Zilbermints Gambit 1. c4 g5 2. d4 e5 -A11 English Opening: Caro-Kann Defensive System 1. c4 c6 -A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 -A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Qc2 -A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Nc3 Nbd7 5. Qc2 -A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Nc3 Nbd7 5. b3 e5 -A11 Réti Opening: Anglo-Slav Variation, Gurevich System 1. c4 c6 2. Nf3 d5 3. e3 Nf6 4. Nc3 e6 5. b3 Bd6 -A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. b3 g6 -A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 -A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 dxc4 -A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Bf5 -A11 Réti Opening: Anglo-Slav Variation, with g3 1. c4 c6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Bf5 5. O-O e6 6. d3 -A11 Réti Opening: Anglo-Slav Variation, with g3 1. Nf3 Nf6 2. g3 d5 3. Bg2 c6 4. O-O Bf5 5. d3 h6 6. c4 e6 -A12 Réti Opening: Anglo-Slav Variation 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 -A12 Réti Opening: Anglo-Slav Variation, Bled Variation 1. Nf3 d5 2. b3 Nf6 3. Bb2 g6 4. c4 c6 -A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 -A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 Bg4 -A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 Bf5 -A12 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation 1. Nf3 d5 2. c4 c6 3. b3 Bf5 4. Bb2 -A12 Réti Opening: Anglo-Slav Variation, Capablanca Variation 1. c4 Nf6 2. Nf3 c6 3. b3 d5 4. Bb2 Bg4 -A12 Réti Opening: Anglo-Slav Variation, Capablanca Variation 1. c4 Nf6 2. Nf3 c6 3. b3 d5 4. Bb2 Bg4 5. e3 -A12 Réti Opening: Anglo-Slav Variation, Capablanca Variation 1. c4 Nf6 2. Nf3 c6 3. b3 d5 4. Bb2 Bg4 5. d3 -A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 -A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 5. Bg2 -A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 5. Bg2 e6 6. Bb2 -A12 Réti Opening: Anglo-Slav Variation, London Defensive System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bf5 5. Bb2 -A12 Réti Opening: Anglo-Slav Variation, New York System 1. Nf3 Nf6 2. c4 c6 3. b3 d5 4. Bb2 Bf5 -A12 Réti Opening: Anglo-Slav Variation, New York System 1. Nf3 Nf6 2. c4 c6 3. b3 d5 4. Bb2 Bf5 5. e3 -A12 Réti Opening: Anglo-Slav Variation, New York System 1. Nf3 Nf6 2. c4 c6 3. b3 d5 4. Bb2 Bf5 5. d3 -A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 -A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 5. Bg2 -A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 5. Bg2 e6 6. Bb2 -A12 Réti Opening: Anglo-Slav Variation, Torre System 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 Bg4 5. Bb2 -A12 Réti Opening: Anglo-Slav Variation, with dxc4 1. c4 Nf6 2. g3 c6 3. Nf3 d5 4. b3 dxc4 -A13 English Opening: Agincourt Defense 1. c4 e6 -A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 -A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 d5 -A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 d5 3. b3 Nf6 4. Bb2 Be7 5. e3 O-O -A13 English Opening: Agincourt Defense 1. c4 e6 2. Nf3 d5 3. b3 Nf6 4. Bb2 Be7 5. e3 O-O 6. d4 -A13 English Opening: Agincourt Defense, Bogoljubow Defense 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Bd6 -A13 English Opening: Agincourt Defense, Catalan Defense 1. c4 e6 2. Nf3 d5 3. g3 b6 4. Bg2 Bb7 5. O-O -A13 English Opening: Agincourt Defense, Catalan Defense 1. c4 e6 2. Nf3 d5 3. g3 c5 -A13 English Opening: Agincourt Defense, Catalan Defense Accepted 1. c4 e6 2. Nf3 Nf6 3. g3 d5 4. Bg2 dxc4 -A13 English Opening: Agincourt Defense, Catalan Defense, Semi-Slav Defense 1. c4 e6 2. Nf3 Nf6 3. g3 d5 4. Bg2 c6 -A13 English Opening: Agincourt Defense, Kurajica Defense 1. c4 e6 2. Nf3 d5 3. g3 c6 -A13 English Opening: Agincourt Defense, Tarrasch Defense 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 c5 5. b3 Nc6 6. O-O Be7 -A13 English Opening: Agincourt Defense, Wimpy System 1. c4 e6 2. Nf3 Nf6 3. b3 d5 4. Bb2 c5 5. e3 -A13 English Opening: Neo-Catalan 1. c4 e6 2. Nf3 d5 3. g3 Nf6 -A13 English Opening: Neo-Catalan Declined 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 -A13 English Opening: Romanishin Gambit 1. c4 Nf6 2. Nf3 e6 3. g3 a6 4. Bg2 b5 -A14 English Opening: Agincourt Defense, Keres Defense 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. O-O c5 6. cxd5 Nxd5 7. Nc3 Nc6 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. O-O -A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. O-O O-O 6. b3 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 7. e3 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 7. e3 d4 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined 1. Nf3 d5 2. g3 Nf6 3. Bg2 e6 4. O-O Be7 5. c4 O-O 6. b3 c5 7. e3 Nc6 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined, Early b3 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. b3 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined, Early b3 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. b3 b6 -A14 English Opening: Agincourt Defense, Neo-Catalan Declined, Early b3 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. b3 c5 -A14 Réti Opening: Anglo-Slav Variation 1. Nf3 d5 2. c4 c6 3. g3 Nf6 4. Bg2 e6 5. b3 Be7 6. Bb2 -A14 Réti Opening: Anglo-Slav Variation, Bogoljubow Variation, Stonewall Line 1. Nf3 d5 2. c4 e6 3. g3 Nf6 4. Bg2 Be7 5. O-O O-O 6. b3 c6 7. Bb2 -A15 English Opening: Anglo-Indian Defense 1. c4 Nf6 -A15 English Opening: Anglo-Indian Defense, Anti-Anti-Grünfeld 1. c4 Nf6 2. Nc3 g6 3. Nf3 Bg7 4. e4 -A15 English Opening: Anglo-Indian Defense, Grünfeld Formation 1. c4 Nf6 2. Nf3 g6 3. g3 d5 -A15 English Opening: Anglo-Indian Defense, King's Indian Formation 1. c4 Nf6 2. Nf3 g6 -A15 English Opening: Anglo-Indian Defense, King's Indian Formation, Double Fianchetto 1. c4 Nf6 2. Nf3 g6 3. g3 b6 4. Bg2 Bb7 -A15 English Opening: Anglo-Indian Defense, King's Knight Variation 1. c4 Nf6 2. Nf3 -A15 English Opening: Anglo-Indian Defense, Old Indian Formation 1. c4 Nf6 2. Nf3 d6 -A15 English Opening: Anglo-Indian Defense, Queen's Indian Formation 1. c4 Nf6 2. Nf3 b6 -A15 English Opening: Anglo-Indian Defense, Queen's Indian Formation 1. c4 e6 2. Nf3 Nf6 3. g3 b6 4. Bg2 Bb7 -A15 English Opening: Anglo-Indian Defense, Romanishin Variation 1. c4 e6 2. Nf3 Nf6 3. g3 a6 -A15 English Opening: Anglo-Indian Defense, Scandinavian Defense 1. c4 Nf6 2. Nf3 d5 -A15 English Opening: Anglo-Indian Defense, Scandinavian Defense, Exchange Variation 1. c4 Nf6 2. Nf3 d5 3. cxd5 Nxd5 -A15 English Opening: Anglo-Indian Defense, Slav Formation 1. c4 Nf6 2. Nf3 g6 3. g3 c6 -A15 English Orangutan 1. c4 Nf6 2. b4 -A15 English Orangutan 1. c4 Nf6 2. Nf3 g6 3. b4 -A16 English Opening: Anglo-Grünfeld Defense 1. c4 Nf6 2. Nc3 d5 -A16 English Opening: Anglo-Grünfeld Defense, Korchnoi Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 g6 5. g3 Bg7 6. Bg2 e5 -A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 -A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 g6 -A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. g3 g6 5. Bg2 Nb6 -A16 English Opening: Anglo-Indian Defense, Anglo-Grünfeld Variation 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. g3 g6 5. Bg2 Nxc3 -A16 English Opening: Anglo-Indian Defense, Queen's Knight Variation 1. c4 Nf6 2. Nc3 -A17 English Opening: Anglo-Indian Defense 1. c4 Nf6 2. Nc3 d5 3. cxd5 Nxd5 4. Nf3 c5 5. e3 e6 -A17 English Opening: Anglo-Indian Defense, Hedgehog System 1. c4 Nf6 2. Nc3 e6 -A17 English Opening: Anglo-Indian Defense, Nimzo-English 1. c4 Nf6 2. Nc3 e6 3. Nf3 Bb4 -A17 English Opening: Anglo-Indian Defense, Queen's Indian Formation 1. c4 e6 2. Nc3 Nf6 3. Nf3 b6 -A17 English Opening: Anglo-Indian Defense, Queen's Indian Variation 1. c4 e6 2. Nc3 Nf6 3. Nf3 b6 4. e4 Bb7 5. Bd3 -A17 English Opening: Anglo-Indian Defense, Zvjaginsev-Krasenkow Attack 1. c4 e6 2. Nc3 Nf6 3. Nf3 Bb4 4. g4 -A18 English Opening: Mikenas-Carls Variation 1. c4 e6 2. Nc3 Nf6 3. e4 -A18 English Opening: Mikenas-Carls Variation 1. c4 e6 2. Nc3 Nf6 3. e4 Nc6 -A18 English Opening: Mikenas-Carls Variation 1. c4 e6 2. Nc3 Nf6 3. e4 d5 4. e5 -A19 English Opening: Anglo-Indian Defense, Flohr-Mikenas-Carls Variation, Nei Gambit 1. c4 e6 2. Nc3 Nf6 3. e4 c5 4. e5 Ng8 -A19 English Opening: Mikenas-Carls, Sicilian 1. c4 e6 2. Nc3 Nf6 3. e4 c5 -A20 English Opening: Drill Variation 1. c4 e5 2. g3 h5 -A20 English Opening: King's English Variation 1. c4 e5 -A20 English Opening: King's English Variation, Kahiko-Hula Gambit 1. c4 e5 2. e3 Nf6 3. f4 exf4 4. Nf3 -A20 English Opening: King's English Variation, Nimzowitsch Variation 1. c4 e5 2. Nf3 -A20 English Opening: King's English Variation, Nimzowitsch-Flohr Variation 1. c4 e5 2. Nf3 e4 -A21 English Opening: King's English Variation 1. c4 e5 2. Nc3 d6 3. Nf3 -A21 English Opening: King's English Variation, Keres Defense 1. c4 e5 2. Nc3 d6 3. g3 c6 -A21 English Opening: King's English Variation, Kramnik-Shirov Counterattack 1. c4 e5 2. Nc3 Bb4 -A21 English Opening: King's English Variation, Reversed Sicilian 1. c4 e5 2. Nc3 -A21 English Opening: King's English Variation, Smyslov Defense 1. c4 e5 2. Nc3 d6 3. Nf3 Bg4 -A21 English Opening: King's English Variation, Troger Defense 1. c4 e5 2. Nc3 Nc6 3. g3 d6 4. Bg2 Be6 -A22 English Opening: Carls-Bremen System 1. c4 e5 2. Nc3 Nf6 3. g3 -A22 English Opening: King's English Variation, Adhiban Gambit 1. c4 e5 2. Nc3 Nf6 3. Nf3 e4 4. Ng5 c6 -A22 English Opening: King's English Variation, Bellon Gambit 1. c4 e5 2. Nc3 Nf6 3. Nf3 e4 4. Ng5 b5 -A22 English Opening: King's English Variation, Two Knights Variation 1. c4 e5 2. Nc3 Nf6 -A22 English Opening: King's English Variation, Two Knights Variation, Reversed Dragon 1. c4 e5 2. Nc3 Nf6 3. g3 d5 -A22 English Opening: King's English Variation, Two Knights Variation, Smyslov System 1. c4 e5 2. Nc3 Nf6 3. g3 Bb4 -A22 English Opening: King's English, Erbenheimer Gambit 1. c4 e5 2. Nc3 Nf6 3. Nf3 e4 4. Ng5 Ng4 -A22 English Opening: King's English, Mazedonisch 1. c4 e5 2. Nc3 Nf6 3. f4 -A23 English Opening: King's English Variation, Two Knights Variation, Keres Variation 1. c4 e5 2. Nc3 Nf6 3. g3 c6 -A23 English Opening: King's English Variation, Two Knights Variation, Keres Variation 1. c4 e5 2. Nc3 Nf6 3. g3 Bc5 4. Bg2 c6 -A24 English Opening: King's English Variation, Two Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. g3 g6 -A25 English Opening: Closed, Taimanov Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Rb1 Nh6 5. Bg2 Bg7 -A25 English Opening: Closed, Taimanov Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. e3 d6 6. Nge2 Nh6 -A25 English Opening: King's English Variation, Bremen-Hort Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. e3 d6 6. Nge2 Be6 -A25 English Opening: King's English Variation, Closed System 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 -A25 English Opening: King's English Variation, Hungarian Attack 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Rb1 -A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. Nc3 Nc6 -A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. g3 Nf6 3. Bg2 Nc6 4. Nc3 Bb4 5. Nd5 -A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. g3 Nf6 3. Bg2 Nc6 4. Nc3 Bb4 5. e4 d6 6. Nge2 -A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. g3 Nf6 3. Bg2 Nc6 4. Nc3 Bb4 5. e4 d6 6. Nge2 Bg4 -A25 English Opening: King's English Variation, Reversed Closed Sicilian 1. c4 e5 2. Nc3 Nf6 3. g3 Bb4 4. e4 O-O 5. Nge2 Nc6 6. Bg2 -A25 English Opening: King's English Variation, Taimanov Variation 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 -A26 English Opening: King's English Variation, Botvinnik System 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. e4 -A26 English Opening: King's English Variation, Closed System, Full Symmetry 1. c4 e5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 -A27 English Opening: King's English Variation, Three Knights System 1. c4 e5 2. Nc3 Nc6 3. Nf3 -A28 English Opening: Four Knights System, Nimzowitsch Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e4 -A28 English Opening: King's English Variation, Four Knights Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 -A28 English Opening: King's English Variation, Four Knights Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d4 exd4 5. Nxd4 Bb4 6. Bg5 h6 7. Bh4 Bxc3+ 8. bxc3 Ne5 -A28 English Opening: King's English Variation, Four Knights Variation, Bradley Beach Variation 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d4 e4 -A28 English Opening: King's English Variation, Four Knights Variation, Flexible Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. d3 -A28 English Opening: King's English Variation, Four Knights Variation, Korchnoi Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. a3 -A28 English Opening: King's English Variation, Four Knights Variation, Quiet Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e3 -A28 English Opening: King's English Variation, Four Knights Variation, Quiet Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e3 Bb4 5. Qc2 Bxc3 -A28 English Opening: King's English Variation, Four Knights Variation, Quiet Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. e3 Bb4 5. Qc2 O-O 6. Nd5 Re8 7. Qf5 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bb4 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bb4 5. Bg2 Bxc3 6. dxc3 d6 7. O-O O-O -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. g3 Nf6 3. Bg2 d5 4. cxd5 Nxd5 5. Nf3 Nc6 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. g3 Nf6 3. Bg2 d5 4. cxd5 Nxd5 5. Nf3 Nc6 6. d3 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line 1. c4 e5 2. g3 Nf6 3. Bg2 d5 4. cxd5 Nxd5 5. Nf3 Nc6 6. d3 Be7 7. O-O O-O -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, Delayed .. Nc6 1. c4 e5 2. Nc3 Nf6 3. g3 Bb4 4. Bg2 O-O 5. Nf3 Re8 6. O-O e4 7. Nd4 Nc6 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 O-O 7. O-O -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6, Be7 1. c4 e5 2. Nc3 Nf6 3. g3 Nc6 4. Bg2 d6 5. d3 Be7 6. Nf3 O-O -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6, a6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 a6 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with .. d6, h6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 Bc5 5. d3 d6 6. Bg2 h6 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with Bc5 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 d5 5. cxd5 Nxd5 6. Bg2 Bc5 -A29 English Opening: King's English Variation, Four Knights Variation, Fianchetto Line, with Nb6 1. c4 e5 2. Nc3 Nf6 3. Nf3 Nc6 4. g3 d5 5. cxd5 Nxd5 6. Bg2 Nb6 -A30 English Opening: Symmetrical Variation 1. c4 c5 -A30 English Opening: Symmetrical Variation 1. c4 c5 2. Nf3 -A30 English Opening: Symmetrical Variation, Hedgehog Defense 1. c4 e6 2. Nf3 Nf6 3. Nc3 c5 4. g3 b6 5. Bg2 Bb7 6. O-O Be7 -A30 English Opening: Symmetrical Variation, Napolitano Gambit 1. c4 c5 2. Nf3 Nf6 3. b4 -A30 English Opening: Symmetrical, Hedgehog, Flexible Formation 1. c4 e6 2. Nf3 c5 3. Nc3 Nf6 4. g3 b6 5. Bg2 Bb7 6. O-O Be7 7. d4 cxd4 8. Qxd4 d6 9. Rd1 a6 10. b3 Nbd7 -A30 English Opening: Wing Gambit 1. c4 c5 2. b4 -A31 English Opening: Symmetrical Variation, Anti-Benoni Variation 1. c4 Nf6 2. d4 c5 3. Nf3 -A31 English Opening: Symmetrical Variation, Anti-Benoni Variation, Kasparov-Vaganian Gambit 1. d4 Nf6 2. c4 c5 3. Nf3 cxd4 4. Nxd4 e5 5. Nb5 d5 -A32 English Opening: Symmetrical Variation, Anti-Benoni Variation, Spielmann Defense 1. c4 e6 2. d4 c5 3. Nf3 cxd4 4. Nxd4 Nf6 -A33 English Opening: Symmetrical Variation, Anti-Benoni Variation, Geller Variation 1. c4 e6 2. Nf3 Nf6 3. Nc3 c5 4. d4 Nc6 5. g3 cxd4 6. Nxd4 Qb6 -A33 English Opening: Symmetrical Variation, Anti-Benoni Variation, Spielmann Defense 1. c4 e6 2. Nf3 Nf6 3. Nc3 c5 4. d4 cxd4 5. Nxd4 Nc6 -A34 English Opening: Symmetrical Variation 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 4. g3 d5 5. d4 cxd4 -A34 English Opening: Symmetrical Variation, Fianchetto Variation 1. c4 Nf6 2. Nc3 c5 3. g3 -A34 English Opening: Symmetrical Variation, Normal Variation 1. c4 c5 2. Nc3 -A34 English Opening: Symmetrical Variation, Rubinstein Variation 1. c4 Nf6 2. Nc3 c5 3. g3 d5 4. cxd5 Nxd5 5. Bg2 Nc7 -A34 English Opening: Symmetrical Variation, Rubinstein Variation 1. c4 c5 2. Nf3 Nf6 3. Nc3 d5 4. cxd5 Nxd5 5. g3 Nc6 6. Bg2 Nc7 -A34 English Opening: Symmetrical Variation, Three Knights Variation 1. c4 c5 2. Nc3 Nf6 3. Nf3 -A35 English Opening: Symmetrical Variation 1. c4 c5 2. Nc3 Nf6 3. Nf3 e5 -A35 English Opening: Symmetrical Variation, Four Knights Variation 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 -A35 English Opening: Symmetrical Variation, Four Knights Variation, Keres-Parma System 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 4. g3 e6 -A35 English Opening: Symmetrical Variation, Two Knights Variation 1. c4 c5 2. Nc3 Nc6 -A36 English Opening: Symmetrical Variation, Botvinnik System 1. c4 c5 2. e4 Nc6 3. Nc3 g6 4. g3 Bg7 5. Bg2 -A36 English Opening: Symmetrical Variation, Botvinnik System Reversed, with e3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. e3 e5 -A36 English Opening: Symmetrical Variation, Two Knights, Fianchetto Variation 1. c4 c5 2. Nc3 Nc6 3. g3 -A36 English Opening: Symmetrical Variation, Ultra-Symmetrical Variation 1. c4 c5 2. g3 g6 3. Bg2 Bg7 4. Nc3 Nc6 -A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 -A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O d6 -A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 -A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 7. a3 -A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 7. d3 -A37 English Opening: Symmetrical Variation, Botvinnik System Reversed, with Nf3 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 e5 6. O-O Nge7 7. d3 d6 -A37 English Opening: Symmetrical Variation, Three Knights, Fianchetto Variation 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 -A37 English Opening: Symmetrical Variation, Three Knights, Fianchetto Variation 1. c4 c5 2. Nf3 Nc6 3. g3 g6 4. Bg2 Bg7 5. O-O d6 6. Nc3 -A37 English Opening: Symmetrical Variation, Three Knights, Fianchetto Variation 1. c4 c5 2. Nf3 Nc6 3. g3 g6 4. Bg2 Bg7 5. O-O e6 6. Nc3 -A38 English Opening: Symmetrical Variation, Double Fianchetto 1. c4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. Nf3 Nf6 6. O-O O-O 7. b3 -A38 English Opening: Symmetrical Variation, Duchamp Variation 1. c4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O c5 6. Nc3 Nc6 7. d3 -A38 English Opening: Symmetrical Variation, Full Symmetry Line 1. c4 Nf6 2. Nf3 c5 3. Nc3 Nc6 4. g3 g6 5. Bg2 Bg7 -A39 English Opening: Symmetrical Variation, Mecking Variation 1. c4 Nf6 2. Nf3 c5 3. Nc3 Nc6 4. g3 g6 5. Bg2 Bg7 6. O-O O-O 7. d4 -A40 Australian Defense 1. d4 Na6 -A40 Benoni Defense: Franco-Sicilian Hybrid 1. d4 e6 2. c4 c5 3. d5 exd5 4. cxd5 d6 5. Nc3 g6 6. e4 Bg7 7. Nf3 Ne7 -A40 Borg Defense: Borg Gambit 1. d4 g5 -A40 Colle System: Pterodactyl Variation 1. d4 g6 2. Nf3 Bg7 3. e3 c5 4. Bd3 Qa5+ -A40 Colle System: Siroccopteryx Variation 1. d4 g6 2. Nf3 Bg7 3. e3 c5 4. Bd3 cxd4 5. Nxd4 Qa5+ -A40 English Defense 1. d4 b6 -A40 English Defense 1. d4 e6 2. c4 b6 -A40 English Defense: Eastbourne Gambit 1. d4 b6 2. c4 Bb7 3. Nc3 e5 -A40 English Defense: Hartlaub Gambit Accepted 1. c4 e6 2. d4 b6 3. Nc3 Bb7 4. e4 f5 5. exf5 Nf6 -A40 English Defense: Hartlaub Gambit Declined 1. c4 e6 2. d4 b6 3. Nc3 Bb7 4. e4 f5 5. d5 -A40 English Defense: Perrin Variation 1. d4 e6 2. c4 b6 3. e4 Bb7 4. Bd3 Nc6 -A40 English Defense: Poli Gambit 1. d4 e6 2. c4 b6 3. e4 Bb7 4. f3 f5 5. exf5 Nh6 -A40 Englund Gambit 1. d4 e5 -A40 Englund Gambit Declined 1. d4 e5 2. d5 -A40 Englund Gambit Declined: Diemer Counterattack 1. d4 e5 2. d5 Bc5 3. e4 Qh4 -A40 Englund Gambit Declined: Reversed Alekhine 1. d4 e5 2. Nf3 -A40 Englund Gambit Declined: Reversed Brooklyn 1. d4 e5 2. Nf3 e4 3. Ng1 -A40 Englund Gambit Declined: Reversed French 1. d4 e5 2. e3 -A40 Englund Gambit Declined: Reversed Krebs 1. d4 e5 2. Nf3 e4 -A40 Englund Gambit Declined: Reversed Mokele Mbembe 1. d4 e5 2. Nf3 e4 3. Ne5 -A40 Englund Gambit: Felbecker Gambit 1. d4 e5 2. dxe5 Nc6 3. Nf3 Bc5 -A40 Englund Gambit: Hartlaub-Charlick Gambit 1. d4 e5 2. dxe5 d6 -A40 Englund Gambit: Main Line 1. d4 e5 2. dxe5 Nc6 3. Nf3 Qe7 -A40 Englund Gambit: Mosquito Gambit 1. d4 e5 2. dxe5 Qh4 -A40 Englund Gambit: Soller Gambit 1. d4 e5 2. dxe5 f6 -A40 Englund Gambit: Soller Gambit Deferred 1. d4 e5 2. dxe5 Nc6 3. Nf3 f6 -A40 Englund Gambit: Stockholm Variation 1. d4 e5 2. dxe5 Nc6 3. Nf3 Qe7 4. Qd5 -A40 Englund Gambit: Zilbermints Gambit 1. d4 e5 2. dxe5 Nc6 3. Nf3 Nge7 -A40 Horwitz Defense 1. d4 e6 -A40 Horwitz Defense: Zilbermints Gambit 1. d4 e6 2. c4 e5 -A40 Kangaroo Defense 1. d4 e6 2. c4 Bb4+ -A40 Kangaroo Defense: Keres Defense, Transpositional Variation 1. d4 e6 2. c4 Bb4+ 3. Nc3 -A40 Mikenas Defense 1. d4 Nc6 -A40 Mikenas Defense: Cannstatter Variation 1. d4 Nc6 2. c4 e5 3. d5 Nd4 -A40 Mikenas Defense: Lithuanian Variation 1. d4 Nc6 2. c4 e5 3. d5 Nce7 -A40 Mikenas Defense: Pozarek Gambit 1. d4 Nc6 2. c4 e5 3. dxe5 Nxe5 4. Nc3 Nxc4 -A40 Modern Defense: Beefeater Variation 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 Bxc3+ 5. bxc3 f5 -A40 Modern Defense: Lizard Defense, Pirc-Diemer Gambit 1. d4 g6 2. h4 Nf6 3. h5 -A40 Montevideo Defense 1. d4 Nc6 2. d5 Nb8 -A40 Polish Defense 1. d4 b5 -A40 Polish Defense: Spassky Gambit Accepted 1. d4 b5 2. e4 Bb7 3. Bxb5 -A40 Pterodactyl Defense: Central, Benoni Beefeater Pterodactyl 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 d6 5. e4 Bxc3+ 6. bxc3 Qa5 -A40 Pterodactyl Defense: Central, Benoni Pterodactyl 1. d4 g6 2. c4 Bg7 3. e4 c5 4. d5 Qa5+ -A40 Pterodactyl Defense: Fianchetto, Queen Benoni Pterodactyl 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 Qa5 -A40 Pterodactyl Defense: Fianchetto, Queen Pteranodon 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. d5 Bxc3+ 5. bxc3 Qa5 -A40 Pterodactyl Defense: Fianchetto, Queen Pterodactyl 1. d4 g6 2. Nf3 Bg7 3. g3 c5 4. Bg2 Qa5+ -A40 Pterodactyl Defense: Queen Pterodactyl, Quiet Line 1. d4 g6 2. c4 Bg7 3. Nc3 c5 4. e3 -A40 Queen's Pawn Game 1. d4 -A40 Queen's Pawn Game: Anglo-Slav Opening 1. d4 c6 2. c4 d6 -A40 Queen's Pawn Game: Modern Defense 1. d4 g6 -A40 Slav Indian: Kudischewitsch Gambit 1. d4 c6 2. Nf3 Nf6 3. c4 b5 -A40 Zaire Defense 1. d4 Nc6 2. d5 Nb8 3. e4 Nf6 4. e5 Ng8 -A41 Modern Defense 1. d4 g6 2. c4 Bg7 3. Nc3 d6 -A41 Modern Defense: Neo-Modern Defense 1. d4 g6 2. c4 Bg7 3. e4 e5 -A41 Old Indian Defense 1. d4 d6 2. c4 -A41 Queen's Pawn Game 1. d4 d6 -A41 Queen's Pawn Game: Rossolimo Variation 1. d4 d6 2. Nf3 g6 -A41 Rat Defense: English Rat 1. d4 d6 2. c4 e5 -A41 Rat Defense: English Rat, Lisbon Gambit 1. d4 d6 2. c4 e5 3. dxe5 Nc6 -A41 Rat Defense: English Rat, Pounds Gambit 1. d4 d6 2. c4 e5 3. dxe5 Be6 -A41 Robatsch Defense: Rossolimo Variation 1. d4 d6 2. Nf3 g6 3. c4 Bg7 4. e4 Bg4 -A41 Wade Defense 1. d4 d6 2. Nf3 Bg4 -A41 Zukertort Opening: Wade Defense, Chigorin Plan 1. d4 d6 2. Nf3 Bg4 3. c4 Nd7 4. Qb3 Rb8 -A42 Modern Defense: Averbakh System 1. d4 g6 2. c4 Bg7 3. Nc3 d6 4. e4 -A42 Modern Defense: Averbakh Variation, Pseudo-Sämisch 1. d4 g6 2. c4 Bg7 3. e4 d6 4. Be3 Nf6 5. f3 -A42 Modern Defense: Kotov Variation 1. d4 g6 2. c4 Bg7 3. Nc3 d6 4. e4 Nc6 -A42 Modern Defense: Randspringer Variation 1. d4 g6 2. c4 Bg7 3. Nc3 d6 4. e4 f5 -A42 Pterodactyl Defense 1. Nf3 c5 2. c4 g6 3. d4 Bg7 4. e4 Qa5+ 5. Nc3 d6 -A42 Pterodactyl Defense: Central, Bogolubovia 1. d4 g6 2. c4 Bg7 3. e4 d6 4. Nc3 c5 5. Nge2 Qa5 -A43 Benoni Defense: Benoni Gambit Accepted 1. d4 c5 2. dxc5 -A43 Benoni Defense: Benoni Gambit, Schlenker Defense 1. d4 c5 2. dxc5 Na6 -A43 Benoni Defense: Benoni-Indian Defense 1. d4 c5 2. d5 Nf6 -A43 Benoni Defense: Benoni-Indian Defense, Kingside Move Order 1. d4 c5 2. d5 Nf6 3. Nf3 -A43 Benoni Defense: Benoni-Staunton Gambit 1. d4 c5 2. d5 f5 3. e4 -A43 Benoni Defense: Cormorant Gambit 1. d4 c5 2. dxc5 b6 -A43 Benoni Defense: French Benoni 1. e4 e6 2. d4 c5 3. d5 -A43 Benoni Defense: Hawk Variation 1. d4 Nf6 2. Nf3 c5 3. d5 c4 -A43 Benoni Defense: Old Benoni 1. d4 c5 -A43 Benoni Defense: Old Benoni 1. d4 c5 2. d5 -A43 Benoni Defense: Old Benoni 1. d4 c5 2. d5 d6 -A43 Benoni Defense: Old Benoni, Mujannah Formation 1. d4 c5 2. d5 f5 -A43 Benoni Defense: Old Benoni, Schmid Variation 1. d4 c5 2. d5 d6 3. Nc3 g6 -A43 Benoni Defense: Snail Variation 1. d4 c5 2. d5 Na6 -A43 Benoni Defense: Woozle 1. d4 c5 2. d5 Nf6 3. Nc3 Qa5 -A43 Benoni Defense: Zilbermints-Benoni Gambit 1. d4 c5 2. b4 -A43 Benoni Defense: Zilbermints-Benoni Gambit 1. d4 c5 2. Nf3 cxd4 3. b4 -A43 Benoni Defense: Zilbermints-Benoni Gambit, Tamarkin Countergambit 1. d4 c5 2. Nf3 cxd4 3. b4 e5 -A43 Indian Defense: Pseudo-Benko 1. d4 Nf6 2. Nf3 c5 3. d5 b5 -A43 Queen's Pawn Game: Liedmann Gambit 1. d4 c5 2. c4 cxd4 3. e3 -A44 Benoni Defense: Old Benoni 1. d4 c5 2. d5 e5 -A44 Benoni Defense: Semi-Benoni 1. d4 c5 2. d5 e5 3. e4 d6 -A45 Amazon Attack: Siberian Attack 1. d4 Nf6 2. Nc3 d5 3. Qd3 -A45 Basque Opening 1. d4 Nf6 2. b3 -A45 Canard Opening 1. d4 Nf6 2. f4 -A45 Indian Defense 1. d4 Nf6 -A45 Indian Defense: Accelerated London System 1. d4 Nf6 2. Bf4 -A45 Indian Defense: Gedult Attack 1. d4 Nf6 2. f3 d5 3. g4 -A45 Indian Defense: Gibbins-Weidenhagen Gambit 1. d4 Nf6 2. g4 -A45 Indian Defense: Gibbins-Weidenhagen Gambit Accepted 1. d4 Nf6 2. g4 Nxg4 -A45 Indian Defense: Gibbins-Weidenhagen Gambit, Maltese Falcon 1. d4 Nf6 2. g4 Nxg4 3. f3 Nf6 4. e4 -A45 Indian Defense: Gibbins-Weidenhagen Gambit, Oshima Defense 1. d4 Nf6 2. g4 e5 -A45 Indian Defense: Gibbins-Weidenhagen Gambit, Stummer Gambit 1. d4 Nf6 2. g4 Nxg4 3. e4 d6 4. Be2 Nf6 5. Nc3 -A45 Indian Defense: Lazard Gambit 1. d4 Nf6 2. Nd2 e5 -A45 Indian Defense: Maddigan Gambit 1. d4 Nf6 2. Nc3 e5 -A45 Indian Defense: Omega Gambit 1. d4 Nf6 2. e4 -A45 Indian Defense: Omega Gambit, Arafat Gambit 1. d4 Nf6 2. e4 Nxe4 3. Bd3 Nf6 4. Bg5 -A45 Indian Defense: Paleface Attack, Blackmar-Diemer Gambit Deferred 1. d4 Nf6 2. f3 d5 3. e4 -A45 Indian Defense: Pawn Push Variation 1. d4 Nf6 2. d5 -A45 Indian Defense: Reversed Chigorin Defense 1. d4 Nf6 2. Nc3 c5 -A45 Indian Defense: Tartakower Attack 1. d4 Nf6 2. g3 -A45 Paleface Attack 1. d4 Nf6 2. f3 -A45 Queen's Pawn Game: Chigorin Variation 1. d4 Nf6 2. Nc3 d5 -A45 Queen's Pawn Game: Veresov, Richter Attack 1. d4 Nf6 2. f3 d5 3. Nc3 -A45 Trompowsky Attack 1. d4 Nf6 2. Bg5 -A45 Trompowsky Attack: Borg Variation 1. d4 Nf6 2. Bg5 Ne4 3. Bf4 g5 -A45 Trompowsky Attack: Classical Defense 1. d4 Nf6 2. Bg5 e6 -A45 Trompowsky Attack: Classical Defense, Big Center Variation 1. d4 Nf6 2. Bg5 e6 3. e4 -A45 Trompowsky Attack: Edge Variation 1. d4 Nf6 2. Bg5 Ne4 3. Bh4 -A45 Trompowsky Attack: Edge Variation, Hergert Gambit 1. d4 Nf6 2. Bg5 Ne4 3. Bh4 c6 4. Nd2 Qa5 5. c3 Nxd2 6. Qxd2 d5 7. e4 -A45 Trompowsky Attack: Edge Variation, Hergert Gambit 1. d4 Nf6 2. Bg5 Ne4 3. Bh4 d5 4. f3 Nf6 5. Nc3 Bf5 6. e4 -A45 Trompowsky Attack: Poisoned Pawn Variation 1. d4 Nf6 2. Bg5 c5 3. d5 Qb6 4. Nc3 -A45 Trompowsky Attack: Raptor Variation 1. d4 Nf6 2. Bg5 Ne4 3. h4 -A45 Trompowsky Attack: Raptor Variation, Hergert Gambit 1. d4 Nf6 2. Bg5 Ne4 3. h4 Nxg5 4. hxg5 e5 -A46 Döry Defense 1. d4 Nf6 2. Nf3 Ne4 -A46 Indian Defense: Czech-Indian 1. d4 Nf6 2. Nf3 c6 -A46 Indian Defense: Knights Variation 1. d4 Nf6 2. Nf3 -A46 Indian Defense: Knights Variation, Alburt-Miles Variation 1. d4 Nf6 2. Nf3 a6 -A46 Indian Defense: London System 1. d4 Nf6 2. Nf3 e6 3. Bf4 -A46 Indian Defense: Polish Variation 1. d4 Nf6 2. Nf3 b5 -A46 Indian Defense: Spielmann-Indian 1. d4 Nf6 2. Nf3 c5 -A46 Indian Defense: Wade-Tartakower Defense 1. d4 Nf6 2. Nf3 d6 -A46 Queen's Pawn Game: Torre Attack, Breyer Variation 1. d4 Nf6 2. Nf3 e6 3. Bg5 d5 4. e3 c5 5. c3 Qb6 -A46 Queen's Pawn Game: Veresov Attack, Classical Defense 1. d4 Nf6 2. Nf3 e6 3. Nc3 d5 4. Bg5 -A46 Torre Attack: Classical Defense 1. d4 Nf6 2. Nf3 e6 3. Bg5 -A46 Torre Attack: Classical Defense, Nimzowitsch Variation 1. d4 Nf6 2. Nf3 e6 3. Bg5 h6 -A46 Torre Attack: Classical Defense, Petrosian Gambit 1. d4 Nf6 2. Nf3 e6 3. Bg5 c5 4. e3 b6 5. d5 -A46 Torre Attack: Wagner Gambit 1. d4 Nf6 2. Nf3 e6 3. Bg5 c5 4. e4 -A46 Yusupov-Rubinstein System 1. d4 Nf6 2. Nf3 e6 3. e3 -A47 Indian Defense: Schnepper Gambit 1. d4 Nf6 2. Nf3 b6 3. c3 e5 -A47 Marienbad System 1. d4 Nf6 2. Nf3 b6 3. g3 Bb7 4. Bg2 c5 -A47 Marienbad System: Berg Variation 1. d4 Nf6 2. Nf3 b6 3. g3 Bb7 4. Bg2 c5 5. c4 cxd4 6. Qxd4 -A47 Pseudo Queen's Indian Defense 1. d4 Nf6 2. Nf3 b6 -A47 Pseudo Queen's Indian Defense 1. d4 Nf6 2. Nf3 b6 3. e3 Bb7 4. Bd3 e6 5. Nbd2 c5 6. b3 Be7 -A48 East Indian Defense 1. d4 Nf6 2. Nf3 g6 -A48 Indian Defense: Colle System, King's Indian Variation 1. d4 Nf6 2. Nf3 g6 3. e3 Bg7 4. Bd3 d6 -A48 London System 1. d4 Nf6 2. Nf3 g6 3. Bf4 -A48 London System 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 -A48 London System 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 -A48 London System, with Bd3 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. Bd3 -A48 London System, with Be2 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. Be2 -A48 London System, with Be2 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. Be2 O-O -A48 London System, with Be2 1. d4 Nf6 2. Nf3 g6 3. Bf4 Bg7 4. e3 d6 5. h3 c5 6. Be2 -A48 Queen's Pawn Game: Barry Attack 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 -A48 Queen's Pawn Game: Barry Attack 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 Bg7 -A48 Queen's Pawn Game: Barry Attack, Grünfeld Variation 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. Be2 -A48 Queen's Pawn Game: Barry Attack, Tarzan Attack 1. d4 Nf6 2. Nf3 g6 3. Nc3 d5 4. Bf4 Bg7 5. Qd2 -A48 Queen's Pawn Game: Torre Attack, Grünfeld Variation, Main Line 1. d4 Nf6 2. Nf3 g6 3. Bg5 Bg7 4. Nbd2 d5 5. e3 O-O -A48 Torre Attack: Fianchetto Defense 1. d4 Nf6 2. Nf3 g6 3. Bg5 -A48 Torre Attack: Fianchetto Defense, Euwe Variation 1. d4 Nf6 2. Nf3 g6 3. Bg5 Bg7 4. Nbd2 c5 -A49 Indian Defense: Przepiorka Variation 1. d4 Nf6 2. Nf3 g6 3. g3 -A50 Indian Defense: Medusa Gambit 1. d4 Nf6 2. c4 g5 -A50 Indian Defense: Normal Variation 1. d4 Nf6 2. c4 -A50 Indian Defense: Pyrenees Gambit 1. d4 Nf6 2. c4 b5 -A50 Mexican Defense 1. d4 Nf6 2. c4 Nc6 -A50 Mexican Defense: Horsefly Gambit 1. d4 Nf6 2. c4 Nc6 3. d5 Ne5 4. f4 -A50 Queen's Indian Accelerated 1. d4 Nf6 2. c4 b6 -A50 Slav Indian 1. d4 Nf6 2. c4 c6 -A51 Indian Defense: Budapest Gambit 1. d4 Nf6 2. c4 e5 -A51 Indian Defense: Budapest Gambit Accepted 1. d4 Nf6 2. c4 e5 3. dxe5 -A51 Indian Defense: Budapest Gambit Accepted, Fajarowicz Defense 1. d4 Nf6 2. c4 e5 3. dxe5 Ne4 -A51 Indian Defense: Budapest Gambit Accepted, Fajarowicz Defense, Bonsdorf Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ne4 4. a3 -A51 Indian Defense: Budapest Gambit Accepted, Fajarowicz Defense, Steiner Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ne4 4. Qc2 -A52 Indian Defense: Budapest Gambit Accepted, Main Line 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 -A52 Indian Defense: Budapest Gambit Accepted, Main Line, Adler Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. Nf3 -A52 Indian Defense: Budapest Gambit Accepted, Main Line, Alekhine Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. e4 -A52 Indian Defense: Budapest Gambit Accepted, Main Line, Alekhine Variation, Abonyi Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. e4 Nxe5 -A52 Indian Defense: Budapest Gambit Accepted, Main Line, Alekhine Variation, Tartakower Defense 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. e4 d6 -A52 Indian Defense: Budapest Gambit Accepted, Main Line, Rubinstein Variation 1. d4 Nf6 2. c4 e5 3. dxe5 Ng4 4. Bf4 -A53 Old Indian Defense 1. d4 Nf6 2. c4 d6 -A53 Old Indian Defense: Aged Gibbon Gambit 1. d4 Nf6 2. c4 d6 3. g4 -A53 Old Indian Defense: Czech Variation, with Nc3 1. d4 Nf6 2. c4 d6 3. Nc3 c6 -A53 Old Indian Defense: Czech Variation, with Nf3 1. d4 Nf6 2. c4 d6 3. Nf3 c6 -A53 Old Indian Defense: Janowski Variation 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 -A53 Old Indian Defense: Janowski Variation, Fianchetto Variation 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 4. g3 -A53 Old Indian Defense: Janowski Variation, Grinberg Gambit 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 4. e4 -A53 Old Indian Defense: Janowski Variation, Main Line 1. d4 Nf6 2. c4 d6 3. Nc3 Bf5 4. f3 -A54 Old Indian Defense: Duz-Khotimirsky Variation 1. d4 Nf6 2. c4 d6 3. Nc3 e5 4. e3 Nbd7 5. Bd3 -A54 Old Indian Defense: Tartakower-Indian 1. d4 Nf6 2. c4 d6 3. Nf3 Bg4 -A54 Old Indian Defense: Two Knights Variation 1. d4 Nf6 2. c4 d6 3. Nc3 e5 4. Nf3 -A54 Old Indian Defense: Ukrainian Variation 1. d4 Nf6 2. c4 d6 3. Nc3 e5 -A55 Old Indian Defense: Normal Variation 1. d4 Nf6 2. c4 d6 3. Nc3 Nbd7 4. e4 e5 5. Nf3 -A56 Benoni Defense 1. d4 Nf6 2. c4 c5 -A56 Benoni Defense: Czech Benoni Defense 1. d4 Nf6 2. c4 c5 3. d5 e5 -A56 Benoni Defense: Hromádka System 1. d4 Nf6 2. c4 c5 3. d5 d6 -A56 Benoni Defense: King's Indian System 1. d4 Nf6 2. c4 c5 3. d5 e5 4. Nc3 d6 5. e4 g6 -A56 Benoni Defense: Weenink Variation 1. d4 Nf6 2. c4 c5 3. dxc5 e6 -A56 Grünfeld Defense: Three Knights Variation, Burille Variation, Reversed Tarrasch 1. d4 Nf6 2. c4 c5 3. e3 g6 4. Nc3 Bg7 5. Nf3 O-O 6. Be2 cxd4 7. exd4 d5 8. O-O Nc6 -A56 Vulture Defense 1. d4 Nf6 2. c4 c5 3. d5 Ne4 -A57 Benko Gambit 1. d4 Nf6 2. c4 c5 3. d5 b5 -A57 Benko Gambit Accepted 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 -A57 Benko Gambit Accepted: Dlugy Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. f3 -A57 Benko Gambit Accepted: Modern Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. e3 -A57 Benko Gambit Accepted: Pawn Return Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. b6 -A57 Benko Gambit Declined: Bishop Attack 1. d4 Nf6 2. c4 c5 3. d5 b5 4. Bg5 -A57 Benko Gambit Declined: Hjørring Countergambit 1. d4 Nf6 2. c4 c5 3. d5 b5 4. e4 -A57 Benko Gambit Declined: Main Line 1. d4 Nf6 2. c4 c5 3. d5 b5 4. Nf3 -A57 Benko Gambit Declined: Pseudo-Sämisch 1. d4 Nf6 2. c4 c5 3. d5 b5 4. f3 -A57 Benko Gambit Declined: Quiet Line 1. d4 Nf6 2. c4 c5 3. d5 b5 4. Nd2 -A57 Benko Gambit Declined: Sosonko Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. a4 -A57 Benko Gambit: Mutkin Countergambit 1. d4 Nf6 2. c4 c5 3. d5 b5 4. g4 -A57 Benko Gambit: Nescafe Frappe Attack 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. Nc3 axb5 6. e4 b4 7. Nb5 d6 8. Bc4 -A57 Benko Gambit: Zaitsev System 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. Nc3 -A57 Benko Gambit: Zaitsev Variation, Nescafe Frappe Attack 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. Nc3 axb5 6. e4 b4 7. Nb5 -A58 Benko Gambit Accepted: Central Storming Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. f4 -A58 Benko Gambit Accepted: Fianchetto Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. g3 d6 8. Bg2 Bg7 9. Nf3 -A58 Benko Gambit Accepted: Fully Accepted Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 -A58 Benko Gambit: Fianchetto Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 Bxa6 6. Nc3 d6 7. Nf3 g6 8. g3 -A58 Benko Gambit: Nd2 Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 Bxa6 6. Nc3 d6 7. Nf3 g6 8. Nd2 -A59 Benko Gambit 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. e4 Bxf1 8. Kxf1 d6 9. g3 -A59 Benko Gambit Accepted: King Walk Variation 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. Nf3 d6 8. e4 Bxf1 9. Kxf1 Bg7 10. g3 O-O 11. Kg2 -A59 Benko Gambit Accepted: Yugoslav 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 Bxa6 6. Nc3 d6 7. e4 -A59 Benko Gambit Accepted: Yugoslav 1. d4 Nf6 2. c4 c5 3. d5 b5 4. cxb5 a6 5. bxa6 g6 6. Nc3 Bxa6 7. e4 Bxf1 8. Kxf1 d6 9. Nge2 -A60 Benoni Defense: Modern Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 -A60 Benoni Defense: Modern Variation, Snake Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 Bd6 -A61 Benoni Defense 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 -A61 Benoni Defense: Fianchetto Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. g3 -A61 Benoni Defense: Knight's Tour Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Nd2 -A61 Benoni Defense: Uhlmann Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg5 -A62 Benoni Defense: Fianchetto Variation 1. d4 Nf6 2. c4 e6 3. g3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg2 Bg7 8. Nf3 O-O -A63 Benoni Defense: Fianchetto Variation, Hastings Defense 1. d4 Nf6 2. c4 e6 3. g3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg2 Bg7 8. Nf3 O-O 9. O-O Nbd7 -A64 Benoni Defense: Fianchetto Variation, Hastings Defense, Main Line 1. d4 Nf6 2. c4 e6 3. g3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. Bg2 Bg7 8. Nf3 O-O 9. O-O a6 10. a4 Nbd7 11. Nd2 Re8 -A65 Benoni Defense: King's Pawn Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 -A65 Benoni Defense: King's Pawn Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 -A65 Benoni Defense: King's Pawn Line 1. d4 Nf6 2. c4 g6 3. f3 c5 4. d5 d6 5. e4 Bg7 6. Nc3 e6 7. Be3 O-O 8. Qd2 exd5 9. cxd5 -A65 Benoni Defense: King's Pawn Line, with Be3 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 8. Be3 -A65 Benoni Defense: King's Pawn Line, with Bg5 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 -A65 Benoni Defense: King's Pawn Line, with Bg5 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 8. Bg5 -A65 Benoni Defense: King's Pawn Line, with Bg5 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 e6 8. Qd2 exd5 9. exd5 -A65 Benoni Defense: King's Pawn Line, with Nge2 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f3 Bg7 8. Nge2 -A65 Benoni Defense: King's Pawn Line, with Nge2 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Nge2 c5 7. d5 e6 8. Ng3 exd5 9. cxd5 -A66 Benoni Defense: Mikenas Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. e5 -A66 Benoni Defense: Pawn Storm Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 -A67 Benoni Defense: Taimanov Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Bb5+ -A68 Benoni Defense: Four Pawns Attack 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O -A68 Benoni Defense: Four Pawns Attack 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 -A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 Re8 -A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 Nbd7 10. O-O Re8 -A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 Nbd7 10. O-O Re8 11. Nd2 -A69 Benoni Defense: Four Pawns Attack, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. f4 Bg7 8. Nf3 O-O 9. Be2 a6 10. a4 Re8 11. Nd2 -A70 Benoni Defense: Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 -A70 Benoni Defense: Classical Variation, New York Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. h3 -A70 Benoni Defense: Classical Variation, Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Be2 -A71 Benoni Defense: Classical Variation, Averbakh-Grivas Attack 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Bg5 -A72 Benoni Defense: Classical Variation 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O -A73 Benoni Defense: Classical Variation, Main Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O -A74 Benoni Defense: Classical Variation, Full Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O a6 10. a4 -A75 Benoni Defense: Classical Variation, Argentine Counterattack 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Be2 O-O 9. O-O a6 10. a4 Bg4 -A76 Benoni Defense: Classical Variation, Czerniak Defense 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 -A77 Benoni Defense: Classical Variation, Czerniak Defense, Tal Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 -A77 Benoni Defense: Classical Variation, Czerniak Defense, Tal Line 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 Nbd7 -A78 Benoni Defense: Classical Variation, Czerniak Defense 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 exd5 5. cxd5 d6 6. Nc3 g6 7. e4 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 Na6 -A79 Benoni Defense: Classical Variation, Czerniak Defense 1. d4 Nf6 2. c4 c5 3. d5 e6 4. Nc3 exd5 5. cxd5 d6 6. e4 g6 7. Nf3 Bg7 8. Be2 O-O 9. O-O Re8 10. Nd2 Na6 11. f3 -A80 Dutch Defense 1. d4 f5 -A80 Dutch Defense: Alapin Variation 1. d4 f5 2. Qd3 -A80 Dutch Defense: Barcza Variation 1. d4 f5 2. Nf3 Nf6 3. c3 -A80 Dutch Defense: Hevendehl Gambit 1. d4 f5 2. g4 e5 -A80 Dutch Defense: Hopton Attack 1. d4 f5 2. Bg5 -A80 Dutch Defense: Janzen-Korchnoi Gambit 1. d4 f5 2. h3 Nf6 3. g4 -A80 Dutch Defense: Kingfisher Gambit 1. d4 f5 2. Nc3 d5 3. e4 -A80 Dutch Defense: Korchnoi Attack 1. d4 f5 2. h3 -A80 Dutch Defense: Krejcik Gambit 1. d4 f5 2. g4 -A80 Dutch Defense: Krejcik Gambit, Tate Gambit 1. d4 f5 2. g4 fxg4 3. e4 d5 4. Nc3 -A80 Dutch Defense: Manhattan Gambit, Anti-Classical Line 1. d4 f5 2. Qd3 e6 3. g4 -A80 Dutch Defense: Manhattan Gambit, Anti-Leningrad 1. d4 f5 2. Qd3 g6 3. g4 -A80 Dutch Defense: Manhattan Gambit, Anti-Modern 1. d4 f5 2. Qd3 d6 3. g4 -A80 Dutch Defense: Manhattan Gambit, Anti-Stonewall 1. d4 f5 2. Qd3 d5 3. g4 -A80 Dutch Defense: Omega-Isis Gambit 1. d4 f5 2. Nf3 e5 -A80 Dutch Defense: Raphael Variation 1. d4 f5 2. Nc3 -A80 Dutch Defense: Senechaud Gambit 1. d4 f5 2. Bf4 e6 3. g4 -A80 Dutch Defense: Spielmann Gambit 1. d4 f5 2. Nc3 Nf6 3. g4 -A80 Queen's Pawn Game: Veresov Attack, Dutch System 1. d4 f5 2. Nc3 d5 -A81 Dutch Defense: Blackburne Variation 1. d4 f5 2. g3 Nf6 3. Bg2 e6 4. Nh3 -A81 Dutch Defense: Fianchetto Attack 1. d4 f5 2. g3 -A81 Dutch Defense: Leningrad Variation, Carlsbad Variation 1. d4 f5 2. g3 g6 3. Bg2 Bg7 4. Nh3 -A81 Dutch Defense: Leningrad, Basman System 1. d4 f5 2. g3 c6 3. Bg2 g6 4. Nf3 Bg7 5. O-O Nh6 -A81 Dutch Defense: Semi-Leningrad Variation 1. d4 f5 2. g3 Nf6 3. Bg2 g6 -A82 Dutch Defense: Blackmar's Second Gambit 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. f3 -A82 Dutch Defense: Staunton Gambit 1. d4 f5 2. e4 -A82 Dutch Defense: Staunton Gambit Accepted 1. d4 f5 2. e4 fxe4 -A82 Dutch Defense: Staunton Gambit, American Attack 1. d4 f5 2. e4 fxe4 3. Nd2 -A82 Dutch Defense: Staunton Gambit, Tartakower Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. g4 -A82 Rat Defense: Balogh Defense 1. e4 d6 2. d4 f5 -A83 Dutch Defense: Staunton Gambit 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 -A83 Dutch Defense: Staunton Gambit, Alekhine Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 g6 5. h4 -A83 Dutch Defense: Staunton Gambit, Chigorin Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 c6 -A83 Dutch Defense: Staunton Gambit, Lasker Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 g6 5. f3 -A83 Dutch Defense: Staunton Gambit, Nimzowitsch Variation 1. d4 f5 2. e4 fxe4 3. Nc3 Nf6 4. Bg5 b6 -A84 Dutch Defense 1. d4 f5 2. c4 -A84 Dutch Defense: Bellon Gambit 1. d4 f5 2. c4 e6 3. e4 -A84 Dutch Defense: Bladel Variation 1. d4 f5 2. c4 g6 3. Nc3 Nh6 -A84 Dutch Defense: Classical Variation 1. d4 f5 2. c4 e6 -A84 Dutch Defense: Krause Variation 1. d4 f5 2. c4 Nf6 3. Nc3 d6 4. Nf3 Nc6 -A84 Dutch Defense: Normal Variation 1. d4 f5 2. c4 Nf6 -A84 Dutch Defense: Rubinstein Variation 1. d4 f5 2. c4 e6 3. Nc3 -A85 Dutch Defense: Queen's Knight Variation 1. d4 f5 2. c4 Nf6 3. Nc3 -A86 Dutch Defense: Fianchetto Variation 1. d4 f5 2. c4 Nf6 3. g3 -A86 Dutch Defense: Hort-Antoshin System 1. d4 f5 2. c4 Nf6 3. g3 d6 4. Bg2 c6 5. Nc3 Qc7 -A86 Dutch Defense: Leningrad Variation 1. d4 f5 2. c4 Nf6 3. g3 g6 -A87 Dutch Defense: Leningrad Variation 1. d4 f5 2. c4 Nf6 3. g3 g6 4. Bg2 Bg7 5. Nf3 -A88 Dutch Defense: Leningrad Variation, Warsaw Variation 1. d4 f5 2. g3 Nf6 3. Bg2 g6 4. Nf3 Bg7 5. O-O O-O 6. c4 d6 7. Nc3 c6 -A89 Dutch Defense: Leningrad Variation, Matulovic Variation 1. d4 f5 2. g3 Nf6 3. Bg2 g6 4. Nf3 Bg7 5. O-O O-O 6. c4 d6 7. Nc3 Nc6 -A90 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 -A90 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 d5 5. Nf3 -A90 Dutch Defense: Nimzo-Dutch Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Bb4+ -A90 Dutch Defense: Nimzo-Dutch Variation, Alekhine Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Bb4+ 5. Bd2 Be7 -A90 Dutch Defense: Stonewall Variation, Modern Variation 1. d4 f5 2. c4 e6 3. Nf3 Nf6 4. g3 c6 5. Bg2 d5 6. O-O Bd6 -A91 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 -A91 Dutch Defense: Classical Variation, Blackburne Attack 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nh3 -A92 Dutch Defense: Alekhine Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O Ne4 -A92 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O -A92 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. Nc3 -A92 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 -A93 Dutch Defense: Stonewall Variation, Botvinnik Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. b3 -A94 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. b3 c6 8. Ba3 -A95 Dutch Defense: Stonewall Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. Nc3 c6 -A95 Dutch Defense: Stonewall Variation, Chekhover Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d5 7. Nc3 c6 8. Qc2 Qe8 9. Bg5 -A96 Dutch Defense: Classical Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 -A96 Dutch Defense: Classical Variation, Buenos Aires Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 a5 -A96 Dutch Defense: Classical Variation, Huisl Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Ne4 -A97 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 -A97 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation, Winter Variation 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 8. Re1 -A98 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation, Alatortsev-Lisitsyn Line 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 8. Qc2 -A99 Dutch Defense: Classical Variation, Ilyin-Zhenevsky Variation, Modern Main Line 1. d4 f5 2. c4 Nf6 3. g3 e6 4. Bg2 Be7 5. Nf3 O-O 6. O-O d6 7. Nc3 Qe8 8. b3 diff --git a/crates/openings/data/b.tsv b/crates/openings/data/b.tsv deleted file mode 100644 index ea15fb3..0000000 --- a/crates/openings/data/b.tsv +++ /dev/null @@ -1,782 +0,0 @@ -eco name pgn -B00 Barnes Defense 1. e4 f6 -B00 Borg Defense 1. e4 g5 -B00 Borg Defense: Borg Gambit 1. e4 g5 2. d4 Bg7 -B00 Borg Defense: Troon Gambit 1. e4 g5 2. d4 h6 3. h4 g4 -B00 Borg Defense: Zilbermints Gambit 1. e4 g5 2. d4 e5 -B00 Carr Defense 1. e4 h6 -B00 Carr Defense: Zilbermints Gambit 1. e4 h6 2. d4 e5 -B00 Duras Gambit 1. e4 f5 -B00 Fried Fox Defense 1. e4 f6 2. d4 Kf7 -B00 Goldsmith Defense 1. e4 h5 -B00 Goldsmith Defense: Picklepuss Defense 1. e4 h5 2. d4 Nf6 -B00 Hippopotamus Defense 1. e4 Nh6 -B00 Hippopotamus Defense 1. e4 Nh6 2. d4 g6 3. c4 f6 -B00 King's Pawn Game 1. e4 -B00 Lemming Defense 1. e4 Na6 -B00 Lion Defense: Lion's Jaw 1. e4 d6 2. d4 Nf6 3. f3 -B00 Nimzowitsch Defense 1. e4 Nc6 -B00 Nimzowitsch Defense 1. e4 Nc6 2. d4 -B00 Nimzowitsch Defense: Breyer Variation 1. e4 Nc6 2. Nc3 Nf6 3. d4 e5 -B00 Nimzowitsch Defense: Colorado Countergambit 1. e4 Nc6 2. Nf3 f5 -B00 Nimzowitsch Defense: Colorado Countergambit Accepted 1. e4 Nc6 2. Nf3 f5 3. exf5 -B00 Nimzowitsch Defense: Declined Variation 1. e4 Nc6 2. Nf3 -B00 Nimzowitsch Defense: El Columpio Defense 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 -B00 Nimzowitsch Defense: El Columpio Defense, El Columpio Gambit 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 4. d4 d6 5. h3 Nh6 6. e6 -B00 Nimzowitsch Defense: El Columpio Defense, Exchange Variation 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 4. d4 d6 5. h3 Nh6 6. exd6 -B00 Nimzowitsch Defense: El Columpio Defense, Pin Variation 1. e4 Nc6 2. Nf3 Nf6 3. e5 Ng4 4. d4 d6 5. h3 Nh6 6. Bb5 -B00 Nimzowitsch Defense: Franco-Nimzowitsch Variation 1. e4 Nc6 2. Nf3 e6 -B00 Nimzowitsch Defense: French Connection 1. e4 Nc6 2. Nc3 e6 -B00 Nimzowitsch Defense: Hornung Gambit 1. e4 Nc6 2. d4 d5 3. Be3 -B00 Nimzowitsch Defense: Kennedy Variation 1. e4 Nc6 2. d4 e5 -B00 Nimzowitsch Defense: Kennedy Variation, Bielefelder Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 Bc5 -B00 Nimzowitsch Defense: Kennedy Variation, Hammer Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 f6 -B00 Nimzowitsch Defense: Kennedy Variation, Herford Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 Qh4 -B00 Nimzowitsch Defense: Kennedy Variation, Keres Attack 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. Nc3 -B00 Nimzowitsch Defense: Kennedy Variation, Linksspringer Variation 1. e4 Nc6 2. d4 e5 3. d5 -B00 Nimzowitsch Defense: Kennedy Variation, Main Line 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. f4 Ng6 -B00 Nimzowitsch Defense: Kennedy Variation, Paulsen Attack 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. Nf3 -B00 Nimzowitsch Defense: Kennedy Variation, Riemann Defense 1. e4 Nc6 2. d4 e5 3. dxe5 Nxe5 4. f4 Nc6 -B00 Nimzowitsch Defense: Kennedy Variation, de Smet Gambit 1. e4 Nc6 2. d4 e5 3. dxe5 d6 -B00 Nimzowitsch Defense: Mikenas Variation 1. e4 Nc6 2. d4 d6 -B00 Nimzowitsch Defense: Neo-Mongoloid Defense 1. e4 Nc6 2. d4 f6 -B00 Nimzowitsch Defense: Pirc Connection 1. e4 Nc6 2. Nc3 g6 -B00 Nimzowitsch Defense: Pseudo-Spanish Variation 1. e4 Nc6 2. Bb5 -B00 Nimzowitsch Defense: Scandinavian Variation 1. e4 Nc6 2. d4 d5 -B00 Nimzowitsch Defense: Scandinavian Variation, Aachen Gambit 1. e4 Nc6 2. d4 d5 3. exd5 Nb4 -B00 Nimzowitsch Defense: Scandinavian Variation, Advance Variation 1. e4 Nc6 2. d4 d5 3. e5 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation 1. e4 Nc6 2. d4 d5 3. Nc3 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Brandics Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 a6 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Erben Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 g6 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Heinola-Deppe Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 e5 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Nimzowitsch Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 4. d5 Ne5 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Richter Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 4. d5 Nb8 5. f3 -B00 Nimzowitsch Defense: Scandinavian Variation, Bogoljubow Variation, Vehre Variation 1. e4 Nc6 2. d4 d5 3. Nc3 Nf6 -B00 Nimzowitsch Defense: Scandinavian Variation, Exchange Variation 1. e4 Nc6 2. d4 d5 3. exd5 Qxd5 -B00 Nimzowitsch Defense: Scandinavian Variation, Exchange Variation, Marshall Gambit 1. e4 Nc6 2. d4 d5 3. exd5 Qxd5 4. Nc3 -B00 Nimzowitsch Defense: Wheeler Gambit 1. e4 Nc6 2. b4 -B00 Nimzowitsch Defense: Williams Variation 1. e4 Nc6 2. Nf3 d6 -B00 Nimzowitsch Defense: Woodchuck Variation 1. e4 Nc6 2. d4 a6 -B00 Owen Defense 1. e4 b6 -B00 Owen Defense: Guatemala Defense 1. e4 b6 2. d4 Ba6 -B00 Owen Defense: Hekili-Loa Gambit 1. e4 b6 2. d4 c5 3. dxc5 Nc6 -B00 Owen Defense: Matovinsky Gambit 1. e4 b6 2. d4 Bb7 3. Bd3 f5 4. exf5 Bxg2 5. Qh5+ g6 -B00 Owen Defense: Naselwaus Gambit 1. e4 b6 2. d4 Bb7 3. Bg5 -B00 Owen Defense: Smith Gambit 1. e4 b6 2. d4 Bb7 3. Nf3 -B00 Owen Defense: Unicorn Variation 1. e4 f6 2. d4 b6 3. c4 Bb7 -B00 Owen Defense: Wind Gambit 1. e4 b6 2. d4 Bb7 3. f3 e5 -B00 Pirc Defense 1. e4 d6 -B00 Pirc Defense 1. e4 d6 2. d4 -B00 Pirc Defense 1. e4 d6 2. d4 Nf6 -B00 Pirc Defense: Roscher Gambit 1. e4 d6 2. d4 Nf6 3. Nf3 -B00 Rat Defense: Antal Defense 1. e4 d6 2. d4 Nd7 -B00 Rat Defense: Fuller Gambit 1. e4 d6 2. f4 d5 3. exd5 Nf6 -B00 Rat Defense: Harmonist 1. e4 d6 2. f4 -B00 Rat Defense: Petruccioli Attack 1. e4 d6 2. h4 -B00 Rat Defense: Spike Attack 1. e4 d6 2. g4 -B00 St. George Defense 1. e4 a6 -B00 St. George Defense: Polish Variation 1. e4 a6 2. d4 b5 3. Nf3 Bb7 4. Bd3 e6 -B00 St. George Defense: San Jorge Variation 1. e4 a6 2. d4 b5 3. Nf3 Bb7 4. Bd3 d6 5. O-O g6 6. c3 Bg7 -B00 St. George Defense: Zilbermints Gambit 1. e4 a6 2. d4 e5 -B00 Van Geet Opening: Berlin Gambit 1. e4 Nc6 2. d4 d5 3. Nc3 dxe4 4. d5 -B00 Ware Defense 1. e4 a5 -B00 Ware Defense: Snagglepuss Defense 1. e4 a5 2. d4 Nc6 -B01 Scandinavian Defense 1. e4 d5 -B01 Scandinavian Defense 1. e4 d5 2. b3 -B01 Scandinavian Defense: Anderssen Counterattack 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 -B01 Scandinavian Defense: Anderssen Counterattack, Collijn Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 5. Nf3 Bg4 -B01 Scandinavian Defense: Anderssen Counterattack, Goteborg System 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 5. Nf3 -B01 Scandinavian Defense: Anderssen Counterattack, Orthodox Attack 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 e5 5. dxe5 Nc6 6. Nf3 Bb4 7. Bd2 -B01 Scandinavian Defense: Blackburne Gambit 1. e4 d5 2. exd5 c6 3. dxc6 Nxc6 -B01 Scandinavian Defense: Blackburne-Kloosterboer Gambit 1. e4 d5 2. exd5 c6 -B01 Scandinavian Defense: Boehnke Gambit 1. e4 d5 2. exd5 e5 3. dxe6 Bxe6 -B01 Scandinavian Defense: Bronstein Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 4. d4 Nf6 5. Nf3 a6 -B01 Scandinavian Defense: Classical Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 5. Nf3 Bf5 -B01 Scandinavian Defense: Grünfeld Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 5. Nf3 Bf5 6. Ne5 c6 7. g4 -B01 Scandinavian Defense: Gubinsky-Melts Defense 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 -B01 Scandinavian Defense: Icelandic-Palme Gambit 1. e4 d5 2. exd5 Nf6 3. c4 e6 -B01 Scandinavian Defense: Kiel Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 4. c4 Nb4 -B01 Scandinavian Defense: Kloosterboer Gambit 1. e4 d5 2. exd5 c6 3. dxc6 e5 -B01 Scandinavian Defense: Kádas Gambit 1. e4 d5 2. exd5 Nf6 3. d4 c6 4. dxc6 e5 -B01 Scandinavian Defense: Lasker Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 5. Nf3 Bg4 6. h3 -B01 Scandinavian Defense: Main Line 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 -B01 Scandinavian Defense: Main Line, Leonhardt Gambit 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. b4 -B01 Scandinavian Defense: Main Line, Mieses Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qa5 4. d4 Nf6 -B01 Scandinavian Defense: Marshall Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 -B01 Scandinavian Defense: Mieses-Kotroc Variation 1. e4 d5 2. exd5 Qxd5 -B01 Scandinavian Defense: Modern Variation 1. e4 d5 2. exd5 Nf6 -B01 Scandinavian Defense: Modern Variation 1. e4 d5 2. exd5 Nf6 3. d4 -B01 Scandinavian Defense: Modern Variation, Gipslis Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 4. Nf3 Bg4 -B01 Scandinavian Defense: Modern Variation, Wing Gambit 1. e4 d5 2. exd5 Nf6 3. d4 g6 4. c4 b5 -B01 Scandinavian Defense: Panov Transfer 1. e4 d5 2. exd5 Nf6 3. c4 c6 -B01 Scandinavian Defense: Portuguese Gambit 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 -B01 Scandinavian Defense: Portuguese Gambit, Banker Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. c4 -B01 Scandinavian Defense: Portuguese Gambit, Classical Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Nf3 -B01 Scandinavian Defense: Portuguese Gambit, Correspondence Refutation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. g4 -B01 Scandinavian Defense: Portuguese Gambit, Elbow Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Bb5+ c6 -B01 Scandinavian Defense: Portuguese Gambit, Jadoul Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. Bb5+ Nbd7 6. c4 -B01 Scandinavian Defense: Portuguese Gambit, Lusophobe Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Bb5+ Nbd7 5. Be2 -B01 Scandinavian Defense: Portuguese Gambit, Melbourne Shuffle Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. f3 Bf5 5. Bb5+ Nbd7 6. Nc3 -B01 Scandinavian Defense: Portuguese Gambit, Wuss Variation 1. e4 d5 2. exd5 Nf6 3. d4 Bg4 4. Be2 -B01 Scandinavian Defense: Richter Variation 1. e4 d5 2. exd5 Nf6 3. d4 Nxd5 4. Nf3 g6 -B01 Scandinavian Defense: Richter Variation 1. e4 d5 2. exd5 Nf6 3. d4 g6 -B01 Scandinavian Defense: Schiller-Pytel Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 4. d4 c6 -B01 Scandinavian Defense: Schiller-Pytel Variation, Modern Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd6 4. d4 Nf6 5. Bc4 c6 6. Nge2 Bf5 7. Bf4 Qb4 -B01 Scandinavian Defense: Valencian Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd8 -B01 Scandinavian Defense: Valencian Variation, Ilundain Variation 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd8 4. d4 Nf6 5. Nf3 c6 -B01 Scandinavian Defense: Valencian Variation, Main Line 1. e4 d5 2. exd5 Qxd5 3. Nc3 Qd8 4. d4 Nf6 5. Nf3 Bg4 -B01 Scandinavian Defense: Zilbermints Gambit 1. e4 d5 2. b4 -B01 Van Geet Opening: Grünfeld Defense 1. e4 d5 2. Nc3 dxe4 3. Nxe4 e5 -B02 Alekhine Defense 1. e4 Nf6 -B02 Alekhine Defense: Brooklyn Variation 1. e4 Nf6 2. e5 Ng8 -B02 Alekhine Defense: Brooklyn Variation, Everglades Variation 1. e4 Nf6 2. e5 Ng8 3. d4 f5 -B02 Alekhine Defense: Buckley Attack 1. e4 Nf6 2. e5 Nd5 3. Na3 -B02 Alekhine Defense: Hunt Variation, Lasker Simul Gambit 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Bc4 e6 6. Nc3 -B02 Alekhine Defense: Hunt Variation, Matsukevich Gambit 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Nc3 Nxc3 6. dxc3 d6 7. Bg5 -B02 Alekhine Defense: Hunt Variation, Mikenas Gambit 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Bc4 e6 6. Nc3 d6 7. Nxd5 exd5 8. Bxd5 -B02 Alekhine Defense: Kmoch Variation 1. e4 Nf6 2. e5 Nd5 3. Bc4 Nb6 4. Bb3 c5 5. d3 -B02 Alekhine Defense: Krejcik Variation 1. e4 Nf6 2. Bc4 -B02 Alekhine Defense: Krejcik Variation, Krejcik Gambit 1. e4 Nf6 2. Bc4 Nxe4 3. Bxf7+ -B02 Alekhine Defense: Maróczy Variation 1. e4 Nf6 2. d3 -B02 Alekhine Defense: Mokele Mbembe 1. e4 Nf6 2. e5 Ne4 -B02 Alekhine Defense: Mokele Mbembe, Modern Line 1. e4 Nf6 2. e5 Ne4 3. d4 f6 -B02 Alekhine Defense: Mokele Mbembe, Vavra Defense 1. e4 Nf6 2. e5 Ne4 3. d4 e6 -B02 Alekhine Defense: Normal Variation 1. e4 Nf6 2. e5 Nd5 -B02 Alekhine Defense: Scandinavian Variation 1. e4 Nf6 2. Nc3 d5 -B02 Alekhine Defense: Scandinavian Variation, Geschev Gambit 1. e4 Nf6 2. Nc3 d5 3. exd5 c6 -B02 Alekhine Defense: Scandinavian Variation, Myers Gambit 1. e4 Nf6 2. Nc3 d5 3. d3 dxe4 4. Bg5 -B02 Alekhine Defense: Spielmann Gambit 1. e4 Nf6 2. Nc3 d5 3. e5 Nfd7 4. e6 -B02 Alekhine Defense: Steiner Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. b3 -B02 Alekhine Defense: Sämisch Attack 1. e4 Nf6 2. e5 Nd5 3. Nc3 -B02 Alekhine Defense: The Squirrel 1. e4 Nf6 2. e5 Nd5 3. c4 Nf4 -B02 Alekhine Defense: Two Pawns Attack 1. e4 Nf6 2. e5 Nd5 3. c4 -B02 Alekhine Defense: Two Pawns Attack, Lasker Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 -B02 Alekhine Defense: Two Pawns Attack, Mikenas Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. c5 Nd5 5. Bc4 e6 6. Nc3 d6 -B02 Alekhine Defense: Two Pawns Attack, Tate Variation 1. e4 Nf6 2. e5 Nd5 3. c4 Nb6 4. a4 -B02 Alekhine Defense: Welling Variation 1. e4 Nf6 2. e5 Nd5 3. b3 -B03 Alekhine Defense 1. e4 Nf6 2. e5 Nd5 3. d4 -B03 Alekhine Defense 1. e4 Nf6 2. e5 Nd5 3. d4 d6 -B03 Alekhine Defense 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 -B03 Alekhine Defense: Balogh Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Bc4 -B03 Alekhine Defense: Exchange Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. exd6 -B03 Alekhine Defense: Exchange Variation, Karpov Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. exd6 cxd6 6. Nc3 g6 7. h3 Bg7 8. Nf3 O-O 9. Be2 Nc6 10. O-O Bf5 11. Bf4 -B03 Alekhine Defense: Exchange Variation, Voronezh Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. exd6 cxd6 6. Nc3 g6 7. Be3 Bg7 8. Rc1 O-O 9. b3 -B03 Alekhine Defense: Four Pawns Attack 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 -B03 Alekhine Defense: Four Pawns Attack, Cambridge Gambit 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 g5 -B03 Alekhine Defense: Four Pawns Attack, Fianchetto Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 g6 -B03 Alekhine Defense: Four Pawns Attack, Ilyin-Zhenevsky Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Nc6 7. Nf3 Bg4 8. e6 fxe6 9. c5 -B03 Alekhine Defense: Four Pawns Attack, Korchnoi Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Bf5 7. Nc3 e6 8. Nf3 Be7 9. Be2 O-O 10. O-O f6 -B03 Alekhine Defense: Four Pawns Attack, Main Line 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Nc6 7. Be3 -B03 Alekhine Defense: Four Pawns Attack, Tartakower Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 dxe5 6. fxe5 Nc6 7. Be3 Bf5 8. Nc3 e6 9. Nf3 Qd7 10. Be2 O-O-O 11. O-O Be7 -B03 Alekhine Defense: Four Pawns Attack, Trifunovic Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. f4 Bf5 -B03 Alekhine Defense: Hunt Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. c5 -B03 Alekhine Defense: Modern Variation, Alekhine Gambit 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. c4 Nb6 5. Nf3 Bg4 6. Be2 -B03 Alekhine Defense: O'Sullivan Gambit 1. e4 Nf6 2. e5 Nd5 3. d4 b5 -B04 Alekhine Defense: Modern Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 -B04 Alekhine Defense: Modern Variation, Alburt Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 g6 -B04 Alekhine Defense: Modern Variation, Keres Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 g6 5. Bc4 Nb6 6. Bb3 Bg7 7. a4 -B04 Alekhine Defense: Modern Variation, Larsen Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 dxe5 -B04 Alekhine Defense: Modern Variation, Larsen-Haakert Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Nc6 -B04 Alekhine Defense: Modern Variation, Schmid Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Nb6 -B05 Alekhine Defense: Modern Variation, Alekhine Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. c4 -B05 Alekhine Defense: Modern Variation, Flohr Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. Be2 c6 -B05 Alekhine Defense: Modern Variation, Main Line 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 -B05 Alekhine Defense: Modern Variation, Panov Variation 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. h3 -B05 Alekhine Defense: Modern Variation, Vitolins Attack 1. e4 Nf6 2. e5 Nd5 3. d4 d6 4. Nf3 Bg4 5. c4 Nb6 6. d5 -B06 Modern Defense 1. e4 g6 -B06 Modern Defense 1. e4 g6 2. d4 Bg7 -B06 Modern Defense: Anti-Modern 1. e4 g6 2. d4 Bg7 3. Nc3 c6 4. Bc4 d6 5. Qe2 -B06 Modern Defense: Bishop Attack 1. e4 g6 2. d4 Bg7 3. Bc4 -B06 Modern Defense: Bishop Attack, Bücker Gambit 1. e4 g6 2. d4 Bg7 3. Bc4 b5 -B06 Modern Defense: Bishop Attack, Monkey's Bum 1. e4 g6 2. Bc4 Bg7 3. Qf3 e6 4. d4 Bxd4 -B06 Modern Defense: Dunworthy Variation 1. e4 g6 2. d4 Bg7 3. c4 d5 4. exd5 c6 5. dxc6 Bxd4 -B06 Modern Defense: Fianchetto Gambit 1. e4 g6 2. d4 f5 -B06 Modern Defense: Gurgenidze Defense 1. e4 g6 2. d4 Bg7 3. Nc3 c6 4. f4 d5 5. e5 h5 -B06 Modern Defense: Lizard Defense, Mittenberger Gambit 1. e4 g6 2. d4 Bg7 3. Nc3 d5 -B06 Modern Defense: Masur Gambit 1. e4 g6 2. d4 Nh6 3. Nc3 f5 4. Bxh6 Bxh6 5. exf5 O-O -B06 Modern Defense: Modern Pterodactyl 1. e4 g6 2. d4 Bg7 3. Nc3 c5 -B06 Modern Defense: Mongredien Defense, with Nc3 1. e4 g6 2. d4 Bg7 3. Nc3 b6 -B06 Modern Defense: Mongredien Defense, with Nf3 1. e4 g6 2. d4 Bg7 3. Nf3 b6 -B06 Modern Defense: Norwegian Defense 1. e4 g6 2. d4 Nf6 -B06 Modern Defense: Norwegian Defense, Norwegian Gambit 1. e4 g6 2. d4 Nf6 3. e5 Nh5 4. Be2 d6 -B06 Modern Defense: Pseudo-Austrian Attack 1. e4 g6 2. d4 Bg7 3. Nc3 d6 4. f4 -B06 Modern Defense: Semi-Averbakh Variation, Pterodactyl Variation Declined 1. e4 g6 2. d4 Bg7 3. c4 c5 4. Nf3 d6 5. Be2 Qa5+ -B06 Modern Defense: Standard Defense 1. e4 g6 2. d4 Bg7 3. Nc3 d6 -B06 Modern Defense: Standard Line 1. e4 g6 2. d4 Bg7 3. Nc3 -B06 Modern Defense: Three Pawns Attack 1. e4 g6 2. d4 Bg7 3. f4 -B06 Modern Defense: Two Knights Variation 1. e4 g6 2. d4 Bg7 3. Nc3 d6 4. Nf3 -B06 Modern Defense: Two Knights Variation, Suttles Variation 1. e4 g6 2. d4 Bg7 3. Nc3 c6 4. Nf3 d6 -B06 Modern Defense: Two Knights Variation, Suttles Variation, Tal Gambit 1. e4 g6 2. d4 Bg7 3. Nc3 d6 4. Nf3 c6 5. Bg5 Qb6 6. Qd2 Qxb2 -B06 Modern Defense: Westermann Gambit 1. e4 g6 2. d4 Bg7 3. Bd2 -B06 Modern Defense: Wind Gambit 1. e4 g6 2. d4 Bg7 3. Bd3 -B06 Pterodactyl Defense: Austrian, Austriadactylus Western 1. e4 g6 2. d4 Bg7 3. f4 c5 4. Nf3 Qa5+ -B06 Pterodactyl Defense: Austrian, Grand Prix Pterodactyl 1. e4 g6 2. Nc3 Bg7 3. f4 c5 4. Nf3 Qa5 -B06 Pterodactyl Defense: Austrian, Pteranodon 1. e4 g6 2. d4 Bg7 3. f4 c5 4. c3 Qa5 -B06 Pterodactyl Defense: Central, Anhanguera 1. e4 g6 2. d4 Bg7 3. c4 c5 4. Nc3 d6 5. Be3 Qa5 -B06 Pterodactyl Defense: Central, Benoni Quetzalcoatlus 1. e4 g6 2. d4 Bg7 3. c4 c5 4. d5 d6 5. Nc3 Qa5 -B06 Pterodactyl Defense: Central, Quetzalcoatlus Gambit 1. e4 g6 2. d4 Bg7 3. c4 c5 4. Nc3 d6 5. dxc5 Qa5 -B06 Pterodactyl Defense: Eastern, Anhanguera 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. Be3 -B06 Pterodactyl Defense: Eastern, Benoni 1. d4 g6 2. e4 Bg7 3. Nc3 c5 4. d5 -B06 Pterodactyl Defense: Eastern, Benoni Pteranodon 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. d5 Bxc3+ 5. bxc3 Qa5 -B06 Pterodactyl Defense: Eastern, Benoni Pterodactyl 1. d4 g6 2. Nc3 Bg7 3. e4 c5 4. d5 Qa5 -B06 Pterodactyl Defense: Eastern, Pteranodon 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. dxc5 Bxc3+ 5. bxc3 Qa5 -B06 Pterodactyl Defense: Eastern, Rhamphorhynchus 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. dxc5 Qa5 -B06 Pterodactyl Defense: Fianchetto, King Pterodactyl 1. e4 g6 2. d4 Bg7 3. g3 c5 4. Nf3 Qa5+ -B06 Pterodactyl Defense: Fianchetto, Rhamphorhynchus 1. e4 g6 2. d4 Bg7 3. g3 c5 4. dxc5 Qa5+ -B06 Pterodactyl Defense: Sicilian, Quetzalcoatlus 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. Nf3 Qa5 5. Be2 d6 -B06 Pterodactyl Defense: Sicilian, Siroccopteryx 1. e4 g6 2. d4 Bg7 3. Nc3 c5 4. Nf3 Qa5 5. Bc4 -B06 Pterodactyl Defense: Western, Anhanguera 1. e4 g6 2. d4 Bg7 3. Nf3 c5 4. Be3 Qa5+ -B06 Pterodactyl Defense: Western, Siroccopteryx 1. e4 g6 2. Nf3 Bg7 3. d4 c5 4. Bc4 cxd4 5. Nxd4 Qa5+ -B06 Rat Defense: Accelerated Gurgenidze 1. e4 g6 2. d4 d6 3. Nc3 c6 -B07 Czech Defense 1. e4 d6 2. d4 Nf6 3. Nc3 c6 -B07 King's Pawn Game: Maróczy Defense 1. e4 d6 2. d4 e5 -B07 Lion Defense 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 -B07 Lion Defense: Anti-Philidor 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. f4 -B07 Lion Defense: Anti-Philidor, Lion's Cave 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. f4 e5 -B07 Lion Defense: Anti-Philidor, Lion's Cave, Lion Claw Gambit 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. f4 e5 5. Nf3 exd4 6. Qxd4 c6 7. Bc4 d5 -B07 Lion Defense: Bayonet Attack 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. g4 -B07 Modern Defense: Geller's System 1. e4 g6 2. d4 Bg7 3. Nf3 d6 4. c3 -B07 Pirc Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 -B07 Pirc Defense: 150 Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 c6 5. Qd2 -B07 Pirc Defense: 150 Attack, Inner Doll Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 c6 5. Qd2 Bg4 -B07 Pirc Defense: 150 Attack, Sveshnikov-Jansa Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 c6 5. h3 -B07 Pirc Defense: Bayonet Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be2 Bg7 5. h4 -B07 Pirc Defense: Byrne Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Bg5 -B07 Pirc Defense: Chinese Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be2 Bg7 5. g4 -B07 Pirc Defense: Kholmov System 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Bc4 -B07 Pirc Defense: Sveshnikov System 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. g3 -B08 Pirc Defense: Classical Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 -B08 Pirc Defense: Classical Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 -B08 Pirc Defense: Classical Variation, Quiet System 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 -B08 Pirc Defense: Classical Variation, Quiet System, Chigorin Line 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 O-O 6. O-O Nc6 -B08 Pirc Defense: Classical Variation, Quiet System, Czech Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 O-O 6. O-O c6 -B08 Pirc Defense: Classical Variation, Quiet System, Parma Defense 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. Be2 O-O 6. O-O Bg4 -B08 Pirc Defense: Classical Variation, Schlechter Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Nf3 Bg7 5. h3 -B09 Pirc Defense: Austrian Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 -B09 Pirc Defense: Austrian Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O -B09 Pirc Defense: Austrian Attack, Dragon Formation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 c5 -B09 Pirc Defense: Austrian Attack, Kurajica Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. Be3 -B09 Pirc Defense: Austrian Attack, Ljubojevic Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Bc4 -B09 Pirc Defense: Austrian Attack, Unzicker Attack 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. e5 -B09 Pirc Defense: Austrian Attack, Unzicker Attack, Bronstein Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. e5 Nfd7 7. h4 -B09 Pirc Defense: Austrian Attack, Weiss Variation 1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. f4 Bg7 5. Nf3 O-O 6. Bd3 -B10 Caro-Kann Defense 1. e4 c6 -B10 Caro-Kann Defense 1. e4 c6 2. Nc3 -B10 Caro-Kann Defense 1. e4 c6 2. Nc3 d5 -B10 Caro-Kann Defense: Accelerated Panov Attack 1. e4 c6 2. c4 -B10 Caro-Kann Defense: Accelerated Panov Attack 1. e4 c6 2. c4 d5 -B10 Caro-Kann Defense: Accelerated Panov Attack, Modern Variation 1. e4 c6 2. c4 d5 3. exd5 cxd5 4. cxd5 Nf6 -B10 Caro-Kann Defense: Accelerated Panov Attack, Open Variation 1. e4 c6 2. c4 e5 -B10 Caro-Kann Defense: Accelerated Panov Attack, Pseudo-Scandinavian 1. e4 c6 2. c4 d5 3. exd5 cxd5 4. cxd5 Qxd5 -B10 Caro-Kann Defense: Accelerated Panov Attack, Van Weersel Attack 1. e4 c6 2. c4 d5 3. cxd5 cxd5 4. Qb3 -B10 Caro-Kann Defense: Apocalypse Attack 1. e4 c6 2. Nf3 d5 3. exd5 cxd5 4. Ne5 -B10 Caro-Kann Defense: Breyer Variation 1. e4 c6 2. d3 -B10 Caro-Kann Defense: Breyer Variation, Stein Attack 1. e4 c6 2. d3 d5 3. Nd2 g6 4. Ngf3 Bg7 5. g3 e5 6. Bg2 Ne7 7. O-O O-O 8. b4 -B10 Caro-Kann Defense: Dinic Gambit 1. e4 c6 2. Nf3 d5 3. d3 dxe4 4. Ng5 -B10 Caro-Kann Defense: Endgame Offer 1. e4 c6 2. Nf3 d5 3. d3 -B10 Caro-Kann Defense: Endgame Variation 1. e4 c6 2. Nf3 d5 3. d3 dxe4 4. dxe4 Qxd1+ 5. Kxd1 -B10 Caro-Kann Defense: Euwe Attack 1. e4 c6 2. b3 -B10 Caro-Kann Defense: Goldman Variation 1. e4 c6 2. Nc3 d5 3. Qf3 -B10 Caro-Kann Defense: Hector Gambit 1. e4 c6 2. Nc3 d5 3. Nf3 dxe4 4. Ng5 -B10 Caro-Kann Defense: Hillbilly Attack 1. e4 c6 2. Bc4 -B10 Caro-Kann Defense: Hillbilly Attack, Schaeffer Gambit 1. e4 c6 2. Bc4 d5 3. Bb3 dxe4 4. Qh5 -B10 Caro-Kann Defense: Labahn Attack 1. e4 c6 2. b4 -B10 Caro-Kann Defense: Labahn Attack, Double Gambit 1. e4 c6 2. b4 d5 3. b5 -B10 Caro-Kann Defense: Labahn Attack, Polish Variation 1. e4 c6 2. b4 e5 3. Bb2 -B10 Caro-Kann Defense: Scorpion-Horus Gambit 1. e4 c6 2. Nc3 d5 3. d3 dxe4 4. Bg5 -B10 Caro-Kann Defense: Spike Variation 1. e4 c6 2. g4 -B10 Caro-Kann Defense: Spike Variation, Scorpion-Grob Gambit 1. e4 c6 2. g4 d5 3. Nc3 dxe4 4. d3 -B10 Caro-Kann Defense: St. Patrick's Attack 1. e4 c6 2. Nc3 d5 3. h3 -B10 Caro-Kann Defense: Toikkanen Gambit 1. e4 c6 2. c4 d5 3. e5 -B10 Caro-Kann Defense: Two Knights Attack 1. e4 c6 2. Nc3 d5 3. Nf3 -B11 Caro-Kann Defense: Two Knights Attack, Mindeno Variation 1. e4 c6 2. Nc3 d5 3. Nf3 Bg4 -B11 Caro-Kann Defense: Two Knights Attack, Mindeno Variation, Exchange Line 1. e4 c6 2. Nc3 d5 3. Nf3 Bg4 4. h3 Bxf3 -B11 Caro-Kann Defense: Two Knights Attack, Mindeno Variation, Retreat Line 1. e4 c6 2. Nc3 d5 3. Nf3 Bg4 4. h3 Bh5 -B12 Caro-Kann Defense 1. e4 c6 2. d4 -B12 Caro-Kann Defense 1. e4 c6 2. d4 d5 -B12 Caro-Kann Defense: Advance Variation 1. e4 c6 2. d4 d5 3. e5 -B12 Caro-Kann Defense: Advance Variation, Bayonet Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. g4 -B12 Caro-Kann Defense: Advance Variation, Botvinnik-Carls Defense 1. e4 c6 2. d4 d5 3. e5 c5 -B12 Caro-Kann Defense: Advance Variation, Bronstein Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Ne2 -B12 Caro-Kann Defense: Advance Variation, Prins Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. b4 -B12 Caro-Kann Defense: Advance Variation, Short Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nf3 -B12 Caro-Kann Defense: Advance Variation, Tal Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. h4 -B12 Caro-Kann Defense: Advance Variation, Van der Wiel Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nc3 -B12 Caro-Kann Defense: Advance Variation, Van der Wiel Attack 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nc3 e6 5. g4 Bg6 6. Nge2 c5 7. h4 -B12 Caro-Kann Defense: Advance Variation, Van der Wiel Attack, Dreyev Defense 1. e4 c6 2. d4 d5 3. e5 Bf5 4. Nc3 Qb6 -B12 Caro-Kann Defense: Advance, Short Variation 1. e4 c6 2. d4 d5 3. e5 Bf5 4. c3 e6 5. Be2 -B12 Caro-Kann Defense: De Bruycker Defense 1. e4 c6 2. d4 Na6 -B12 Caro-Kann Defense: De Bruycker Defense 1. e4 c6 2. d4 Na6 3. Nc3 Nc7 -B12 Caro-Kann Defense: Edinburgh Variation 1. e4 c6 2. d4 d5 3. Nd2 Qb6 -B12 Caro-Kann Defense: Maróczy Variation 1. e4 c6 2. d4 d5 3. f3 -B12 Caro-Kann Defense: Maróczy Variation, Maróczy Gambit 1. e4 c6 2. d4 d5 3. f3 dxe4 4. fxe4 e5 5. Nf3 exd4 6. Bc4 -B12 Caro-Kann Defense: Masi Variation 1. e4 c6 2. d4 Nf6 -B12 Caro-Kann Defense: Massachusetts Defense 1. e4 c6 2. d4 f5 -B12 Caro-Kann Defense: Mieses Attack, Landau Gambit 1. e4 c6 2. d4 d5 3. Bd3 Nf6 4. e5 Nfd7 5. e6 -B12 Caro-Kann Defense: Mieses Gambit 1. e4 c6 2. d4 d5 3. Be3 -B12 Caro-Kann Defense: Modern Variation 1. e4 c6 2. d4 d5 3. Nd2 -B12 Caro-Kann Defense: Ulysses Gambit 1. e4 c6 2. d4 d5 3. Nf3 dxe4 4. Ng5 -B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 -B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 -B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. Bf4 -B13 Caro-Kann Defense: Exchange Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. Nf3 Nc6 -B13 Caro-Kann Defense: Exchange Variation, Bulla Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. g4 -B13 Caro-Kann Defense: Exchange Variation, Rubinstein Variation 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. Bd3 Nc6 5. c3 Nf6 6. Bf4 -B13 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 -B13 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 -B13 Caro-Kann Defense: Panov Attack, Gunderam Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. c5 -B13 Caro-Kann Defense: Panov Attack, Modern Defense 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 -B13 Caro-Kann Defense: Panov Attack, Modern Defense, Carlsbad Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 e6 -B13 Caro-Kann Defense: Panov Attack, Modern Defense, Czerniak Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 Qa5 -B13 Caro-Kann Defense: Panov Attack, Modern Defense, Mieses Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Nf3 Bg4 -B13 Caro-Kann Defense: Panov Attack, Modern Defense, Reifir-Spielmann Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 Qb6 -B13 Caro-Kann Defense: Panov-Botvinnik, Herzog Defense 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Bg5 dxc4 7. d5 Na5 -B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 e6 -B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nc6 5. Nc3 Nf6 6. Nf3 e6 7. cxd5 exd5 8. Bb5 Bg4 -B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nc6 5. Nc3 Nf6 6. Nf3 e6 7. cxd5 exd5 8. Bb5 Bd6 9. Bg5 O-O 10. O-O -B14 Caro-Kann Defense: Panov Attack 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 Nc6 6. Nf3 e6 7. c5 -B14 Caro-Kann Defense: Panov Attack, Fianchetto Defense 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 g6 -B14 Caro-Kann Defense: Panov Attack, Fianchetto Defense, Fianchetto Gambit 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 g6 6. cxd5 Bg7 -B14 Caro-Kann Defense: Panov Attack, Main Line 1. e4 c6 2. d4 d5 3. exd5 cxd5 4. c4 Nf6 5. Nc3 e6 6. Nf3 Bb4 -B15 Caro-Kann Defense 1. e4 c6 2. d4 d5 3. Nc3 -B15 Caro-Kann Defense 1. e4 c6 2. d4 d5 3. Nc3 dxe4 -B15 Caro-Kann Defense: Alekhine Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Bd3 -B15 Caro-Kann Defense: Alien Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Ng5 h6 6. Nxf7 -B15 Caro-Kann Defense: Campomanes Attack 1. e4 c6 2. d4 d5 3. Nc3 Nf6 -B15 Caro-Kann Defense: Forgacs Variation 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ exf6 6. Bc4 -B15 Caro-Kann Defense: Gurgenidze Counterattack 1. e4 c6 2. d4 d5 3. Nc3 b5 -B15 Caro-Kann Defense: Gurgenidze System 1. e4 c6 2. d4 d5 3. Nc3 g6 -B15 Caro-Kann Defense: Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 -B15 Caro-Kann Defense: Rasa-Studier Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. f3 -B15 Caro-Kann Defense: Tartakower Variation 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ exf6 -B15 Caro-Kann Defense: Tartakower Variation, Perlis Line 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ exf6 6. c3 Bd6 7. Bd3 O-O 8. Qc2 h6 -B15 Caro-Kann Defense: von Hennig Gambit 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Bc4 -B16 Caro-Kann Defense: Bronstein-Larsen Variation 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nf6 5. Nxf6+ gxf6 -B16 Caro-Kann Defense: Finnish Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 h6 -B17 Caro-Kann Defense: Karpov Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 -B17 Caro-Kann Defense: Karpov Variation, Modern Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Ng5 Ngf6 6. Bd3 e6 7. N1f3 Bd6 8. Qe2 h6 9. Ne4 Nxe4 10. Qxe4 -B17 Caro-Kann Defense: Karpov Variation, Modern Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Ng5 -B17 Caro-Kann Defense: Karpov Variation, Modern Variation, Ivanchuk Defense 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Ng5 Ndf6 -B17 Caro-Kann Defense: Karpov Variation, Modern Variation, Kasparov Attack 1. e4 c6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6 6. Ng3 -B17 Caro-Kann Defense: Karpov Variation, Smyslov Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Bc4 Ngf6 6. Ng5 e6 7. Qe2 Nb6 -B17 Caro-Kann Defense: Karpov Variation, Smyslov Variation, Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Bc4 Ngf6 6. Ng5 e6 7. Qe2 Nb6 8. Bb3 -B17 Caro-Kann Defense: Karpov Variation, Tiviakov-Fischer Attack 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Bc4 Ngf6 6. Nxf6+ Nxf6 -B18 Caro-Kann Defense: Classical Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 -B18 Caro-Kann Defense: Classical Variation, Flohr Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. Nh3 -B18 Caro-Kann Defense: Classical Variation, Main Line 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 -B18 Caro-Kann Defense: Classical Variation, Maróczy Attack 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. f4 -B18 Caro-Kann Defense: Martian Gambit 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng5 Bg6 6. N1f3 h6 7. Ne6 -B19 Caro-Kann Defense: Classical Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 -B19 Caro-Kann Defense: Classical Variation, Lobron System 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 8. h5 Bh7 9. Bd3 Bxd3 10. Qxd3 e6 11. Bd2 Ngf6 12. O-O-O Be7 -B19 Caro-Kann Defense: Classical Variation, Seirawan Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 8. h5 Bh7 9. Bd3 Bxd3 10. Qxd3 Ngf6 11. Bd2 e6 12. O-O-O Bd6 -B19 Caro-Kann Defense: Classical Variation, Spassky Variation 1. e4 c6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Bf5 5. Ng3 Bg6 6. h4 h6 7. Nf3 Nd7 8. h5 -B20 Sicilian Defense 1. e4 c5 -B20 Sicilian Defense: Amazon Attack 1. e4 c5 2. Qg4 -B20 Sicilian Defense: Big Clamp Formation 1. e4 c5 2. d3 Nc6 3. c3 d6 4. f4 -B20 Sicilian Defense: Bowdler Attack 1. e4 c5 2. Bc4 -B20 Sicilian Defense: Brick Variation 1. e4 c5 2. Nh3 -B20 Sicilian Defense: Czerniak Attack 1. e4 c5 2. b3 -B20 Sicilian Defense: Czerniak Attack, Queen Fianchetto Variation 1. e4 c5 2. b3 b6 -B20 Sicilian Defense: Euwe Attack, Prins Gambit 1. e4 c5 2. b3 d5 3. Bb2 -B20 Sicilian Defense: Gloria Variation 1. e4 c5 2. c4 d6 3. Nc3 Nc6 4. g3 h5 -B20 Sicilian Defense: Grob Variation 1. e4 c5 2. g4 -B20 Sicilian Defense: Keres Variation 1. e4 c5 2. Ne2 -B20 Sicilian Defense: King David's Opening 1. e4 c5 2. Ke2 -B20 Sicilian Defense: Kronberger Variation 1. e4 c5 2. Na3 -B20 Sicilian Defense: Kronberger Variation, Nemeth Gambit 1. e4 c5 2. Na3 Nc6 3. d4 cxd4 4. Bc4 -B20 Sicilian Defense: Lasker-Dunne Attack 1. e4 c5 2. g3 -B20 Sicilian Defense: Mengarini Variation 1. e4 c5 2. a3 -B20 Sicilian Defense: Myers Attack, with a4 1. e4 c5 2. a4 -B20 Sicilian Defense: Myers Attack, with h4 1. e4 c5 2. h4 -B20 Sicilian Defense: Staunton-Cochrane Variation 1. e4 c5 2. c4 -B20 Sicilian Defense: Wing Gambit 1. e4 c5 2. b4 -B20 Sicilian Defense: Wing Gambit, Abrahams Variation 1. e4 c5 2. b4 cxb4 3. Bb2 -B20 Sicilian Defense: Wing Gambit, Carlsbad Variation 1. e4 c5 2. b4 cxb4 3. a3 bxa3 -B20 Sicilian Defense: Wing Gambit, Marienbad Variation 1. e4 c5 2. b4 cxb4 3. a3 d5 4. exd5 Qxd5 5. Bb2 -B20 Sicilian Defense: Wing Gambit, Marshall Variation 1. e4 c5 2. b4 cxb4 3. a3 -B20 Sicilian Defense: Wing Gambit, Nanu Gambit 1. e4 c5 2. b4 cxb4 3. a3 d5 4. exd5 Qxd5 5. Nf3 e5 6. c4 Qe6 7. Bd3 -B20 Sicilian Defense: Wing Gambit, Romanian Defense 1. e4 c5 2. b4 cxb4 3. a3 d5 4. exd5 Qxd5 5. Nf3 e5 6. Bb2 Nc6 7. c4 Qe6 -B20 Sicilian Defense: Wing Gambit, Santasiere Variation 1. e4 c5 2. b4 cxb4 3. c4 -B21 Bird Opening: Dutch Variation, Batavo Gambit 1. e4 c5 2. f4 d5 3. Nf3 dxe4 -B21 Sicilian Defense: Coles Sicilian Gambit 1. e4 c5 2. d4 cxd4 3. Qxd4 Nc6 4. Qd1 Nf6 5. Bc4 -B21 Sicilian Defense: Halasz Gambit 1. e4 c5 2. d4 cxd4 3. f4 -B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 -B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 e6 -B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 e6 4. d3 -B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 g6 4. Bb5 Bg7 -B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 g6 4. Bb5 Bg7 5. c3 Nf6 -B21 Sicilian Defense: McDonnell Attack 1. e4 c5 2. f4 Nc6 3. Nf3 g6 4. Bb5 Bg7 5. Bxc6 bxc6 6. O-O d6 7. d3 Nf6 -B21 Sicilian Defense: McDonnell Attack, Tal Gambit 1. e4 c5 2. f4 d5 3. exd5 Nf6 -B21 Sicilian Defense: McDonnell Attack, Toilet Variation 1. e4 c5 2. f4 d5 3. Nc3 -B21 Sicilian Defense: Morphy Gambit 1. e4 c5 2. d4 cxd4 3. Nf3 -B21 Sicilian Defense: Morphy Gambit, Andreaschek Gambit 1. e4 c5 2. d4 cxd4 3. Nf3 e5 4. c3 -B21 Sicilian Defense: Smith-Morra Gambit 1. e4 c5 2. d4 -B21 Sicilian Defense: Smith-Morra Gambit 1. e4 c5 2. d4 cxd4 3. c3 -B21 Sicilian Defense: Smith-Morra Gambit Accepted 1. e4 c5 2. d4 cxd4 3. c3 dxc3 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Chicago Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Bc4 e6 6. Nf3 d6 7. O-O a6 8. Qe2 b5 9. Bb3 Ra7 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Chicago Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 d6 5. Nf3 e6 6. Bc4 Nf6 7. O-O a6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Classical Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 d6 6. Bc4 a6 7. O-O Nf6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Danish Variation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nf3 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 g6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 g6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 d6 6. Bc4 g6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Fianchetto Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 d6 5. Nf3 g6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Finegold Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 e6 5. Nf3 d6 6. Bc4 a6 7. O-O Be7 8. Qe2 Nf6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Kan Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 e6 5. Nf3 a6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Larsen Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Qc7 7. Qe2 a6 8. O-O Bd6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Morphy Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Bc5 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Morphy Defense Deferred 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 a6 7. O-O b5 8. Bb3 Bc5 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Paulsen Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 a6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Pin Defense 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Bb4 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Scheveningen Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 d6 6. Bc4 e6 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Siberian Variation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Qc7 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Siberian Variation, Siberian Trap 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Nf3 e6 6. Bc4 Qc7 7. Qe2 Nf6 8. O-O Ng4 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Sozin Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 Nc6 5. Bc4 e6 6. Nf3 d6 7. O-O a6 8. Qe2 b5 -B21 Sicilian Defense: Smith-Morra Gambit Accepted, Taimanov Formation 1. e4 c5 2. d4 cxd4 3. c3 dxc3 4. Nxc3 e6 5. Bc4 a6 6. Nf3 Ne7 -B21 Sicilian Defense: Smith-Morra Gambit Declined, Alapin Formation 1. e4 c5 2. d4 cxd4 3. c3 Nf6 -B21 Sicilian Defense: Smith-Morra Gambit Declined, Center Formation 1. e4 c5 2. d4 cxd4 3. c3 e5 -B21 Sicilian Defense: Smith-Morra Gambit Declined, Dubois Variation 1. e4 c5 2. d4 cxd4 3. c3 d3 4. c4 -B21 Sicilian Defense: Smith-Morra Gambit Declined, Push Variation 1. e4 c5 2. d4 cxd4 3. c3 d3 -B21 Sicilian Defense: Smith-Morra Gambit Declined, Scandinavian Formation 1. e4 c5 2. d4 cxd4 3. c3 d5 -B21 Sicilian Defense: Smith-Morra Gambit Declined, Wing Formation 1. e4 c5 2. d4 cxd4 3. c3 Qa5 -B22 Sicilian Defense: Alapin Variation 1. e4 c5 2. c3 -B22 Sicilian Defense: Alapin Variation, Anti-Alapin Gambit 1. e4 c5 2. c3 d5 3. exd5 Nf6 -B22 Sicilian Defense: Alapin Variation, Barmen Defense 1. e4 c5 2. c3 d5 3. exd5 Qxd5 -B22 Sicilian Defense: Alapin Variation, Barmen Defense 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 g6 5. Nf3 -B22 Sicilian Defense: Alapin Variation, Barmen Defense 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 Nc6 5. Nf3 -B22 Sicilian Defense: Alapin Variation, Barmen Defense, Central Exchange 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 cxd4 5. cxd4 Nc6 6. Nf3 Bg4 -B22 Sicilian Defense: Alapin Variation, Barmen Defense, Endgame Variation 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 cxd4 5. cxd4 Nc6 6. Nf3 Bg4 7. Nc3 Bxf3 8. gxf3 Qxd4 9. Qxd4 Nxd4 -B22 Sicilian Defense: Alapin Variation, Barmen Defense, Milner-Barry Attack 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 Nc6 5. Nf3 cxd4 6. cxd4 e5 7. Nc3 Bb4 8. Be2 -B22 Sicilian Defense: Alapin Variation, Barmen Defense, Modern Line 1. e4 c5 2. c3 d5 3. exd5 Qxd5 4. d4 Nf6 5. Nf3 Bg4 -B22 Sicilian Defense: Alapin Variation, Smith-Morra Declined 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. d4 cxd4 -B22 Sicilian Defense: Alapin Variation, Stoltz Attack 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. Nf3 Nc6 5. Bc4 Nb6 6. Bb3 -B22 Sicilian Defense: Alapin Variation, Stoltz Attack, Ivanchuk Line 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. Nf3 Nc6 5. Bc4 Nb6 6. Bb3 c4 7. Bc2 Qc7 8. Qe2 g5 -B22 Sicilian Defense: Delayed Alapin Variation 1. e4 c5 2. Nf3 e6 3. c3 d5 4. exd5 Qxd5 5. d4 Nf6 -B22 Sicilian Defense: Delayed Alapin Variation 1. e4 c5 2. Nf3 e6 3. c3 d5 4. exd5 exd5 5. Bb5+ Nc6 6. O-O Bd6 7. d4 -B22 Sicilian Defense: Heidenfeld Variation 1. e4 c5 2. c3 Nf6 3. e5 Nd5 4. Nf3 Nc6 5. Na3 -B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 -B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 -B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. g3 -B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. f4 Nc6 4. Nf3 d5 -B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. f4 Nc6 4. Nf3 d5 5. Bb5 -B23 Sicilian Defense: Closed 1. e4 c5 2. Nc3 e6 3. Nge2 a6 4. g3 -B23 Sicilian Defense: Closed, Carlsen Variation 1. e4 c5 2. Nc3 d6 3. d4 cxd4 4. Qxd4 Nc6 5. Qd2 -B23 Sicilian Defense: Closed, Chameleon Variation 1. e4 c5 2. Nc3 Nc6 3. Nge2 -B23 Sicilian Defense: Closed, Grob Attack 1. e4 c5 2. Nc3 Nc6 3. g4 -B23 Sicilian Defense: Closed, Korchnoi Defense 1. e4 c5 2. Nc3 e6 3. g3 d5 -B23 Sicilian Defense: Closed, Portland Attack 1. e4 c5 2. Nc3 Nc6 3. d3 g6 4. g4 -B23 Sicilian Defense: Closed, Traditional 1. e4 c5 2. Nc3 Nc6 -B23 Sicilian Defense: Grand Prix Attack 1. e4 c5 2. Nc3 Nc6 3. f4 -B23 Sicilian Defense: Grand Prix Attack, Schofman Variation 1. e4 c5 2. Nc3 Nc6 3. f4 g6 4. Nf3 Bg7 5. Bc4 e6 6. f5 -B24 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 -B24 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 -B24 Sicilian Defense: Closed, Fianchetto Variation 1. e4 c5 2. Nc3 Nc6 3. g3 -B24 Sicilian Defense: Closed, Smyslov Variation 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 e6 6. Be3 Nd4 7. Nce2 -B25 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 -B25 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. f4 -B25 Sicilian Defense: Closed, Botvinnik Defense, Edge Variation 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. f4 e5 7. Nh3 Nge7 -B25 Sicilian Defense: Closed, Botvinnik Defense, with Nge2 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. Nge2 e5 -B25 Sicilian Defense: Closed, Botvinnik Defense, with f4 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. f4 e5 -B26 Sicilian Defense: Closed 1. e4 c5 2. Nc3 Nc6 3. g3 g6 4. Bg2 Bg7 5. d3 d6 6. Be3 -B27 Modern Defense: Pterodactyl Variation 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 -B27 Pterodactyl Defense: Sicilian, Anhanguera 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 5. Be3 -B27 Pterodactyl Defense: Sicilian, Benoni Gambit 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 5. d5 -B27 Pterodactyl Defense: Sicilian, Pteranodon 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ 5. Nc3 Bxc3+ 6. bxc3 -B27 Pterodactyl Defense: Sicilian, Rhamphorhynchus 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ 5. Nc3 -B27 Pterodactyl Defense: Sicilian, Unpin 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. Nc3 Qa5 5. Bd2 -B27 Pterodactyl Defense: Western, Pterodactyl 1. e4 c5 2. Nf3 g6 3. c3 Bg7 4. d4 Qa5 -B27 Pterodactyl Defense: Western, Rhamphorhynchus 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ -B27 Sicilian Defense 1. e4 c5 2. Nf3 -B27 Sicilian Defense: Acton Extension 1. e4 c5 2. Nf3 g6 3. c4 Bh6 -B27 Sicilian Defense: Brussels Gambit 1. e4 c5 2. Nf3 f5 -B27 Sicilian Defense: Bücker Variation 1. e4 c5 2. Nf3 h6 -B27 Sicilian Defense: Double-Dutch Gambit 1. e4 c5 2. Nf3 f5 3. exf5 Nh6 -B27 Sicilian Defense: Frederico Variation 1. e4 c5 2. Nf3 g6 3. d4 f5 -B27 Sicilian Defense: Hyperaccelerated Dragon 1. e4 c5 2. Nf3 g6 -B27 Sicilian Defense: Hyperaccelerated Dragon 1. e4 c5 2. Nf3 g6 3. d4 -B27 Sicilian Defense: Hyperaccelerated Pterodactyl 1. e4 c5 2. Nf3 g6 3. d4 Bg7 -B27 Sicilian Defense: Hyperaccelerated Pterodactyl, Exchange Variation 1. e4 c5 2. Nf3 g6 3. d4 Bg7 4. dxc5 Qa5+ 5. Nc3 Bxc3+ 6. bxc3 Qxc3+ -B27 Sicilian Defense: Jalalabad Variation 1. e4 c5 2. Nf3 e5 -B27 Sicilian Defense: Katalimov Variation 1. e4 c5 2. Nf3 b6 -B27 Sicilian Defense: Mongoose Variation 1. e4 c5 2. Nf3 Qa5 -B27 Sicilian Defense: Polish Gambit 1. e4 c5 2. Nf3 b5 -B27 Sicilian Defense: Quinteros Variation 1. e4 c5 2. Nf3 Qc7 -B28 Sicilian Defense: O'Kelly Variation 1. e4 c5 2. Nf3 a6 -B28 Sicilian Defense: O'Kelly Variation, Aronin System 1. e4 c5 2. Nf3 a6 3. Be2 -B28 Sicilian Defense: O'Kelly Variation, Kieseritzky System 1. e4 c5 2. Nf3 a6 3. b3 -B28 Sicilian Defense: O'Kelly Variation, Maróczy Bind 1. e4 c5 2. Nf3 a6 3. c4 -B28 Sicilian Defense: O'Kelly Variation, Maróczy Bind, Paulsen Line 1. e4 c5 2. Nf3 a6 3. c4 e6 -B28 Sicilian Defense: O'Kelly Variation, Maróczy Bind, Robatsch Line 1. e4 c5 2. Nf3 a6 3. c4 d6 -B28 Sicilian Defense: O'Kelly Variation, Normal System 1. e4 c5 2. Nf3 a6 3. d4 -B28 Sicilian Defense: O'Kelly Variation, Normal System, Cortlever Gambit 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. Bc4 -B28 Sicilian Defense: O'Kelly Variation, Normal System, Smith-Morra Line 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. c3 -B28 Sicilian Defense: O'Kelly Variation, Normal System, Taimanov Line 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. Nxd4 e5 -B28 Sicilian Defense: O'Kelly Variation, Normal System, Zagorovsky Line 1. e4 c5 2. Nf3 a6 3. d4 cxd4 4. Qxd4 -B28 Sicilian Defense: O'Kelly Variation, Quiet System 1. e4 c5 2. Nf3 a6 3. d3 -B28 Sicilian Defense: O'Kelly Variation, Réti System 1. e4 c5 2. Nf3 a6 3. g3 -B28 Sicilian Defense: O'Kelly Variation, Venice System 1. e4 c5 2. Nf3 a6 3. c3 -B28 Sicilian Defense: O'Kelly Variation, Venice System, Barcza Line 1. e4 c5 2. Nf3 a6 3. c3 Nf6 -B28 Sicilian Defense: O'Kelly Variation, Venice System, Gambit Line 1. e4 c5 2. Nf3 a6 3. c3 d5 4. exd5 Nf6 -B28 Sicilian Defense: O'Kelly Variation, Venice System, Ljubojevic Line 1. e4 c5 2. Nf3 a6 3. c3 b5 -B28 Sicilian Defense: O'Kelly Variation, Venice System, Steiner Line 1. e4 c5 2. Nf3 a6 3. c3 d6 -B28 Sicilian Defense: O'Kelly Variation, Wing Gambit 1. e4 c5 2. Nf3 a6 3. b4 -B28 Sicilian Defense: O'Kelly Variation, Yerevan System 1. e4 c5 2. Nf3 a6 3. Nc3 -B29 Sicilian Defense: Nimzowitsch Variation 1. e4 c5 2. Nf3 Nf6 -B29 Sicilian Defense: Nimzowitsch Variation, Advance Variation 1. e4 c5 2. Nf3 Nf6 3. e5 -B29 Sicilian Defense: Nimzowitsch Variation, Closed Variation 1. e4 c5 2. Nf3 Nf6 3. Nc3 -B29 Sicilian Defense: Nimzowitsch Variation, Exchange Variation 1. e4 c5 2. Nf3 Nf6 3. e5 Nd5 4. Nc3 Nxc3 -B29 Sicilian Defense: Nimzowitsch Variation, Main Line 1. e4 c5 2. Nf3 Nf6 3. e5 Nd5 4. Nc3 e6 5. Nxd5 exd5 6. d4 Nc6 -B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 -B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation, Kharlov-Kramnik Line 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 4. Bc4 Be7 5. d3 d6 6. Nd2 Bg5 -B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation, with Nf6 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 4. Bc4 Be7 5. d3 Nf6 -B30 Sicilian Defense: Closed, Anti-Sveshnikov Variation, with d6 1. e4 c5 2. Nf3 Nc6 3. Nc3 e5 4. Bc4 Be7 5. d3 d6 -B30 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack 1. e4 c5 2. Nf3 Nc6 3. Bb5 -B30 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Brooklyn Retreat Defense 1. e4 c5 2. Nf3 Nc6 3. Bb5 Nb8 -B30 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, San Francisco Gambit 1. e4 c5 2. Nf3 Nc6 3. Bb5 Na5 4. b4 -B30 Sicilian Defense: Old Sicilian 1. e4 c5 2. Nf3 Nc6 -B30 Sicilian Defense: Portsmouth Gambit 1. e4 c5 2. Nf3 Nc6 3. b4 -B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 -B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation, Gufeld Gambit 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. c3 e5 6. d4 -B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation, Lutikov Gambit 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. c3 Nf6 6. d4 -B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Fianchetto Variation, Totsky Attack 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. c3 Nf6 6. Qa4 -B31 Sicilian Defense: Nyezhmetdinov-Rossolimo Attack, Gurgenidze Variation 1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 5. Re1 e5 6. b4 -B32 Sicilian Defense: Accelerated Dragon 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 -B32 Sicilian Defense: Flohr Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Qc7 -B32 Sicilian Defense: Franco-Sicilian Variation 1. e4 c5 2. Nf3 Nc6 3. d4 e6 -B32 Sicilian Defense: Godiva Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Qb6 -B32 Sicilian Defense: Kalashnikov Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 e5 5. Nb5 d6 -B32 Sicilian Defense: Löwenthal Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 e5 -B32 Sicilian Defense: Nimzo-American Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 d5 -B32 Sicilian Defense: O'Kelly Variation, Maróczy Bind, Geller Line 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 a6 5. c4 e5 -B32 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 -B32 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 -B32 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 -B33 Sicilian Defense: Lasker-Pelikan Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 -B33 Sicilian Defense: Lasker-Pelikan Variation, Bird Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 Be6 -B33 Sicilian Defense: Lasker-Pelikan Variation, Exchange Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Nxc6 -B33 Sicilian Defense: Lasker-Pelikan Variation, Retreat Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Nf3 -B33 Sicilian Defense: Lasker-Pelikan Variation, Schlechter Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Nb3 -B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 -B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Bxf6 gxf6 10. Nd5 f5 -B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation, Chelyabinsk Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Nd5 -B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation, Novosibirsk Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Bxf6 gxf6 10. Nd5 Bg7 -B33 Sicilian Defense: Lasker-Pelikan Variation, Sveshnikov Variation, Peresypkin's Sacrifice 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Ndb5 d6 7. Bg5 a6 8. Na3 b5 9. Bxf6 gxf6 10. Nd5 f5 11. Bxb5 -B33 Sicilian Defense: Open 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 -B34 Sicilian Defense: Accelerated Dragon, Exchange Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nxc6 -B34 Sicilian Defense: Accelerated Dragon, Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 -B35 Sicilian Defense: Accelerated Dragon, Modern Bc4 Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 -B35 Sicilian Defense: Dragon Variation, Modern Bc4 Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Bc4 d6 -B36 Sicilian Defense: Accelerated Dragon, Maróczy Bind 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 -B36 Sicilian Defense: Accelerated Dragon, Maróczy Bind, Gurgenidze Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Nf6 6. Nc3 Nxd4 7. Qxd4 d6 -B37 Sicilian Defense: Accelerated Dragon, Maróczy Bind 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 -B37 Sicilian Defense: Accelerated Dragon, Simagin Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 6. Nc2 d6 7. Be2 Nh6 -B38 Sicilian Defense: Accelerated Dragon, Maróczy Bind 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 6. Be3 -B39 Sicilian Defense: Accelerated Dragon, Maróczy Bind, Breyer Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. c4 Bg7 6. Be3 Nf6 7. Nc3 Ng4 -B40 Sicilian Defense: Alapin Variation, Sherzer Variation 1. e4 c5 2. Nf3 e6 3. c3 Nf6 4. e5 Nd5 5. d4 Nc6 -B40 Sicilian Defense: Delayed Alapin Variation, with e6 1. e4 c5 2. Nf3 e6 3. c3 -B40 Sicilian Defense: Drazic Variation 1. e4 c5 2. Nf3 e6 3. d4 a6 -B40 Sicilian Defense: French Variation 1. e4 c5 2. Nf3 e6 -B40 Sicilian Defense: French Variation, Normal 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 -B40 Sicilian Defense: French Variation, Open 1. e4 c5 2. Nf3 e6 3. d4 cxd4 -B40 Sicilian Defense: French Variation, Westerinen Attack 1. e4 c5 2. Nf3 e6 3. b3 -B40 Sicilian Defense: Gaw-Paw Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Qb6 -B40 Sicilian Defense: Kan Variation, Wing Attack, Fianchetto Variation 1. e4 c5 2. Nf3 e6 3. Nc3 a6 4. g3 b5 5. d4 cxd4 6. Nxd4 -B40 Sicilian Defense: Kramnik Variation 1. e4 c5 2. Nf3 e6 3. c4 -B40 Sicilian Defense: Kveinis Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Qb6 -B40 Sicilian Defense: Marshall Counterattack 1. e4 c5 2. Nf3 e6 3. d4 d5 -B40 Sicilian Defense: Paulsen-Basman Defense 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Bc5 -B40 Sicilian Defense: Pin Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bb4 -B40 Sicilian Defense: Pin Variation, Jaffe Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bb4 6. Bd3 e5 -B40 Sicilian Defense: Pin Variation, Koch Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bb4 6. e5 -B40 Sicilian Defense: Smith-Morra Gambit Deferred 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. c3 -B40 Sicilian Defense: Wing Gambit Deferred 1. e4 c5 2. Nf3 e6 3. b4 -B41 Sicilian Defense: Kan Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 -B41 Sicilian Defense: Kan Variation, Maróczy Bind, Bronstein Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 Nf6 6. Nc3 Bb4 7. Bd3 Nc6 -B41 Sicilian Defense: Kan Variation, Maróczy Bind, Bronstein Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 Nf6 6. Nc3 Bb4 7. Bd3 Nc6 8. Bc2 -B41 Sicilian Defense: Kan Variation, Maróczy Bind, Hedgehog Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 g6 -B41 Sicilian Defense: Kan Variation, Maróczy Bind, Réti Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. c4 -B42 Sicilian Defense: Kan Variation, Gipslis Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 Nf6 6. O-O d6 7. c4 g6 -B42 Sicilian Defense: Kan Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 -B42 Sicilian Defense: Kan Variation, Polugaevsky Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 Bc5 -B42 Sicilian Defense: Kan Variation, Swiss Cheese Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Bd3 g6 -B43 Sicilian Defense: Kan Variation, Knight Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 -B43 Sicilian Defense: Kan Variation, Knight Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 6. g3 Bb7 7. Bg2 -B43 Sicilian Defense: Kan Variation, Wing Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 -B43 Sicilian Defense: Kan Variation, Wing Attack, Christiansen's Dream 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 6. Bd3 Qb6 7. Be3 Bc5 8. Qg4 -B43 Sicilian Defense: Kan Variation, Wing Attack, Spraggett Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 a6 5. Nc3 b5 6. Bd3 Qb6 7. Nf3 -B44 Sicilian Defense: Taimanov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 -B44 Sicilian Defense: Taimanov Variation, Gary Gambit 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 d6 6. c4 Nf6 7. N1c3 a6 8. Na3 d5 -B44 Sicilian Defense: Taimanov Variation, Modern Line 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 d6 6. c4 Nf6 7. N1c3 a6 8. Na3 Be7 9. Be2 O-O 10. O-O b6 -B44 Sicilian Defense: Taimanov Variation, Szén Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nb5 -B45 Sicilian Defense: Four Knights Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 -B45 Sicilian Defense: Four Knights Variation, American Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Ndb5 Bb4 7. Nd6+ -B45 Sicilian Defense: Four Knights Variation, Cobra Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Ndb5 Bc5 -B45 Sicilian Defense: Four Knights Variation, Exchange Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Nxc6 -B45 Sicilian Defense: Four Knights Variation, Sveshnikov Transfer 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Nf6 6. Ndb5 d6 -B45 Sicilian Defense: Taimanov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 -B46 Sicilian Defense: Taimanov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 a6 -B47 Sicilian Defense: Taimanov Variation, Bastrikov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 -B47 Sicilian Defense: Taimanov Variation, Bastrikov Variation, Ponomariov Gambit 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Ndb5 Qb8 7. Be3 a6 8. Bb6 -B48 Sicilian Defense: Taimanov Variation, Bastrikov Variation, English Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be3 -B49 Sicilian Defense: Taimanov Variation, Bastrikov Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be3 a6 7. Be2 -B50 Sicilian Defense 1. e4 c5 2. Nf3 d6 3. d4 -B50 Sicilian Defense 1. e4 c5 2. Nf3 d6 3. d4 cxd4 -B50 Sicilian Defense: Delayed Alapin Variation, Basman-Palatnik Double Gambit 1. e4 c5 2. Nf3 d6 3. c3 Nf6 4. Be2 Nc6 5. d4 cxd4 6. cxd4 Nxe4 7. d5 Qa5+ 8. Nc3 Nxc3 9. bxc3 -B50 Sicilian Defense: Delayed Alapin Variation, Basman-Palatnik Gambit 1. e4 c5 2. Nf3 d6 3. c3 Nf6 4. Be2 Nc6 5. d4 cxd4 6. cxd4 Nxe4 -B50 Sicilian Defense: Delayed Alapin Variation, with d6 1. e4 c5 2. Nf3 d6 3. c3 -B50 Sicilian Defense: Kopec System 1. e4 c5 2. Nf3 d6 3. Bd3 -B50 Sicilian Defense: Kotov Gambit 1. e4 c5 2. Nf3 d6 3. g3 b5 -B50 Sicilian Defense: Modern Variations 1. e4 c5 2. Nf3 d6 -B50 Sicilian Defense: Modern Variations, Anti-Qxd4 Move Order 1. e4 c5 2. Nf3 d6 3. d4 Nf6 -B50 Sicilian Defense: Modern Variations, Anti-Qxd4 Move Order Accepted 1. e4 c5 2. Nf3 d6 3. d4 Nf6 4. dxc5 Nxe4 -B50 Sicilian Defense: Modern Variations, Tartakower 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. c3 -B50 Sicilian Defense: Wing Gambit, Deferred Variation 1. e4 c5 2. Nf3 d6 3. b4 -B51 Sicilian Defense: Moscow Variation 1. e4 c5 2. Nf3 d6 3. Bb5+ -B51 Sicilian Defense: Moscow Variation, Dorfman Gambit 1. e4 c5 2. Nf3 d6 3. Bb5+ Nc6 4. O-O Bd7 5. Qe2 g6 6. e5 -B51 Sicilian Defense: Moscow Variation, Moscow Gambit 1. e4 c5 2. Nf3 d6 3. Bb5+ Nc6 4. O-O Bd7 5. c3 Nf6 6. Re1 a6 7. Bxc6 Bxc6 8. d4 Bxe4 9. Bg5 -B52 Sicilian Defense: Moscow Variation, Haag Gambit 1. e4 c5 2. Nf3 d6 3. Bb5+ Bd7 4. Bxd7+ Qxd7 5. O-O Nc6 6. c3 Nf6 7. d4 -B52 Sicilian Defense: Moscow Variation, Main Line 1. e4 c5 2. Nf3 d6 3. Bb5+ Bd7 -B52 Sicilian Defense: Moscow Variation, Sokolsky Variation 1. e4 c5 2. Nf3 d6 3. Bb5+ Bd7 4. Bxd7+ Qxd7 5. c4 -B53 Sicilian Defense: Chekhover Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Qxd4 -B53 Sicilian Defense: Chekhover Variation, Zaitsev Defense 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Qxd4 Nc6 5. Bb5 Qd7 -B54 Sicilian Defense: Dragon Variation, Accelerated Dragon 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 g6 -B54 Sicilian Defense: Modern Variations, Ginsberg Gambit 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Bc4 -B54 Sicilian Defense: Modern Variations, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 -B54 Sicilian Defense: Prins Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. f3 -B55 Sicilian Defense: Prins Variation, Venice Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. f3 e5 6. Bb5+ -B56 Sicilian Defense: Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 -B56 Sicilian Defense: Classical Variation, Fianchetto Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. g3 -B56 Sicilian Defense: Kupreichik Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Bd7 -B56 Sicilian Defense: Spielmann Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Nde2 -B56 Sicilian Defense: Venice Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 e5 6. Bb5+ -B57 Sicilian Defense: Classical Variation, Anti-Sozin Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 Qb6 -B57 Sicilian Defense: Classical Variation, Sozin Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bc4 -B57 Sicilian Defense: Magnus Smith Trap 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 g6 7. Nxc6 bxc6 8. e5 -B58 Sicilian Defense: Boleslavsky Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Be2 e5 -B58 Sicilian Defense: Boleslavsky Variation, Louma Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 e5 7. Nxc6 -B58 Sicilian Defense: Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Be2 -B58 Sicilian Defense: Classical Variation, Dragon Transfer 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Be2 Nxd4 7. Qxd4 g6 -B59 Sicilian Defense: Boleslavsky Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 e5 7. Nb3 -B60 Sicilian Defense: Richter-Rauzer Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 -B60 Sicilian Defense: Richter-Rauzer Variation, Dragon Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 g6 -B60 Sicilian Defense: Richter-Rauzer Variation, Modern Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 Bd7 -B61 Sicilian Defense: Richter-Rauzer Variation, Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 Bd7 7. Qd2 -B62 Sicilian Defense: Richter-Rauzer Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 -B62 Sicilian Defense: Richter-Rauzer Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd3 -B62 Sicilian Defense: Richter-Rauzer Variation, Exchange Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Nxc6 -B62 Sicilian Defense: Richter-Rauzer Variation, Podebrady Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Nb3 -B62 Sicilian Defense: Richter-Rauzer Variation, Vitolins Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Bb5 -B63 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 -B63 Sicilian Defense: Richter-Rauzer Variation, Classical Variation, Kantscher Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O Nxd4 9. Qxd4 a6 10. f4 b5 -B63 Sicilian Defense: Richter-Rauzer Variation, Ivanov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Qb6 -B63 Sicilian Defense: Richter-Rauzer Variation, Traditional Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 -B64 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 e5 -B64 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 -B65 Sicilian Defense: Richter-Rauzer Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 Nxd4 10. Qxd4 -B65 Sicilian Defense: Richter-Rauzer Variation, Rauzer Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 Be7 8. O-O-O O-O 9. f4 Nxd4 -B66 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation, Early Deviations 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bg5 e6 7. Qd2 a6 -B67 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 a6 8. O-O-O Bd7 -B68 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 a6 8. O-O-O Bd7 9. f4 Be7 -B69 Sicilian Defense: Richter-Rauzer Variation, Neo-Modern Variation, Nyezhmetdinov Attack 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bg5 e6 7. Qd2 a6 8. O-O-O Bd7 9. f4 Be7 10. Nf3 b5 11. Bxf6 -B70 Sicilian Defense: Dragon Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 -B70 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 -B70 Sicilian Defense: Dragon Variation, Fianchetto Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. g3 -B71 Sicilian Defense: Dragon Variation, Levenfish Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. f4 -B71 Sicilian Defense: Dragon Variation, Levenfish Variation, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. f4 Nbd7 -B72 Sicilian Defense: Dragon Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 -B72 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. Be2 -B72 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. Be2 Nc6 -B72 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. Be2 Nc6 8. Nb3 -B72 Sicilian Defense: Dragon Variation, Classical Variation, Amsterdam Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 g6 7. Be3 Bg7 8. Qd2 -B72 Sicilian Defense: Dragon Variation, Classical Variation, Grigoriev Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 g6 7. Be3 Bg7 8. Qd2 O-O 9. O-O-O -B73 Sicilian Defense: Dragon Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O Nc6 8. Be3 -B73 Sicilian Defense: Dragon Variation, Classical Variation, Battery Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Qd2 -B73 Sicilian Defense: Dragon Variation, Classical Variation, Zollner Gambit 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Be3 Bg7 6. Be2 Nf6 7. Nc3 O-O 8. O-O d6 9. f4 Qb6 10. e5 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Alekhine Line 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Be2 O-O 8. O-O d6 9. Nb3 a5 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Bernard Defense 1. e4 c5 2. Nf3 g6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 Be6 10. f4 Na5 11. f5 Bc4 12. Bd3 Bxd3 13. cxd3 d5 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Maróczy Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 Be6 10. f4 Na5 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Normal Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Spielmann Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 g6 5. Nc3 Bg7 6. Be3 Nf6 7. Be2 O-O 8. Nb3 d6 9. O-O Be6 10. f4 Na5 11. f5 Bc4 12. Bd3 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Stockholm Attack 1. e4 c5 2. Nc3 d6 3. f4 Nc6 4. Nf3 g6 5. d4 cxd4 6. Nxd4 Bg7 7. Be3 Nf6 8. Be2 O-O 9. Nb3 Be6 10. O-O Na5 11. f5 Bc4 12. Nxa5 Bxe2 13. Qxe2 Qxa5 14. g4 -B74 Sicilian Defense: Dragon Variation, Classical Variation, Tartakower Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be2 Bg7 7. O-O O-O 8. Be3 Nc6 9. Nb3 Be6 10. f4 Qc8 -B75 Sicilian Defense: Dragon Variation, Yugoslav Attack, Belezky Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 -B75 Sicilian Defense: Dragon Variation, Yugoslav Attack, Early Deviations 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 -B75 Sicilian Defense: Dragon Variation, Yugoslav Attack, Hungarian Dragon 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Nc6 7. f3 h5 -B76 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O -B76 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 -B76 Sicilian Defense: Dragon Variation, Yugoslav Attack, Modern Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. O-O-O -B76 Sicilian Defense: Dragon Variation, Yugoslav Attack, Panov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. g4 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Byrne Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 a5 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Czerniak Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. Bc4 Nxd4 10. Bxd4 Be6 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Czerniak Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. Bc4 Nxd4 10. Bxd4 Be6 11. Bb3 Qa5 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. Bb3 -B77 Sicilian Defense: Dragon Variation, Yugoslav Attack, Sosonko Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 Nc6 8. Qd2 O-O 9. Bc4 Nd7 -B78 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O -B78 Sicilian Defense: Dragon Variation, Yugoslav Attack, Chinese Dragon 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Rb8 -B78 Sicilian Defense: Dragon Variation, Yugoslav Attack, Old Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Rc8 -B78 Sicilian Defense: Dragon Variation, Yugoslav Attack, Topalov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Rc8 11. Bb3 Nxd4 12. Bxd4 -B79 Sicilian Defense: Dragon Variation, Yugoslav Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. h4 Qa5 11. O-O-O Rfc8 12. Bb3 -B79 Sicilian Defense: Dragon Variation, Yugoslav Attack, Soltis Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 g6 6. Be3 Bg7 7. f3 O-O 8. Qd2 Nc6 9. Bc4 Bd7 10. O-O-O Qa5 11. h4 Rfc8 12. Bb3 h5 -B80 Sicilian Defense: Scheveningen Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 -B80 Sicilian Defense: Scheveningen Variation, English Attack, with Qd2 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. Qd2 -B80 Sicilian Defense: Scheveningen Variation, Fianchetto Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. g3 -B80 Sicilian Defense: Scheveningen Variation, Vitolins Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bb5+ -B81 Sicilian Defense: Scheveningen Variation, Keres Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. g4 -B82 Sicilian Defense: Scheveningen Variation, Matanovic Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. f4 -B82 Sicilian Defense: Scheveningen Variation, Tal Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. f4 Nc6 7. Be3 Be7 8. Qf3 -B83 Sicilian Defense: Scheveningen Variation, Classical Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 -B83 Sicilian Defense: Scheveningen Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 d6 6. Be2 Nf6 -B83 Sicilian Defense: Scheveningen Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 Be7 7. O-O O-O 8. f4 Nc6 9. Be3 -B83 Sicilian Defense: Scheveningen Variation, Modern Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Be2 Be7 7. O-O O-O 8. f4 Nc6 9. Be3 Bd7 10. Nb3 -B84 Sicilian Defense: Najdorf Variation, Scheveningen Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e6 7. O-O Nbd7 -B84 Sicilian Defense: Scheveningen Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e6 -B84 Sicilian Defense: Scheveningen Variation, Classical Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e6 7. O-O Qc7 -B85 Sicilian Defense: Scheveningen Variation, Classical Main Line 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be2 a6 7. O-O Nf6 8. Be3 Be7 9. f4 d6 10. Qe1 O-O -B85 Sicilian Defense: Scheveningen Variation, Classical Variation, Paulsen Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. f4 e6 7. Be2 Qc7 8. O-O Nc6 -B85 Sicilian Defense: Scheveningen Variation, Classical Variation, Paulsen Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be2 a6 7. O-O Nf6 8. Be3 d6 9. f4 -B85 Sicilian Defense: Scheveningen Variation, Classical Variation, Paulsen Variation 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nc6 5. Nc3 Qc7 6. Be2 a6 7. O-O Nf6 8. Kh1 Be7 9. f4 d6 10. a4 -B86 Sicilian Defense: Sozin Attack 1. e4 c5 2. Nf3 e6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 -B87 Sicilian Defense: Sozin Attack, Flank Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bc4 e6 7. Bb3 b5 -B88 Sicilian Defense: Sozin Attack, Fischer Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 7. Bb3 Be7 8. Be3 O-O 9. f4 -B88 Sicilian Defense: Sozin Attack, Leonhardt Variation 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 -B89 Sicilian Defense: Sozin Attack, Main Line 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 7. Be3 -B89 Sicilian Defense: Sozin Attack, Main Line, Sherbakov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 Nc6 6. Bc4 e6 7. Be3 Be7 8. Bb3 O-O 9. O-O Na5 10. f4 b6 -B89 Sicilian Defense: Velimirovic Attack 1. e4 c5 2. Nf3 Nc6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 d6 6. Bc4 e6 7. Be3 Be7 8. Qe2 -B90 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 -B90 Sicilian Defense: Najdorf Variation, Adams Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. h3 -B90 Sicilian Defense: Najdorf Variation, Dekker Gambit 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. g4 -B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 -B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be6 8. f3 -B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be7 8. f3 -B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be6 8. h3 -B90 Sicilian Defense: Najdorf Variation, English Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e5 7. Nb3 Be7 8. h3 -B90 Sicilian Defense: Najdorf Variation, English Attack, Anti-English 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 Ng4 -B90 Sicilian Defense: Najdorf Variation, Lipnitsky Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bc4 -B90 Sicilian Defense: Najdorf Variation, Petronić Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Rg1 -B90 Sicilian Defense: Najdorf Variation, Yates Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bd3 -B90 Sicilian Defense: Scheveningen Variation, Delayed Keres Attack 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. g4 -B90 Sicilian Defense: Scheveningen Variation, Delayed Keres Attack, Perenyi Gambit 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. g4 e5 8. Nf5 g6 9. g5 -B90 Sicilian Defense: Scheveningen Variation, English Attack, with f3 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be3 e6 7. f3 -B91 Sicilian Defense: Najdorf Variation, Zagreb Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. g3 -B92 Sicilian Defense: Najdorf Variation, Opocensky Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 -B92 Sicilian Defense: Najdorf Variation, Opocensky Variation 1. e4 c5 2. Nf3 Nf6 3. Nc3 d6 4. d4 cxd4 5. Nxd4 a6 6. Be2 e5 7. Nb3 Be6 8. Be3 -B92 Sicilian Defense: Najdorf Variation, Opocensky Variation, Modern Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e5 7. Nb3 Be7 8. O-O Be6 -B92 Sicilian Defense: Najdorf Variation, Opocensky Variation, Traditional Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Be2 e5 7. Nb3 Be7 8. O-O O-O -B93 Sicilian Defense: Najdorf Variation, Amsterdam Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. f4 -B94 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 -B94 Sicilian Defense: Najdorf Variation, Ivkov Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 Nbd7 7. Bc4 Qa5 8. Qd2 e6 9. O-O-O b5 10. Bb3 Bb7 11. Rhe1 Nc5 12. e5 -B95 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 -B96 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 -B96 Sicilian Defense: Najdorf Variation, Neo-Classical Defense 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Nc6 -B96 Sicilian Defense: Najdorf Variation, Polugaevsky Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 b5 -B96 Sicilian Defense: Najdorf Variation, Polugaevsky Variation, Simagin Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 b5 8. e5 dxe5 9. fxe5 Qc7 10. Qe2 -B97 Sicilian Defense: Najdorf Variation, Poisoned Pawn Accepted 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Qb6 8. Qd2 Qxb2 9. Rb1 Qa3 -B97 Sicilian Defense: Najdorf Variation, Poisoned Pawn Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Qb6 -B98 Sicilian Defense: Najdorf Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 -B98 Sicilian Defense: Najdorf Variation, Browne Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 h6 9. Bh4 Qc7 -B98 Sicilian Defense: Najdorf Variation, Goteborg Variation 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 h6 9. Bh4 g5 -B98 Sicilian Defense: Najdorf Variation, Traditional Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 -B99 Sicilian Defense: Najdorf Variation, Main Line 1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 6. Bg5 e6 7. f4 Be7 8. Qf3 Qc7 9. O-O-O Nbd7 diff --git a/crates/openings/data/c.tsv b/crates/openings/data/c.tsv deleted file mode 100644 index 4b3d9c9..0000000 --- a/crates/openings/data/c.tsv +++ /dev/null @@ -1,1251 +0,0 @@ -eco name pgn -C00 French Defense 1. e4 e6 -C00 French Defense 1. e4 e6 2. d4 d5 -C00 French Defense: Alapin Gambit 1. e4 e6 2. d4 d5 3. Be3 -C00 French Defense: Baeuerle Gambit 1. e4 e6 2. d4 b5 -C00 French Defense: Banzai-Leong Gambit 1. e4 e6 2. b4 -C00 French Defense: Banzai-Leong Gambit, Pinova Gambit 1. e4 e6 2. b4 Bxb4 3. e5 -C00 French Defense: Bird Invitation 1. e4 e6 2. Bb5 -C00 French Defense: Carlson Gambit 1. e4 e6 2. d4 d5 3. Nf3 dxe4 4. Ne5 -C00 French Defense: Chigorin Variation 1. e4 e6 2. Qe2 -C00 French Defense: Diemer-Duhm Gambit 1. e4 e6 2. d4 d5 3. c4 -C00 French Defense: Diemer-Duhm Gambit Accepted 1. e4 e6 2. d4 d5 3. c4 dxe4 -C00 French Defense: Franco-Hiva Gambit 1. e4 e6 2. d4 f5 -C00 French Defense: Franco-Hiva Gambit Accepted 1. e4 e6 2. d4 f5 3. exf5 -C00 French Defense: Franco-Sicilian Defense 1. e4 e6 2. d4 c5 -C00 French Defense: Hoffmann Gambit 1. e4 e6 2. d4 d5 3. Qe2 e5 4. f4 exf4 -C00 French Defense: Horwitz Attack 1. e4 e6 2. b3 -C00 French Defense: Horwitz Attack, Papa-Ticulat Gambit 1. e4 e6 2. b3 d5 3. Bb2 -C00 French Defense: King's Indian Attack 1. e4 e6 2. d3 -C00 French Defense: King's Indian Attack, Franco-Hiva Gambit 1. e4 e6 2. d3 f5 -C00 French Defense: Knight Variation 1. e4 e6 2. Nf3 -C00 French Defense: Knight Variation, Franco-Hiva Gambit 1. e4 e6 2. Nf3 f5 -C00 French Defense: La Bourdonnais Variation 1. e4 e6 2. f4 -C00 French Defense: La Bourdonnais Variation, Reuter Gambit 1. e4 e6 2. f4 d5 3. Nf3 dxe4 -C00 French Defense: Mediterranean Defense 1. e4 e6 2. d4 Nf6 -C00 French Defense: Morphy Gambit 1. e4 e6 2. d4 d5 3. Nh3 -C00 French Defense: Normal Variation 1. e4 e6 2. d4 -C00 French Defense: Orthoschnapp Gambit 1. e4 e6 2. c4 d5 3. cxd5 exd5 4. Qb3 -C00 French Defense: Pelikan Variation 1. e4 e6 2. Nc3 d5 3. f4 -C00 French Defense: Perseus Gambit 1. e4 e6 2. d4 d5 3. Nf3 -C00 French Defense: Queen's Knight 1. e4 e6 2. Nc3 -C00 French Defense: Reversed Philidor Formation 1. e4 e6 2. d3 d5 3. Nd2 Nf6 4. Ngf3 Nc6 5. Be2 -C00 French Defense: Réti-Spielmann Attack 1. e4 e6 2. g3 -C00 French Defense: Schlechter Variation 1. e4 e6 2. d4 d5 3. Bd3 -C00 French Defense: St. George Defense 1. e4 e6 2. d4 a6 -C00 French Defense: St. George Defense, Sanky-George Gambit 1. e4 e6 2. d4 a6 3. c4 b5 -C00 French Defense: St. George Defense, St. George Gambit 1. e4 e6 2. d4 a6 3. c4 b5 4. cxb5 axb5 -C00 French Defense: St. George Defense, Three Pawn Attack 1. e4 e6 2. d4 a6 3. c4 -C00 French Defense: St. George Defense, Traditional Line 1. e4 e6 2. d4 a6 3. Nf3 b5 4. Bd3 c5 5. c3 Bb7 6. O-O Nf6 -C00 French Defense: Steiner Variation 1. e4 e6 2. c4 -C00 French Defense: Steinitz Attack 1. e4 e6 2. e5 -C00 French Defense: Two Knights Variation 1. e4 e6 2. Nf3 d5 3. Nc3 -C00 French Defense: Wing Gambit 1. e4 e6 2. Nf3 d5 3. e5 c5 4. b4 -C00 Rat Defense: Small Center Defense 1. d4 e6 2. e4 d6 -C01 French Defense: Exchange Variation 1. e4 e6 2. d4 d5 3. exd5 -C01 French Defense: Exchange Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. Nf3 -C01 French Defense: Exchange Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. Nc3 -C01 French Defense: Exchange Variation, Bogoljubow Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. Nc3 Nf6 5. Bg5 Nc6 -C01 French Defense: Exchange Variation, Monte Carlo Variation 1. e4 e6 2. d4 d5 3. exd5 exd5 4. c4 -C01 French Defense: Exchange Variation, Svenonius Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. exd5 exd5 5. Bg5 -C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 -C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 c5 -C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 -C02 French Defense: Advance Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 -C02 French Defense: Advance Variation, Euwe Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Bd7 -C02 French Defense: Advance Variation, Extended Bishop Swap 1. e4 e6 2. d4 d5 3. e5 Bd7 -C02 French Defense: Advance Variation, Frenkel Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. b4 -C02 French Defense: Advance Variation, Kupreichik Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Be3 -C02 French Defense: Advance Variation, Lputian Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. a3 Nh6 -C02 French Defense: Advance Variation, Main Line 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. a3 -C02 French Defense: Advance Variation, Milner-Barry Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 -C02 French Defense: Advance Variation, Milner-Barry Gambit, Hector Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. O-O -C02 French Defense: Advance Variation, Milner-Barry Gambit, Hector Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. O-O Bd7 8. Re1 -C02 French Defense: Advance Variation, Milner-Barry Gambit, Main Line 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. cxd4 Bd7 8. O-O -C02 French Defense: Advance Variation, Milner-Barry Gambit, Sørensen Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 Qb6 6. Bd3 cxd4 7. cxd4 Bd7 8. O-O Nxd4 9. Ng5 -C02 French Defense: Advance Variation, Nimzowitsch Attack 1. e4 e6 2. d4 d5 3. e5 c5 4. Qg4 -C02 French Defense: Advance Variation, Nimzowitsch Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. Qg4 cxd4 5. Nf3 -C02 French Defense: Advance Variation, Nimzowitsch System 1. e4 e6 2. d4 d5 3. e5 c5 4. Nf3 -C02 French Defense: Advance Variation, Paulsen Attack 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Nc6 5. Nf3 -C02 French Defense: Advance Variation, Ruisdonk Gambit 1. e4 e6 2. d4 d5 3. e5 c5 4. Nf3 cxd4 5. Bd3 -C02 French Defense: Advance Variation, Steinitz Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. dxc5 -C02 French Defense: Advance Variation, Wade Variation 1. e4 e6 2. d4 d5 3. e5 c5 4. c3 Qb6 5. Nf3 Bd7 -C03 French Defense: Tarrasch Variation 1. e4 e6 2. d4 d5 3. Nd2 -C03 French Defense: Tarrasch Variation, Guimard Defense 1. e4 e6 2. d4 d5 3. Nd2 Nc6 -C03 French Defense: Tarrasch Variation, Guimard Defense, Thunderbunny Variation 1. e4 e6 2. d4 d5 3. Nd2 Nc6 4. c3 dxe4 5. Nxe4 e5 -C03 French Defense: Tarrasch Variation, Haberditz Variation 1. e4 e6 2. d4 d5 3. Nd2 f5 -C03 French Defense: Tarrasch Variation, Modern System 1. e4 e6 2. d4 d5 3. Nd2 a6 -C03 French Defense: Tarrasch Variation, Morozevich Variation 1. e4 e6 2. d4 d5 3. Nd2 Be7 -C04 French Defense: Tarrasch Variation, Guimard Defense, Main Line 1. e4 e6 2. d4 d5 3. Nd2 Nc6 4. Ngf3 Nf6 -C05 French Defense: Tarrasch Variation, Botvinnik Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 b6 -C05 French Defense: Tarrasch Variation, Closed Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 -C05 French Defense: Tarrasch Variation, Closed Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 Nc6 -C05 French Defense: Tarrasch Variation, Pawn Center Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. f4 -C06 French Defense: Tarrasch Variation, Closed Variation, Main Line 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 Nc6 7. Ne2 cxd4 8. cxd4 -C06 French Defense: Tarrasch Variation, Leningrad Variation 1. e4 e6 2. d4 d5 3. Nd2 Nf6 4. e5 Nfd7 5. Bd3 c5 6. c3 Nc6 7. Ne2 cxd4 8. cxd4 Nb6 -C07 French Defense: Tarrasch Variation, Chistyakov Defense 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Qxd5 -C07 French Defense: Tarrasch Variation, Chistyakov Defense, Modern Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Qxd5 5. Ngf3 cxd4 6. Bc4 Qd6 7. O-O Nf6 8. Nb3 Nc6 9. Nbxd4 Nxd4 10. Nxd4 a6 -C07 French Defense: Tarrasch Variation, Eliskases Variation 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Qxd5 5. Ngf3 cxd4 6. Bc4 Qd8 -C07 French Defense: Tarrasch Variation, Open System 1. e4 e6 2. d4 d5 3. Nd2 c5 -C07 French Defense: Tarrasch Variation, Open System, Euwe-Keres Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. Ngf3 -C07 French Defense: Tarrasch Variation, Open System, Shaposhnikov Gambit 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 Nf6 -C07 French Defense: Tarrasch Variation, Open System, Süchting Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. c3 -C08 French Defense: Tarrasch Variation, Open System 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 -C08 French Defense: Tarrasch Variation, Open System, Advance Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 5. Ngf3 c4 -C09 French Defense: Tarrasch Variation, Open System, Main Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 5. Ngf3 Nc6 -C09 French Defense: Tarrasch Variation, Open System, Main Line 1. e4 e6 2. d4 d5 3. Nd2 c5 4. exd5 exd5 5. Ngf3 Nc6 6. Bb5 Bd6 7. dxc5 Bxc5 8. O-O Ne7 9. c3 -C10 French Defense: Hecht-Reefschläger Variation 1. e4 e6 2. d4 d5 3. Nc3 Nc6 -C10 French Defense: Marshall Gambit 1. e4 e6 2. d4 d5 3. Nc3 c5 -C10 French Defense: Paulsen Variation 1. e4 e6 2. d4 d5 3. Nc3 -C10 French Defense: Rubinstein Variation 1. e4 e6 2. d4 d5 3. Nc3 dxe4 -C10 French Defense: Rubinstein Variation, Blackburne Defense 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nd7 -C10 French Defense: Rubinstein Variation, Capablanca Line 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6 6. Nxf6+ Nxf6 7. Ne5 -C10 French Defense: Rubinstein Variation, Ellis Gambit 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 e5 -C10 French Defense: Rubinstein Variation, Fort Knox Variation 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Bd7 5. Nf3 Bc6 -C10 French Defense: Rubinstein Variation, Kasparov Attack 1. e4 e6 2. d4 d5 3. Nd2 dxe4 4. Nxe4 Nd7 5. Nf3 Ngf6 6. Nxf6+ Nxf6 7. c3 -C10 French Defense: Rubinstein Variation, Maric Variation 1. e4 e6 2. d4 d5 3. Nc3 dxe4 4. Nxe4 Qd5 -C11 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 -C11 French Defense: Classical Variation, Delayed Exchange Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. exd5 -C11 French Defense: Classical Variation, Shirov-Anand Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. Nce2 -C11 French Defense: Classical Variation, Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 -C11 French Defense: Classical Variation, Swiss Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bd3 -C11 French Defense: Henneberger Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Be3 -C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 -C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 6. a3 -C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 6. Ne2 -C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. dxc5 Nc6 -C11 French Defense: Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. Nf3 -C11 French Defense: Steinitz Variation, Boleslavsky Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. Nf3 Nc6 7. Be3 -C11 French Defense: Steinitz Variation, Bradford Attack Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. dxc5 Bxc5 7. Qg4 -C11 French Defense: Steinitz Variation, Brodsky-Jones Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. f4 c5 6. dxc5 Nc6 7. a3 Bxc5 8. Qg4 O-O 9. Nf3 f6 -C11 French Defense: Steinitz Variation, Gledhill Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. e5 Nfd7 5. Qg4 -C12 French Defense, Classical, 4. Bg5 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 -C12 French Defense: McCutcheon Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 -C12 French Defense: McCutcheon Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 -C12 French Defense: McCutcheon Variation, Bernstein Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bh4 -C12 French Defense: McCutcheon Variation, Bogoljubow Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. exd5 Qxd5 6. Bxf6 gxf6 7. Qd2 Qa5 -C12 French Defense: McCutcheon Variation, Chigorin Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. exf6 -C12 French Defense: McCutcheon Variation, Dr. Olland Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bc1 -C12 French Defense: McCutcheon Variation, Duras Variation 1. e4 e6 2. Nc3 d5 3. d4 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Bxc3 7. bxc3 Ne4 8. Qg4 Kf8 9. Bc1 -C12 French Defense: McCutcheon Variation, Exchange Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. exd5 -C12 French Defense: McCutcheon Variation, Grigoriev Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. exf6 hxg5 7. fxg7 Rg8 8. h4 gxh4 9. Qg4 -C12 French Defense: McCutcheon Variation, Janowski Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Be3 -C12 French Defense: McCutcheon Variation, Lasker Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Bxc3 -C12 French Defense: McCutcheon Variation, Lasker Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Bxc3 7. bxc3 Ne4 8. Qg4 g6 -C12 French Defense: McCutcheon Variation, Tartakower Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Bb4 5. e5 h6 6. Bd2 Nfd7 -C13 French Defense: Alekhine-Chatard Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 -C13 French Defense: Alekhine-Chatard Attack, Albin-Chatard Gambit 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 Bxg5 7. hxg5 Qxg5 -C13 French Defense: Alekhine-Chatard Attack, Breyer Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 c5 -C13 French Defense: Alekhine-Chatard Attack, Maróczy Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 a6 -C13 French Defense: Alekhine-Chatard Attack, Spielmann Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 O-O -C13 French Defense: Alekhine-Chatard Attack, Teichmann Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. h4 f6 -C13 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 5. Nxe4 Be7 -C13 French Defense: Classical Variation, Burn Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 -C13 French Defense: Classical Variation, Burn Variation, Main Line 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 5. Nxe4 Be7 6. Bxf6 Bxf6 7. Nf3 O-O -C13 French Defense: Classical Variation, Burn Variation, Morozevich Line 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 dxe4 5. Nxe4 Be7 6. Bxf6 gxf6 -C13 French Defense: Classical Variation, Frankfurt Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Ng8 6. Be3 b6 -C13 French Defense: Classical Variation, Normal Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 -C13 French Defense: Classical Variation, Richter Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 -C13 French Defense: Classical Variation, Richter Attack 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 Bxf6 6. e5 Be7 7. Qg4 -C13 French Defense: Classical Variation, Tartakower Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Ne4 -C13 French Defense: Classical Variation, Vistaneckis Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Ng8 -C14 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 a6 4. Nf3 Nf6 5. e5 Nfd7 6. Bg5 -C14 French Defense: Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 -C14 French Defense: Classical Variation, Alapin Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Nb5 -C14 French Defense: Classical Variation, Pollock Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Qg4 -C14 French Defense: Classical Variation, Rubinstein Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Qd2 -C14 French Defense: Classical Variation, Stahlberg Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. f4 O-O 8. Nf3 c5 9. Qd2 Nc6 10. O-O-O c4 -C14 French Defense: Classical Variation, Steinitz Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. f4 -C14 French Defense: Classical Variation, Tarrasch Variation 1. e4 e6 2. d4 d5 3. Nc3 Nf6 4. Bg5 Be7 5. e5 Nfd7 6. Bxe7 Qxe7 7. Bd3 -C15 French Defense: McCutcheon Variation, Wolf Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 Nf6 5. Bg5 -C15 French Defense: Winawer Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 -C15 French Defense: Winawer Variation, Alekhine Gambit Accepted 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 dxe4 5. a3 Bxc3+ -C15 French Defense: Winawer Variation, Alekhine Gambit, Alatortsev Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 dxe4 5. a3 Be7 6. Nxe4 Nf6 7. N2g3 O-O 8. Be2 Nc6 -C15 French Defense: Winawer Variation, Alekhine Gambit, Kan Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 dxe4 5. a3 Bxc3+ 6. Nxc3 Nc6 -C15 French Defense: Winawer Variation, Alekhine-Maróczy Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Ne2 -C15 French Defense: Winawer Variation, Delayed Exchange Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. exd5 -C15 French Defense: Winawer Variation, Exchange Variation, Canal Attack 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. exd5 exd5 5. Bd3 Ne7 6. Qh5 -C15 French Defense: Winawer Variation, Fingerslip Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 -C15 French Defense: Winawer Variation, Fingerslip Variation, Kunin Double Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 dxe4 5. Qg4 Qxd4 -C15 French Defense: Winawer Variation, Fingerslip Variation, Main Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 dxe4 5. Qg4 Nf6 6. Qxg7 Rg8 7. Qh6 -C15 French Defense: Winawer Variation, Fingerslip Variation, Schwarz's Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd2 Ne7 5. Nb1 -C15 French Defense: Winawer Variation, Kondratiyev Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. Bd3 c5 5. exd5 Qxd5 6. Bd2 -C15 French Defense: Winawer Variation, Winckelmann-Reimer Gambit 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 dxe4 6. f3 -C16 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 -C16 French Defense: Winawer Variation, Petrosian Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 Qd7 -C17 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 -C17 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 -C17 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 cxd4 6. axb4 dxc3 7. Nf3 -C17 French Defense: Winawer Variation, Advance Variation, Moscow Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. Qg4 -C17 French Defense: Winawer Variation, Bogoljubow Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. Bd2 -C17 French Defense: Winawer Variation, Bogoljubow Variation, Icelandic Defense 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. Bd2 Ne7 6. f4 -C17 French Defense: Winawer Variation, Maróczy-Wallis Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 cxd4 6. axb4 dxc3 -C17 French Defense: Winawer Variation, Retreat Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Ba5 -C17 French Defense: Winawer Variation, Retreat Variation, Armenian Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Ba5 6. b4 cxd4 -C18 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 -C18 French Defense: Winawer Variation, Advance Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 -C18 French Defense: Winawer Variation, Advance Variation, with Bd3 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Bd3 -C18 French Defense: Winawer Variation, Advance Variation, with Bd3 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Bd3 Qc7 -C18 French Defense: Winawer Variation, Advance Variation, with h4 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. h4 -C18 French Defense: Winawer Variation, Advance Variation, with h4 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. h4 Qc7 -C18 French Defense: Winawer Variation, Classical Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Qc7 -C18 French Defense: Winawer Variation, Eingorn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Kf8 -C18 French Defense: Winawer Variation, Poisoned Pawn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 -C18 French Defense: Winawer Variation, Poisoned Pawn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 cxd4 8. Qxg7 -C18 French Defense: Winawer Variation, Poisoned Pawn Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 cxd4 8. Qxg7 Rg8 9. Qxh7 Nbc6 -C18 French Defense: Winawer Variation, Poisoned Pawn Variation Declined 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 8. Bd3 -C18 French Defense: Winawer Variation, Poisoned Pawn Variation, Main Line 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 8. Qxg7 Rg8 9. Qxh7 cxd4 10. Ne2 -C18 French Defense: Winawer Variation, Poisoned Pawn Variation, Paoli Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 Qc7 8. Qxg7 Rg8 9. Qxh7 cxd4 10. Kd1 -C18 French Defense: Winawer Variation, Portisch-Hook Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Qa5 -C18 French Defense: Winawer Variation, Warsaw Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Qg4 O-O -C19 French Defense: Winawer Variation, Advance Variation, Smyslov Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 Ne7 5. a3 Bxc3+ 6. bxc3 c5 7. a4 -C19 French Defense: Winawer Variation, Advance Variation, Smyslov Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 Ne7 5. a3 Bxc3+ 6. bxc3 c5 7. a4 Qc7 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Qd2 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Qd2 Bd7 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Bd2 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Bd2 Bd7 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. a4 Nbc6 8. Nf3 Qa5 9. Bd2 c4 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Nf3 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Nc6 7. Nf3 Nge7 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Nf3 Qc7 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Nf3 Qc7 8. h4 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Ne7 7. Bd3 Nbc6 8. Nf3 -C19 French Defense: Winawer Variation, Positional Variation 1. e4 e6 2. d4 d5 3. Nc3 Bb4 4. e5 c5 5. a3 Bxc3+ 6. bxc3 Nc6 7. Nf3 Qa5 8. Bd2 Nge7 -C20 Barnes Opening: Walkerling 1. f3 e5 2. e4 Nf6 3. Bc4 -C20 Bongcloud Attack 1. e4 e5 2. Ke2 -C20 Center Game 1. e4 e5 2. d4 -C20 English Opening: The Whale 1. e4 e5 2. c4 -C20 King's Pawn Game 1. e4 e5 -C20 King's Pawn Game: Alapin Opening 1. e4 e5 2. Ne2 -C20 King's Pawn Game: Bavarian Gambit 1. e4 e5 2. c4 d5 -C20 King's Pawn Game: Beyer Gambit 1. e4 e5 2. d4 d5 -C20 King's Pawn Game: Clam Variation, King's Gambit Reversed 1. e4 e5 2. d3 f5 -C20 King's Pawn Game: Clam Variation, Radisch Gambit 1. e4 e5 2. d3 Nf6 3. f4 Bc5 -C20 King's Pawn Game: King's Head Opening 1. e4 e5 2. f3 -C20 King's Pawn Game: King's Head Opening 1. e4 e5 2. f3 Nf6 3. Nc3 -C20 King's Pawn Game: Leonardis Variation 1. e4 e5 2. d3 -C20 King's Pawn Game: MacLeod Attack 1. e4 e5 2. c3 -C20 King's Pawn Game: MacLeod Attack, Lasa Gambit 1. e4 e5 2. c3 f5 -C20 King's Pawn Game: MacLeod Attack, Norwalde Gambit 1. e4 e5 2. c3 d5 3. Qh5 Bd6 -C20 King's Pawn Game: Mengarini's Opening 1. e4 e5 2. a3 -C20 King's Pawn Game: Napoleon Attack 1. e4 e5 2. Qf3 -C20 King's Pawn Game: Philidor Gambit 1. e4 e5 2. d4 d6 3. dxe5 Bd7 -C20 King's Pawn Game: Tortoise Opening 1. e4 e5 2. Bd3 -C20 King's Pawn Game: Wayward Queen Attack 1. e4 e5 2. Qh5 -C20 King's Pawn Game: Wayward Queen Attack, Kiddie Countergambit 1. e4 e5 2. Qh5 Nf6 -C20 King's Pawn Game: Wayward Queen Attack, Mellon Gambit 1. e4 e5 2. Qh5 Nc6 3. Bc4 Nh6 4. d3 g6 5. Qf3 f6 6. Ne2 d5 -C20 King's Pawn Game: Weber Gambit 1. e4 e5 2. d3 d5 3. exd5 c6 4. dxc6 Nxc6 -C20 King's Pawn Opening 1. e4 e5 2. b3 -C20 King's Pawn Opening: Speers 1. e4 e5 2. Qg4 Nf6 3. Qf5 -C20 King's Pawn Opening: Van Hooydoon Gambit 1. e4 e5 2. Qe2 Nc6 3. c3 Nf6 4. Nf3 Bc5 5. d4 exd4 6. cxd4 Nxd4 -C20 Portuguese Opening 1. e4 e5 2. Bb5 -C20 Portuguese Opening: Miguel Gambit 1. e4 e5 2. Bb5 Bc5 3. b4 -C20 Portuguese Opening: Portuguese Gambit 1. e4 e5 2. Bb5 Nf6 3. d4 -C21 Center Game 1. e4 e5 2. d4 exd4 3. Qxd4 -C21 Center Game Accepted 1. e4 e5 2. d4 exd4 -C21 Center Game: Halasz-McDonnell Gambit 1. e4 e5 2. d4 exd4 3. f4 -C21 Center Game: Halasz-McDonnell Gambit, Crocodile Variation 1. e4 e5 2. d4 exd4 3. f4 Bc5 4. Nf3 Nc6 5. c3 -C21 Center Game: Kieseritzky Variation 1. e4 e5 2. d4 exd4 3. Nf3 -C21 Center Game: Kieseritzky Variation 1. e4 e5 2. d4 exd4 3. Nf3 c5 -C21 Center Game: Kieseritzky Variation 1. e4 e5 2. d4 exd4 3. Nf3 c5 4. Bc4 -C21 Center Game: Lanc-Arnold Gambit 1. e4 e5 2. d4 exd4 3. Nf3 Bc5 4. c3 -C21 Center Game: Lanc-Arnold Gambit, Schippler Gambit 1. e4 e5 2. d4 exd4 3. Nf3 Bc5 4. c3 dxc3 5. Bc4 -C21 Center Game: Ross Gambit 1. e4 e5 2. d4 exd4 3. Bd3 -C21 Center Game: von der Lasa Gambit 1. e4 e5 2. d4 exd4 3. Bc4 -C21 Danish Gambit 1. e4 e5 2. d4 exd4 3. c3 -C21 Danish Gambit Accepted 1. e4 e5 2. d4 exd4 3. c3 dxc3 -C21 Danish Gambit Accepted: Chigorin Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 Qe7 -C21 Danish Gambit Accepted: Classical Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 Nf6 -C21 Danish Gambit Accepted: Copenhagen Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 Bb4+ -C21 Danish Gambit Accepted: Schlechter Defense 1. e4 e5 2. d4 exd4 3. c3 dxc3 4. Bc4 cxb2 5. Bxb2 d5 -C21 Danish Gambit Accepted: Svenonius Defense 1. e4 e5 2. d4 exd4 3. c3 Ne7 -C21 Danish Gambit Declined: Sörensen Defense 1. e4 e5 2. d4 exd4 3. c3 d5 -C22 Center Game: Berger Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 Nf6 -C22 Center Game: Charousek Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 Bb4+ 5. c3 Be7 -C22 Center Game: Hall Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qc4 -C22 Center Game: Kupreichik Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 Nf6 5. Nc3 Bb4 6. Bd2 O-O 7. O-O-O Re8 8. Bc4 d6 9. Nh3 -C22 Center Game: Normal Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 -C22 Center Game: Paulsen Attack Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 -C22 Center Game: l'Hermet Variation 1. e4 e5 2. d4 exd4 3. Qxd4 Nc6 4. Qe3 f5 -C23 Bishop's Opening 1. e4 e5 2. Bc4 -C23 Bishop's Opening: Anderssen Gambit 1. e4 e5 2. Bc4 b5 3. Bxb5 c6 -C23 Bishop's Opening: Boi Variation 1. e4 e5 2. Bc4 Bc5 -C23 Bishop's Opening: Calabrese Countergambit 1. e4 e5 2. Bc4 f5 -C23 Bishop's Opening: Calabrese Countergambit, Jaenisch Variation 1. e4 e5 2. Bc4 f5 3. d3 -C23 Bishop's Opening: Four Pawns Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 Bxb4 4. f4 exf4 5. Nf3 Be7 6. d4 Bh4+ 7. g3 fxg3 8. O-O gxh2+ 9. Kh1 -C23 Bishop's Opening: Khan Gambit 1. e4 e5 2. Bc4 d5 -C23 Bishop's Opening: Lewis Countergambit 1. e4 e5 2. Bc4 Bc5 3. c3 d5 -C23 Bishop's Opening: Lewis Countergambit 1. e4 e5 2. Bc4 Bc5 3. c3 d5 4. Bxd5 Nf6 -C23 Bishop's Opening: Lewis Countergambit, Walker Variation 1. e4 e5 2. Bc4 Bc5 3. c3 d5 4. Bxd5 Nf6 5. d4 -C23 Bishop's Opening: Lewis Gambit 1. e4 e5 2. Bc4 Bc5 3. d4 -C23 Bishop's Opening: Lisitsyn Variation 1. e4 e5 2. Bc4 c6 3. d4 d5 4. exd5 cxd5 5. Bb5+ Bd7 6. Bxd7+ Nxd7 7. dxe5 Nxe5 8. Ne2 -C23 Bishop's Opening: Lopez Gambit 1. e4 e5 2. Bc4 Bc5 3. Qe2 Nc6 4. c3 Nf6 5. f4 -C23 Bishop's Opening: Lopez Variation 1. e4 e5 2. Bc4 Bc5 3. Qe2 -C23 Bishop's Opening: Lopez Variation, Lopez Gambit 1. e4 e5 2. Bc4 Bc5 3. Qe2 Nf6 4. f4 -C23 Bishop's Opening: McDonnell Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 -C23 Bishop's Opening: McDonnell Gambit, La Bourdonnais-Denker Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 Bxb4 4. c3 -C23 Bishop's Opening: McDonnell Gambit, McDonnell Double Gambit 1. e4 e5 2. Bc4 Bc5 3. b4 Bxb4 4. f4 -C23 Bishop's Opening: Philidor Counterattack 1. e4 e5 2. Bc4 c6 -C23 Bishop's Opening: Philidor Variation 1. e4 e5 2. Bc4 Bc5 3. c3 -C23 Bishop's Opening: Pratt Variation 1. e4 e5 2. Bc4 Bc5 3. c3 Nf6 4. d4 exd4 5. e5 d5 6. exf6 dxc4 7. Qh5 O-O -C23 Bishop's Opening: Stein Gambit 1. e4 e5 2. Bc4 Bc5 3. f4 -C23 Bishop's Opening: Thorold Gambit 1. e4 e5 2. Bc4 b5 3. Bxb5 f5 -C23 Bishop's Opening: del Rio Variation 1. e4 e5 2. Bc4 Bc5 3. c3 Qg5 -C24 Bishop's Opening: Berlin Defense 1. e4 e5 2. Bc4 Nf6 -C24 Bishop's Opening: Berlin Defense, Greco Gambit 1. e4 e5 2. Bc4 Nf6 3. f4 -C24 Bishop's Opening: Kitchener Folly 1. e4 e5 2. Bc4 Nf6 3. d3 Be7 4. Nf3 O-O -C24 Bishop's Opening: Krejcik Gambit 1. e4 e5 2. Bc4 Nf6 3. f3 Bc5 4. Ne2 Nc6 5. b4 -C24 Bishop's Opening: Pachman Gambit 1. e4 e5 2. Bc4 Nf6 3. Ne2 Nxe4 4. Nec3 -C24 Bishop's Opening: Paulsen Defense 1. e4 e5 2. Bc4 Nf6 3. d3 c6 -C24 Bishop's Opening: Ponziani Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 -C24 Bishop's Opening: Urusov Gambit, Panov Variation 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. Nf3 d5 5. exd5 Bb4+ 6. c3 Qe7+ -C24 Bishop's Opening: Vienna Hybrid 1. e4 e5 2. Bc4 Nf6 3. d3 Nc6 4. Nc3 -C24 Bishop's Opening: Warsaw Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. c3 -C25 Vienna Gambit, with Max Lange Defense 1. e4 e5 2. Nc3 Nc6 3. f4 -C25 Vienna Gambit, with Max Lange Defense: Cunningham Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 Be7 -C25 Vienna Gambit, with Max Lange Defense: Hamppe-Allgaier Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. h4 g4 6. Ng5 -C25 Vienna Gambit, with Max Lange Defense: Hamppe-Allgaier Gambit, Alapin Variation 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. h4 g4 6. Ng5 d6 -C25 Vienna Gambit, with Max Lange Defense: Hamppe-Allgaier Gambit, Thorold Variation 1. e4 e5 2. f4 exf4 3. Nf3 Nc6 4. Nc3 g5 5. h4 g4 6. Ng5 h6 7. Nxf7 Kxf7 8. d4 -C25 Vienna Gambit, with Max Lange Defense: Hamppe-Muzio Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. Bc4 g4 6. O-O gxf3 -C25 Vienna Gambit, with Max Lange Defense: Knight Variation 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 -C25 Vienna Gambit, with Max Lange Defense: Pierce Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. d4 -C25 Vienna Gambit, with Max Lange Defense: Quelle Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 Bc5 4. fxe5 d6 -C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 -C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Fraser-Minckwitz Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 b6 -C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Main Line 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 -C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Paulsen Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 d6 -C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Sörensen Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 g5 -C25 Vienna Gambit, with Max Lange Defense: Steinitz Gambit, Zukertort Defense 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. d4 Qh4+ 5. Ke2 d5 -C25 Vienna Game 1. e4 e5 2. Nc3 -C25 Vienna Game: Anderssen Defense 1. e4 e5 2. Nc3 Bc5 -C25 Vienna Game: Fyfe Gambit 1. e4 e5 2. Nc3 Nc6 3. d4 -C25 Vienna Game: Giraffe Attack 1. e4 e5 2. Nc3 Bc5 3. Qg4 -C25 Vienna Game: Hamppe-Meitner Variation 1. e4 e5 2. Nc3 Bc5 3. Na4 -C25 Vienna Game: Hamppe-Muzio Gambit 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. Bc4 g4 6. O-O -C25 Vienna Game: Hamppe-Muzio, Dubois Variation 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. Bc4 g4 6. O-O gxf3 7. Qxf3 Ne5 8. Qxf4 Qf6 -C25 Vienna Game: Max Lange Defense 1. e4 e5 2. Nc3 Nc6 -C25 Vienna Game: Omaha Gambit 1. e4 e5 2. Nc3 d6 3. f4 -C25 Vienna Game: Paulsen Variation 1. e4 e5 2. Nc3 Nc6 3. g3 -C25 Vienna Game: Paulsen Variation 1. e4 e5 2. Nc3 Nc6 3. g3 Nf6 4. Bg2 Bc5 5. Nge2 d5 -C25 Vienna Game: Paulsen Variation, Mariotti Gambit 1. e4 e5 2. Nc3 Nc6 3. g3 Bc5 4. Bg2 h5 5. Nf3 h4 -C25 Vienna Game: Philidor Countergambit 1. e4 e5 2. Nc3 Nc6 3. d4 f5 -C25 Vienna Game: Pierce Gambit, Rushmere Attack 1. e4 e5 2. Nc3 Nc6 3. f4 exf4 4. Nf3 g5 5. d4 g4 6. Bc4 gxf3 7. O-O d5 8. exd5 Bg4 9. dxc6 -C25 Vienna Game: Stanley Variation, Meitner-Mieses Gambit 1. e4 e5 2. Nc3 Nc6 3. Bc4 Bc5 4. Qg4 Qf6 5. Nd5 -C25 Vienna Game: Zhuravlev Countergambit 1. e4 e5 2. Nc3 Bb4 3. Qg4 Nf6 -C26 Bishop's Opening: Horwitz Gambit 1. e4 e5 2. Bc4 Nf6 3. Nc3 b5 -C26 Bishop's Opening: Vienna Hybrid, Spielmann Attack 1. e4 e5 2. Nc3 Nf6 3. Bc4 Bc5 4. d3 -C26 Vienna Game: Falkbeer Variation 1. e4 e5 2. Nc3 Nf6 -C26 Vienna Game: Mengarini Variation 1. e4 e5 2. Nc3 Nf6 3. a3 -C26 Vienna Game: Mieses Variation 1. e4 e5 2. Nc3 Nf6 3. g3 -C26 Vienna Game: Mieses Variation, Erben Gambit 1. e4 e5 2. Nc3 Nf6 3. g3 d5 4. exd5 c6 -C26 Vienna Game: Paulsen Variation, Pollock Gambit 1. e4 e5 2. Nc3 Nf6 3. g3 Bc5 4. Bg2 Nc6 5. Nge2 d5 6. exd5 -C26 Vienna Game: Stanley Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 -C26 Vienna Game: Stanley Variation, Eifel Gambit 1. e4 e5 2. Nc3 Nf6 3. Bc4 Bc5 4. Nge2 b5 -C26 Vienna Game: Stanley Variation, Reversed Spanish 1. e4 e5 2. Nc3 Nf6 3. Bc4 Bb4 -C27 Bishop's Opening: Boden-Kieseritzky Gambit 1. e4 e5 2. Nf3 Nf6 3. Bc4 Nxe4 4. Nc3 -C27 Bishop's Opening: Boden-Kieseritzky Gambit, Lichtenhein Defense 1. e4 e5 2. Nf3 Nf6 3. Bc4 Nxe4 4. Nc3 d5 -C27 Vienna Game: Adams' Gambit 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Nc6 6. d4 -C27 Vienna Game: Frankenstein-Dracula Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 -C27 Vienna Game: Stanley Variation, Alekhine Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Be7 6. Nf3 Nc6 7. Nxe5 -C27 Vienna Game: Stanley Variation, Frankenstein-Dracula Variation 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Nc6 6. Nb5 g6 7. Qf3 f5 8. Qd5 Qe7 9. Nxc7+ Kd8 10. Nxa8 b6 -C27 Vienna Game: Stanley Variation, Monster Declined 1. e4 e5 2. Nc3 Nf6 3. Bc4 Nxe4 4. Qh5 Nd6 5. Bb3 Be7 -C28 Bishop's Opening: Vienna Hybrid, Hromádka Variation 1. e4 e5 2. Nc3 Nc6 3. Bc4 Nf6 4. d3 Bb4 5. Ne2 -C28 Vienna Game: Stanley Variation, Bronstein Gambit 1. e4 e5 2. Nc3 Nc6 3. Bc4 Nf6 4. f4 Nxe4 5. Nf3 -C28 Vienna Game: Stanley Variation, Three Knights Variation 1. e4 e5 2. Nc3 Nc6 3. Bc4 Nf6 -C29 Vienna Game: Heyde Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Qf3 f5 6. d4 -C29 Vienna Game: Vienna Gambit 1. e4 e5 2. Nc3 Nf6 3. f4 -C29 Vienna Game: Vienna Gambit, Bardeleben Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Qf3 f5 -C29 Vienna Game: Vienna Gambit, Breyer Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Nf3 Be7 -C29 Vienna Game: Vienna Gambit, Kaufmann Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Nf3 Bg4 6. Qe2 -C29 Vienna Game: Vienna Gambit, Main Line 1. e4 e5 2. Nc3 Nf6 3. f4 d5 -C29 Vienna Game: Vienna Gambit, Modern Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. d3 -C29 Vienna Game: Vienna Gambit, Paulsen Attack 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. Qf3 -C29 Vienna Game: Vienna Gambit, Steinitz Variation 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. d3 -C29 Vienna Game: Vienna Gambit, Wurzburger Trap 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. fxe5 Nxe4 5. d3 Qh4+ 6. g3 Nxg3 7. Nf3 Qh5 8. Nxd5 -C30 King's Gambit 1. e4 e5 2. f4 -C30 King's Gambit Declined: Classical Variation 1. e4 e5 2. f4 Bc5 -C30 King's Gambit Declined: Classical Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 -C30 King's Gambit Declined: Classical Variation, Euwe Attack 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 Bg4 5. fxe5 dxe5 6. Qa4+ -C30 King's Gambit Declined: Classical Variation, Rotlewi Countergambit 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. b4 -C30 King's Gambit Declined: Classical Variation, Rubinstein Countergambit 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 f5 -C30 King's Gambit Declined: Classical Variation, Walthoffen Attack 1. e4 e5 2. f4 Bc5 3. Qh5 -C30 King's Gambit Declined: Classical, Hanham Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. Nc3 Nd7 -C30 King's Gambit Declined: Classical, Réti Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. c3 f5 5. fxe5 dxe5 6. d4 exd4 7. Bc4 -C30 King's Gambit Declined: Classical, Soldatenkov Variation 1. e4 e5 2. f4 Bc5 3. Nf3 d6 4. fxe5 -C30 King's Gambit Declined: Classical, Svenonius Variation 1. e4 e5 2. Bc4 Nc6 3. Nc3 Nf6 4. d3 Bc5 5. f4 d6 6. Nf3 Bg4 7. h3 Bxf3 8. Qxf3 exf4 -C30 King's Gambit Declined: Hobbs-Zilbermints Gambit 1. e4 e5 2. f4 Nc6 3. Nf3 g5 4. fxg5 h6 -C30 King's Gambit Declined: Keene Defense 1. e4 e5 2. f4 Qh4+ 3. g3 Qe7 -C30 King's Gambit Declined: Keene's Defense 1. e4 e5 2. f4 Qh4+ -C30 King's Gambit Declined: Keene's Defense 1. e4 e5 2. f4 Qh4+ 3. g3 -C30 King's Gambit Declined: Mafia Defense 1. e4 c5 2. f4 e5 -C30 King's Gambit Declined: Miles Defense 1. e4 e5 2. f4 Nc6 3. Nf3 f5 -C30 King's Gambit Declined: Norwalde Variation 1. e4 e5 2. f4 Qf6 -C30 King's Gambit Declined: Norwalde Variation, Bücker Gambit 1. e4 e5 2. f4 Qf6 3. Nc3 Qxf4 4. Nf3 Bb4 5. Bc4 -C30 King's Gambit Declined: Norwalde Variation, Schubert Variation 1. e4 e5 2. f4 Qf6 3. Nc3 Qxf4 4. d4 -C30 King's Gambit Declined: Panteldakis Countergambit 1. e4 e5 2. f4 f5 -C30 King's Gambit Declined: Panteldakis Countergambit, Greco Variation 1. e4 e5 2. f4 f5 3. exf5 Qh4+ -C30 King's Gambit Declined: Panteldakis Countergambit, Pawn Sacrifice Line 1. e4 e5 2. f4 f5 3. exf5 exf4 4. Qh5+ g6 5. fxg6 Qe7+ 6. Kd1 -C30 King's Gambit Declined: Panteldakis Countergambit, Schiller's Defense 1. e4 e5 2. f4 f5 3. exf5 Bc5 -C30 King's Gambit Declined: Panteldakis Countergambit, Shirazi Line 1. e4 e5 2. f4 f5 3. exf5 exf4 4. Qh5+ Ke7 -C30 King's Gambit Declined: Panteldakis Countergambit, Symmetrical Variation 1. e4 e5 2. f4 f5 3. exf5 exf4 4. Nf3 d5 5. d4 Bd6 6. Bd3 -C30 King's Gambit Declined: Petrov's Defense 1. e4 e5 2. f4 Nf6 -C30 King's Gambit Declined: Queen's Knight Defense 1. e4 e5 2. f4 Nc6 -C30 King's Gambit Declined: Senechaud Countergambit 1. e4 e5 2. f4 Bc5 3. Nf3 g5 -C30 King's Gambit Declined: Soller-Zilbermints Gambit 1. e4 e5 2. f4 f6 3. fxe5 Nc6 -C30 King's Gambit Declined: Zilbermints Double Countergambit 1. e4 e5 2. f4 g5 -C30 King's Gambit Declined: Zilbermints Double Gambit 1. e4 e5 2. f4 Nc6 3. Nf3 g5 -C31 King's Gambit Declined: Falkbeer Countergambit 1. e4 e5 2. f4 d5 -C31 King's Gambit Declined: Falkbeer Countergambit Accepted 1. e4 e5 2. f4 d5 3. exd5 -C31 King's Gambit Declined: Falkbeer Countergambit, Anderssen Attack 1. e4 e5 2. f4 d5 3. exd5 e4 4. Bb5+ -C31 King's Gambit Declined: Falkbeer Countergambit, Blackburne Attack 1. e4 e5 2. f4 d5 3. Nf3 -C31 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 -C31 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Morphy Defense 1. e4 e5 2. Nc3 Nf6 3. f4 d5 4. exd5 e4 5. d3 Bb4 6. Bd2 e3 -C31 King's Gambit Declined: Falkbeer Countergambit, Hinrichsen Gambit 1. e4 e5 2. f4 d5 3. d4 -C31 King's Gambit Declined: Falkbeer Countergambit, Miles Gambit 1. e4 e5 2. f4 d5 3. exd5 Bc5 -C31 King's Gambit Declined: Falkbeer Countergambit, Milner-Barry Variation 1. e4 e5 2. f4 d5 3. Nc3 -C31 King's Gambit Declined: Falkbeer Countergambit, Modern Transfer 1. e4 e5 2. f4 d5 3. exd5 exf4 -C31 King's Gambit Declined: Falkbeer Countergambit, Nimzowitsch-Marshall Countergambit 1. e4 e5 2. f4 d5 3. exd5 c6 -C31 King's Gambit Declined: Falkbeer Countergambit, Pickler Gambit 1. e4 e5 2. f4 d5 3. exd5 c6 4. dxc6 Bc5 -C31 King's Gambit Declined: Falkbeer Countergambit, Rubinstein Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. Nc3 Nf6 5. Qe2 -C31 King's Gambit Declined: Falkbeer Countergambit, Staunton Line 1. e4 e5 2. f4 d5 3. exd5 e4 -C31 Van Geet Opening: Grünfeld Defense, Steiner Gambit 1. e4 e5 2. f4 d5 3. Nc3 dxe4 4. Nxe4 -C32 King's Gambit Declined: Falkbeer Countergambit, Alapin Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Nf3 Bc5 7. Qe2 Bf2+ 8. Kd1 Qxd5+ 9. Nfd2 -C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Qe2 -C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit Accepted 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 -C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Keres Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. Nd2 -C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Main Line 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Nf3 Bc5 7. Qe2 Bf5 -C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Gambit, Old Line 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. Qe2 -C32 King's Gambit Declined: Falkbeer Countergambit, Charousek Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Qe2 Qxd5 7. Nd2 f5 8. g4 -C32 King's Gambit Declined: Falkbeer Countergambit, Tarrasch Variation 1. e4 e5 2. f4 d5 3. exd5 e4 4. d3 Nf6 5. dxe4 Nxe4 6. Nf3 Bc5 7. Qe2 Bf5 8. g4 O-O -C33 King's Gambit Accepted 1. e4 e5 2. f4 exf4 -C33 King's Gambit Accepted: Basman Gambit 1. e4 e5 2. f4 exf4 3. Qe2 -C33 King's Gambit Accepted: Bishop's Gambit 1. e4 e5 2. f4 exf4 3. Bc4 -C33 King's Gambit Accepted: Bishop's Gambit, Anderssen Defense 1. e4 e5 2. f4 exf4 3. Bc4 g5 -C33 King's Gambit Accepted: Bishop's Gambit, Anderssen Variation 1. e4 e5 2. f4 exf4 3. Bc4 d5 4. Bxd5 c6 -C33 King's Gambit Accepted: Bishop's Gambit, Bledow Countergambit 1. e4 e5 2. f4 exf4 3. Bc4 d5 4. Bxd5 Nf6 -C33 King's Gambit Accepted: Bishop's Gambit, Bledow Variation 1. e4 e5 2. f4 exf4 3. Bc4 d5 -C33 King's Gambit Accepted: Bishop's Gambit, Boden Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Nc6 -C33 King's Gambit Accepted: Bishop's Gambit, Bogoljubow Defense 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 4. Nc3 c6 -C33 King's Gambit Accepted: Bishop's Gambit, Bogoljubow Variation 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 4. Nc3 -C33 King's Gambit Accepted: Bishop's Gambit, Boren-Svenonius Variation 1. e4 e5 2. f4 exf4 3. Bc4 d5 4. Bxd5 Qh4+ 5. Kf1 Bd6 -C33 King's Gambit Accepted: Bishop's Gambit, Bryan Countergambit 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 b5 -C33 King's Gambit Accepted: Bishop's Gambit, Chigorin's Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 d5 5. Bxd5 g5 6. g3 -C33 King's Gambit Accepted: Bishop's Gambit, Classical Defense 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Ne7 5. Nc3 g5 6. d4 Bg7 -C33 King's Gambit Accepted: Bishop's Gambit, Classical Defense, Cozio Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Qf3 -C33 King's Gambit Accepted: Bishop's Gambit, Cozio Defense 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 -C33 King's Gambit Accepted: Bishop's Gambit, Cozio Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 d6 -C33 King's Gambit Accepted: Bishop's Gambit, First Jaenisch Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Nf6 -C33 King's Gambit Accepted: Bishop's Gambit, Fraser Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. g3 fxg3 7. Qf3 -C33 King's Gambit Accepted: Bishop's Gambit, Gianutio Gambit 1. e4 e5 2. f4 exf4 3. Bc4 f5 -C33 King's Gambit Accepted: Bishop's Gambit, Greco Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 Bc5 -C33 King's Gambit Accepted: Bishop's Gambit, Grimm Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. d4 d6 7. e5 -C33 King's Gambit Accepted: Bishop's Gambit, Kieseritzky Gambit 1. e4 e5 2. f4 exf4 3. Bc4 b5 -C33 King's Gambit Accepted: Bishop's Gambit, Lopez Defense 1. e4 e5 2. f4 exf4 3. Bc4 c6 -C33 King's Gambit Accepted: Bishop's Gambit, Lopez Variation 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 -C33 King's Gambit Accepted: Bishop's Gambit, Maurian Defense 1. e4 e5 2. f4 exf4 3. Bc4 Nc6 -C33 King's Gambit Accepted: Bishop's Gambit, McDonnell Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. d4 Ne7 7. g3 -C33 King's Gambit Accepted: Bishop's Gambit, McDonnell Attack 1. e4 e5 2. f4 exf4 3. Bc4 Qh4+ 4. Kf1 g5 5. Nc3 Bg7 6. g3 -C33 King's Gambit Accepted: Bishop's Gambit, Paulsen Attack 1. e4 e5 2. f4 exf4 3. Bc4 Nf6 4. Nc3 Bb4 5. e5 -C33 King's Gambit Accepted: Bishop's Gambit, Steinitz Defense 1. e4 e5 2. f4 exf4 3. Bc4 Ne7 -C33 King's Gambit Accepted: Breyer Gambit 1. e4 e5 2. f4 exf4 3. Qf3 -C33 King's Gambit Accepted: Carrera Gambit 1. e4 e5 2. f4 exf4 3. Qh5 -C33 King's Gambit Accepted: Dodo Variation 1. e4 e5 2. f4 exf4 3. Qg4 -C33 King's Gambit Accepted: Eisenberg Variation 1. e4 e5 2. f4 exf4 3. Nh3 -C33 King's Gambit Accepted: Gaga Gambit 1. e4 e5 2. f4 exf4 3. g3 -C33 King's Gambit Accepted: Lopez-Gianutio Countergambit, Hein Variation 1. e4 e5 2. f4 exf4 3. Bc4 f5 4. Qe2 Qh4+ 5. Kd1 fxe4 6. Nc3 Kd8 -C33 King's Gambit Accepted: Mason-Keres Gambit 1. e4 e5 2. f4 exf4 3. Nc3 -C33 King's Gambit Accepted: Orsini Gambit 1. e4 e5 2. f4 exf4 3. b3 -C33 King's Gambit Accepted: Paris Gambit 1. e4 e5 2. f4 exf4 3. Ne2 -C33 King's Gambit Accepted: Schurig Gambit, with Bb5 1. e4 e5 2. f4 exf4 3. Bb5 -C33 King's Gambit Accepted: Schurig Gambit, with Bd3 1. e4 e5 2. f4 exf4 3. Bd3 -C33 King's Gambit Accepted: Stamma Gambit 1. e4 e5 2. f4 exf4 3. h4 -C33 King's Gambit Accepted: Tartakower Gambit 1. e4 e5 2. f4 exf4 3. Be2 -C33 King's Gambit Accepted: Tartakower Gambit, Weiss Defense 1. e4 e5 2. f4 exf4 3. Be2 f5 4. exf5 d6 -C33 King's Gambit Accepted: Tumbleweed 1. e4 e5 2. f4 exf4 3. Kf2 -C33 King's Gambit Accepted: Villemson Gambit 1. e4 e5 2. f4 exf4 3. d4 -C34 King's Gambit Accepted: Becker Defense 1. e4 e5 2. f4 exf4 3. Nf3 h6 -C34 King's Gambit Accepted: Bonsch-Osmolovsky Variation 1. e4 e5 2. f4 exf4 3. Nf3 Ne7 -C34 King's Gambit Accepted: Fischer Defense 1. e4 e5 2. f4 exf4 3. Nf3 d6 -C34 King's Gambit Accepted: Fischer Defense, Schulder Gambit 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. b4 -C34 King's Gambit Accepted: Fischer Defense, Spanish Variation 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. d4 Nf6 5. Bd3 -C34 King's Gambit Accepted: Gianutio Countergambit 1. e4 e5 2. f4 exf4 3. Nf3 f5 -C34 King's Gambit Accepted: Greco Gambit 1. e4 e5 2. f4 exf4 3. Nf3 d6 4. Bc4 h6 5. d4 g5 6. h4 Bg7 -C34 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 -C34 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 -C34 King's Gambit Accepted: MacLeod Defense 1. e4 e5 2. f4 exf4 3. Nf3 Nc6 -C34 King's Gambit Accepted: Schallopp Defense 1. e4 e5 2. f4 exf4 3. Nf3 Nf6 -C34 King's Gambit Accepted: Schallopp Defense, Tashkent Attack 1. e4 e5 2. f4 exf4 3. Nf3 Nf6 4. e5 Nh5 5. g4 -C34 King's Gambit Accepted: Wagenbach Defense 1. e4 e5 2. f4 exf4 3. Nf3 h5 -C35 King's Gambit Accepted: Cunningham Defense 1. e4 e5 2. f4 exf4 3. Nf3 Be7 -C35 King's Gambit Accepted: Cunningham Defense, Bertin Gambit 1. e4 e5 2. f4 exf4 3. Nf3 Be7 4. Bc4 Bh4+ 5. g3 -C35 King's Gambit Accepted: Cunningham Defense, Bertin Gambit 1. e4 e5 2. f4 exf4 3. Nf3 Be7 4. Bc4 Bh4+ 5. g3 fxg3 6. O-O gxh2+ 7. Kh1 -C35 King's Gambit Accepted: Cunningham Defense, McCormick Defense 1. e4 e5 2. f4 exf4 3. Nf3 Be7 4. Bc4 Nf6 -C36 King's Gambit Accepted: Abbazia Defense 1. e4 e5 2. f4 exf4 3. Nf3 d5 4. exd5 Nf6 -C36 King's Gambit Accepted: Abbazia Defense, Main Line 1. e4 e5 2. f4 exf4 3. Nf3 d5 4. exd5 Nf6 5. Bb5+ c6 6. dxc6 bxc6 7. Bc4 Nd5 -C36 King's Gambit Accepted: Modern Defense 1. e4 e5 2. f4 exf4 3. Nf3 d5 -C36 King's Gambit Accepted: Modern Defense 1. e4 e5 2. f4 exf4 3. Nf3 d5 4. exd5 -C37 King's Gambit Accepted: Australian Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. h4 -C37 King's Gambit Accepted: Blachly Gambit 1. e4 e5 2. f4 exf4 3. Nf3 Nc6 4. Bc4 g5 -C37 King's Gambit Accepted: Double Muzio Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. e5 Qxe5 8. Bxf7+ -C37 King's Gambit Accepted: Double Muzio Gambit, Baldwin Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. Nc3 Qd4+ 8. Kh1 Qxc4 9. Nd5 -C37 King's Gambit Accepted: Double Muzio Gambit, Bello Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. Nc3 -C37 King's Gambit Accepted: Double Muzio Gambit, Paulsen Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. e5 Qxe5 8. d3 Bh6 9. Nc3 Ne7 10. Bd2 Nbc6 11. Rae1 -C37 King's Gambit Accepted: Double Muzio Gambit, Young Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 7. Bxf7+ Kxf7 8. d4 Qxd4+ 9. Be3 Qf6 10. Nc3 fxe3 -C37 King's Gambit Accepted: Ghulam-Kassim Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. d4 -C37 King's Gambit Accepted: Ghulam-Kassim Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. d4 gxf3 6. Qxf3 -C37 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 -C37 King's Gambit Accepted: Kotov Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. d4 gxf3 6. Bxf4 -C37 King's Gambit Accepted: Lolli Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Bxf7+ -C37 King's Gambit Accepted: Lolli Gambit, Young Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Bxf7+ Kxf7 6. O-O gxf3 7. Qxf3 Qf6 8. d4 Qxd4+ 9. Be3 Qf6 10. Nc3 -C37 King's Gambit Accepted: McDonnell Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Nc3 -C37 King's Gambit Accepted: Middleton Countergambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 d6 5. O-O Bg4 6. h3 h5 7. hxg4 hxg4 -C37 King's Gambit Accepted: Muzio Gambit Accepted, From's Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qe7 -C37 King's Gambit Accepted: Muzio Gambit, Brentano Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O d5 -C37 King's Gambit Accepted: Muzio Gambit, Holloway Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Nc6 -C37 King's Gambit Accepted: Muzio Gambit, Kling and Horwitz Counterattack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O Qe7 -C37 King's Gambit Accepted: Muzio Gambit, Sarratt Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O gxf3 6. Qxf3 Qf6 -C37 King's Gambit Accepted: Muzio Gambit, Wild Muzio Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. O-O -C37 King's Gambit Accepted: Quaade Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Nc3 -C37 King's Gambit Accepted: Rosentreter Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 -C37 King's Gambit Accepted: Rosentreter Gambit, Bird Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Ne5 Qh4+ 6. g3 -C37 King's Gambit Accepted: Rosentreter Gambit, Sörensen Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Nc3 -C37 King's Gambit Accepted: Rosentreter Gambit, Testa Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Bxf4 -C37 King's Gambit Accepted: Salvio Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 -C37 King's Gambit Accepted: Salvio Gambit, Anderssen Counterattack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nh6 7. d4 d6 -C37 King's Gambit Accepted: Salvio Gambit, Cochrane Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 f3 -C37 King's Gambit Accepted: Salvio Gambit, Santa Maria Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nf6 -C37 King's Gambit Accepted: Salvio Gambit, Silberschmidt Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nh6 -C37 King's Gambit Accepted: Salvio Gambit, Viennese Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nc6 -C37 King's Gambit Accepted: Silberschmidt Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 g4 5. Ne5 Qh4+ 6. Kf1 Nh6 7. d4 f3 -C37 King's Gambit Accepted: Sörensen Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. d4 g4 5. Ne5 -C38 King's Gambit Accepted: Greco Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. h4 h6 6. d4 d6 7. Nc3 c6 8. hxg5 hxg5 9. Rxh8 Bxh8 10. Ne5 -C38 King's Gambit Accepted: Hanstein Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. O-O -C38 King's Gambit Accepted: Mayet Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. d4 d6 6. c3 -C38 King's Gambit Accepted: Philidor Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 5. h4 -C38 King's Gambit Accepted: Philidor Gambit, Schultz Variation 1. e4 e5 2. f4 exf4 3. Nf3 h6 4. Bc4 d6 5. d4 g5 6. h4 Bg7 7. Qd3 -C38 King's Gambit Accepted: Traditional Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. Bc4 Bg7 -C39 King's Gambit Accepted: Allgaier Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 -C39 King's Gambit Accepted: Allgaier Gambit, Thorold Attack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. d4 -C39 King's Gambit Accepted: Allgaier Gambit, Urusov Attack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Bc4+ -C39 King's Gambit Accepted: Allgaier, Blackburne Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Nc3 -C39 King's Gambit Accepted: Allgaier, Cook Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. d4 d5 8. Bxf4 dxe4 9. Bc4+ Kg7 10. Be5+ -C39 King's Gambit Accepted: Allgaier, Horny Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Qxg4 Nf6 8. Qxf4 Bd6 -C39 King's Gambit Accepted: Allgaier, Schlechter Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 Nf6 -C39 King's Gambit Accepted: Allgaier, Urusov Attack 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 Kxf7 7. Bc4+ d5 8. Bxd5+ Kg7 9. d4 -C39 King's Gambit Accepted: Kieseritzky Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 -C39 King's Gambit Accepted: Kieseritzky Gambit, Anderssen Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 -C39 King's Gambit Accepted: Kieseritzky Gambit, Anderssen-Cordel Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 8. d4 Nh5 9. Bxf4 Nxf4 -C39 King's Gambit Accepted: Kieseritzky Gambit, Berlin Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 -C39 King's Gambit Accepted: Kieseritzky Gambit, Berlin Defense, Rubinstein Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. d4 -C39 King's Gambit Accepted: Kieseritzky Gambit, Berlin Defense, de Riviere Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Nxg4 d5 -C39 King's Gambit Accepted: Kieseritzky Gambit, Brentano Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d5 -C39 King's Gambit Accepted: Kieseritzky Gambit, Brentano Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d5 6. d4 Nf6 7. Bxf4 -C39 King's Gambit Accepted: Kieseritzky Gambit, Brentano Defense, Caro Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d5 6. d4 Nf6 7. Bxf4 Nxe4 8. Nd2 -C39 King's Gambit Accepted: Kieseritzky Gambit, Cotter Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ng5 h6 6. Nxf7 -C39 King's Gambit Accepted: Kieseritzky Gambit, Kolisch Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 d6 -C39 King's Gambit Accepted: Kieseritzky Gambit, Long Whip 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 h5 -C39 King's Gambit Accepted: Kieseritzky Gambit, Neumann Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nc6 -C39 King's Gambit Accepted: Kieseritzky Gambit, Paulsen Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Bg7 -C39 King's Gambit Accepted: Kieseritzky Gambit, Paulsen Defense Deferred 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bg7 -C39 King's Gambit Accepted: Kieseritzky Gambit, Rice Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 8. O-O Bxe5 -C39 King's Gambit Accepted: Kieseritzky Gambit, Rosenthal Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Qe7 -C39 King's Gambit Accepted: Kieseritzky, Long Whip Defense, Jaenisch Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 h5 6. Bc4 Rh7 7. d4 Bh6 8. Nc3 -C39 King's Gambit Accepted: Kieseritzky, Polerio Defense 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Be7 -C39 King's Gambit Accepted: Kieseritzky, Rice Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Nf6 6. Bc4 d5 7. exd5 Bd6 8. O-O -C39 King's Gambit Accepted: Kieseritzky, Salvio Defense, Cozio Variation 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 g4 5. Ne5 Qe7 6. d4 f5 7. Bc4 -C39 King's Gambit Accepted: King's Knight's Gambit 1. e4 e5 2. f4 exf4 3. Nf3 g5 4. h4 -C40 Elephant Gambit 1. e4 e5 2. Nf3 d5 -C40 Elephant Gambit: Maróczy Gambit 1. e4 e5 2. Nf3 d5 3. exd5 Bd6 -C40 Elephant Gambit: Paulsen Countergambit 1. e4 e5 2. Nf3 d5 3. exd5 e4 -C40 Elephant Gambit: Wasp Variation 1. e4 e5 2. Nf3 d5 3. Nxe5 dxe4 4. Bc4 Qg5 -C40 Gunderam Defense 1. e4 e5 2. Nf3 Qe7 -C40 King's Knight Opening 1. e4 e5 2. Nf3 -C40 King's Pawn Game: Busch-Gass Gambit 1. e4 e5 2. Nf3 Bc5 -C40 King's Pawn Game: Busch-Gass Gambit, Chiodini Gambit 1. e4 e5 2. Nf3 Bc5 3. Nxe5 Nc6 -C40 King's Pawn Game: Damiano Defense 1. e4 e5 2. Nf3 f6 -C40 King's Pawn Game: Damiano Defense, Damiano Gambit 1. e4 e5 2. Nf3 f6 3. Nxe5 fxe5 4. Qh5+ g6 5. Qxe5+ Qe7 6. Qxh8 -C40 King's Pawn Game: Damiano Defense, Damiano Gambit, Chigorin Gambit 1. e4 e5 2. Nf3 f6 3. Nxe5 Qe7 4. Nf3 d5 -C40 King's Pawn Game: Gunderam Defense, Gunderam Gambit 1. e4 e5 2. Nf3 Qe7 3. Bc4 f5 -C40 King's Pawn Game: Gunderam Gambit 1. e4 e5 2. Nf3 c6 -C40 King's Pawn Game: La Bourdonnais Gambit 1. e4 e5 2. Nf3 Qf6 3. Bc4 Qg6 4. O-O -C40 King's Pawn Game: McConnell Defense 1. e4 e5 2. Nf3 Qf6 -C40 Latvian Gambit 1. e4 e5 2. Nf3 f5 -C40 Latvian Gambit Accepted 1. e4 e5 2. Nf3 f5 3. exf5 -C40 Latvian Gambit Accepted: Bilguer Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 -C40 Latvian Gambit Accepted: Bronstein Attack 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 fxe4 6. Be2 -C40 Latvian Gambit Accepted: Bronstein Gambit 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 fxe4 6. Qh5+ g6 7. Qe2 -C40 Latvian Gambit Accepted: Foltys Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. Nc4 fxe4 5. d3 -C40 Latvian Gambit Accepted: Foltys-Leonhardt Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. Nc4 -C40 Latvian Gambit Accepted: Leonhardt Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. Nc4 fxe4 5. Nc3 -C40 Latvian Gambit Accepted: Main Line 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 -C40 Latvian Gambit Accepted: Nimzowitsch Attack 1. e4 e5 2. Nf3 f5 3. Nxe5 Qf6 4. d4 d6 5. Nc4 fxe4 6. Ne3 -C40 Latvian Gambit: Behting Variation 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 Qg5 5. Nf7 Qxg2 6. Rf1 d5 7. Nxh8 Nf6 -C40 Latvian Gambit: Corkscrew Countergambit 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 Nf6 -C40 Latvian Gambit: Corkscrew Gambit 1. e4 e5 2. Nf3 f5 3. Nxe5 Nf6 4. Bc4 fxe4 5. Nf7 Qe7 6. Nxh8 d5 -C40 Latvian Gambit: Diepstraten Countergambit 1. e4 e5 2. Nf3 f5 3. c4 -C40 Latvian Gambit: Fraser Defense 1. e4 e5 2. Nf3 f5 3. Nxe5 Nc6 -C40 Latvian Gambit: Greco Variation 1. e4 e5 2. Nf3 f5 3. Nxe5 Qe7 -C40 Latvian Gambit: Lobster Gambit 1. e4 e5 2. Nf3 f5 3. g4 -C40 Latvian Gambit: Mason Countergambit 1. e4 e5 2. Nf3 f5 3. d4 -C40 Latvian Gambit: Mayet Attack 1. e4 e5 2. Nf3 f5 3. Bc4 -C40 Latvian Gambit: Mayet Attack, Morgado Defense 1. e4 e5 2. Nf3 f5 3. Bc4 Nf6 -C40 Latvian Gambit: Mayet Attack, Poisoned Pawn Variation 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 Qg5 5. d4 Qxg2 -C40 Latvian Gambit: Mayet Attack, Polerio-Svedenborg Variation 1. e4 e5 2. Nf3 f5 3. Bc4 fxe4 4. Nxe5 d5 -C40 Latvian Gambit: Mayet Attack, Strautins Gambit 1. e4 e5 2. Nf3 f5 3. Bc4 b5 -C40 Latvian Gambit: Mlotkowski Variation 1. e4 e5 2. Nf3 f5 3. Nc3 -C40 Latvian Gambit: Senechaud Gambit 1. e4 e5 2. Nf3 f5 3. b4 -C41 Philidor Defense 1. e4 e5 2. Nf3 d6 -C41 Philidor Defense 1. e4 e5 2. Nf3 d6 3. d4 -C41 Philidor Defense 1. e4 e5 2. Nf3 d6 3. Bc4 -C41 Philidor Defense 1. e4 e5 2. Nf3 d6 3. Bc4 Be7 -C41 Philidor Defense: Albin-Blackburne Gambit 1. e4 e5 2. Nf3 d6 3. d4 Bg4 4. dxe5 Nd7 -C41 Philidor Defense: Berger Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 Nf6 5. Nc3 Be7 6. Be2 O-O 7. O-O c5 8. Nf3 Nc6 9. Bg5 Be6 10. Re1 -C41 Philidor Defense: Bird Gambit 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. c3 -C41 Philidor Defense: Boden Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Qxd4 Bd7 -C41 Philidor Defense: Exchange Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 -C41 Philidor Defense: Exchange Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 -C41 Philidor Defense: Exchange Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 Nf6 -C41 Philidor Defense: Hanham Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 -C41 Philidor Defense: Hanham Variation, Delmar Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. c3 -C41 Philidor Defense: Hanham Variation, Krause Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. O-O -C41 Philidor Defense: Hanham Variation, Schlechter Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. Nc3 -C41 Philidor Defense: Hanham Variation, Sharp Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 Nb6 -C41 Philidor Defense: Hanham Variation, Steiner Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. O-O Be7 6. dxe5 -C41 Philidor Defense: Hanham, Kmoch Variation 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Bc4 c6 5. Ng5 -C41 Philidor Defense: Larsen Variation 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 g6 -C41 Philidor Defense: Lion Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 -C41 Philidor Defense: Lion Variation, Bishop Sacrifice 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. Bxf7+ -C41 Philidor Defense: Lion Variation, Delayed Bishop Sacrifice 1. e4 d6 2. d4 Nf6 3. Nc3 Nbd7 4. Nf3 e5 5. Bc4 Be7 6. dxe5 dxe5 7. Bxf7+ -C41 Philidor Defense: Lion Variation, Forcing Line 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. Ng5 O-O 7. Bxf7+ Rxf7 8. Ne6 -C41 Philidor Defense: Lion Variation, Lion's Claw, with Bc4 and h6 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. O-O h6 -C41 Philidor Defense: Lion Variation, Lion's Claw, with Be2 and c6 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Be2 Be7 6. O-O c6 -C41 Philidor Defense: Lion Variation, Shirov Gambit 1. e4 e5 2. Nf3 d6 3. d4 Nd7 4. Nc3 Ngf6 5. g4 -C41 Philidor Defense: Lion Variation, Sozin Variation 1. e4 d6 2. d4 Nf6 3. Nc3 e5 4. Nf3 Nbd7 5. Bc4 Be7 6. O-O O-O 7. Qe2 c6 8. a4 exd4 -C41 Philidor Defense: Lopez Countergambit 1. e4 e5 2. Nf3 d6 3. Bc4 f5 -C41 Philidor Defense: Lopez Countergambit, Jaenisch Variation 1. e4 e5 2. Nf3 d6 3. d4 f5 4. Bc4 exd4 5. Ng5 Nh6 6. Nxh7 -C41 Philidor Defense: Morphy Gambit 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Bc4 -C41 Philidor Defense: Nimzowitsch Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 -C41 Philidor Defense: Nimzowitsch Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. dxe5 -C41 Philidor Defense: Nimzowitsch Variation, Klein Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Bc4 -C41 Philidor Defense: Nimzowitsch Variation, Rellstab Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. dxe5 Nxe4 5. Qd5 -C41 Philidor Defense: Nimzowitsch Variation, Sokolsky Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. dxe5 Nxe4 5. Nbd2 -C41 Philidor Defense: Nimzowitsch, Larobok Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Nc3 Nbd7 5. Bc4 Be7 6. Ng5 O-O 7. Bxf7+ -C41 Philidor Defense: Nimzowitsch, Locock Variation 1. e4 e5 2. Nf3 d6 3. d4 Nf6 4. Ng5 -C41 Philidor Defense: Paulsen Attack 1. e4 e5 2. Nf3 d6 3. d4 exd4 4. Nxd4 d5 5. exd5 -C41 Philidor Defense: Philidor Countergambit 1. e4 e5 2. Nf3 d6 3. d4 f5 -C41 Philidor Defense: Philidor Countergambit, Berger Variation 1. e4 e5 2. Nf3 d6 3. d4 f5 4. dxe5 fxe4 5. Ng5 d5 6. e6 Bc5 7. Nc3 -C41 Philidor Defense: Philidor Countergambit, Zukertort Variation 1. e4 e5 2. Nf3 d6 3. d4 f5 4. Nc3 -C41 Philidor Defense: Philidor Countergambit, del Rio Attack 1. e4 e5 2. Nf3 d6 3. d4 f5 4. dxe5 fxe4 5. Ng5 d5 6. e6 -C41 Philidor Defense: Philidor Gambit 1. e4 e5 2. Nf3 d6 3. d4 Bd7 -C41 Philidor Defense: Steinitz Variation 1. e4 e5 2. Nf3 d6 3. Bc4 Be7 4. c3 -C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 -C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 -C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 -C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 -C42 Petrov's Defense 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 -C42 Petrov's Defense: Classical Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 -C42 Petrov's Defense: Classical Attack, Berger Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O Nc6 8. Re1 Bg4 9. c3 f5 10. Nbd2 -C42 Petrov's Defense: Classical Attack, Chigorin Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O Nc6 8. Re1 -C42 Petrov's Defense: Classical Attack, Chigorin Variation, Browne Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. c4 Nb4 9. cxd5 -C42 Petrov's Defense: Classical Attack, Chigorin Variation, Main Line 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. c4 Nb4 9. Be2 -C42 Petrov's Defense: Classical Attack, Closed Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 Nf6 -C42 Petrov's Defense: Classical Attack, Jaenisch Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. c4 -C42 Petrov's Defense: Classical Attack, Krause Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 7. O-O Be7 8. Re1 Bg4 9. c3 f5 10. c4 -C42 Petrov's Defense: Classical Attack, Marshall Trap 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 Bg4 9. cxd5 f5 10. Re1 Bxh2+ -C42 Petrov's Defense: Classical Attack, Marshall Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 -C42 Petrov's Defense: Classical Attack, Marshall Variation, Chinese Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 c6 9. Re1 Bg4 -C42 Petrov's Defense: Classical Attack, Maróczy Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O Nc6 8. Re1 Bg4 9. c3 f5 10. c4 Bh4 -C42 Petrov's Defense: Classical Attack, Mason Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Be7 7. O-O O-O -C42 Petrov's Defense: Classical Attack, Mason-Showalter Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Nc6 -C42 Petrov's Defense: Classical Attack, Staunton Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 c6 -C42 Petrov's Defense: Classical Attack, Tarrasch Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d4 d5 6. Bd3 Bd6 7. O-O O-O 8. c4 Bg4 -C42 Petrov's Defense: Cochrane Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nxf7 -C42 Petrov's Defense: Cochrane Gambit, Bishop Check Line 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nxf7 Kxf7 5. Bc4+ -C42 Petrov's Defense: Cochrane Gambit, Center Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nxf7 Kxf7 5. d4 -C42 Petrov's Defense: Cozio Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. Qe2 -C42 Petrov's Defense: Damiano Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nxe4 -C42 Petrov's Defense: Damiano Variation, Kholmov Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nxe4 4. Qe2 Qe7 -C42 Petrov's Defense: French Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. d3 -C42 Petrov's Defense: Italian Variation 1. e4 e5 2. Nf3 Nf6 3. Bc4 -C42 Petrov's Defense: Karklins-Martinovsky Variation 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nd3 -C42 Petrov's Defense: Kaufmann Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. c4 -C42 Petrov's Defense: Millennium Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. Bd3 -C42 Petrov's Defense: Moody Gambit 1. e4 e5 2. Nf3 Nf6 3. Qe2 Nc6 4. d4 -C42 Petrov's Defense: Nimzowitsch Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nf3 Nxe4 5. Nc3 -C42 Petrov's Defense: Paulsen Attack 1. e4 e5 2. Nf3 Nf6 3. Nxe5 d6 4. Nc4 -C42 Petrov's Defense: Stafford Gambit 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 -C42 Petrov's Defense: Stafford Gambit Accepted 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 -C42 Petrov's Defense: Stafford Gambit Accepted 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 5. Nc3 Bc5 -C42 Petrov's Defense: Stafford Gambit Accepted 1. e4 e5 2. Nf3 Nf6 3. Nxe5 Nc6 4. Nxc6 dxc6 5. d3 Bc5 -C42 Petrov's Defense: Three Knights Game 1. e4 e5 2. Nf3 Nf6 3. Nc3 -C43 Bishop's Opening: Urusov Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. Nf3 -C43 Bishop's Opening: Urusov Gambit, Keidansky Gambit 1. e4 e5 2. Bc4 Nf6 3. d4 exd4 4. Nf3 Nxe4 5. Qxd4 -C43 Petrov's Defense: Modern Attack 1. e4 e5 2. Nf3 Nf6 3. d4 -C43 Petrov's Defense: Modern Attack 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 -C43 Petrov's Defense: Modern Attack, Bardeleben Variation 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Qe2 Nc5 6. Nxd4 Nc6 -C43 Petrov's Defense: Modern Attack, Center Attack 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Qxd4 -C43 Petrov's Defense: Modern Attack, Center Variation 1. e4 e5 2. Nf3 Nf6 3. d4 Nxe4 4. Bd3 -C43 Petrov's Defense: Modern Attack, Murrey Variation 1. e4 e5 2. Nf3 Nf6 3. d4 Nxe4 4. Bd3 Nc6 -C43 Petrov's Defense: Modern Attack, Steinitz Variation 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Qe2 -C43 Petrov's Defense: Modern Attack, Symmetrical Variation 1. e4 e5 2. Nf3 Nf6 3. d4 d5 -C43 Petrov's Defense: Modern Attack, Tal Gambit 1. e4 e5 2. Nf3 Nf6 3. d4 exd4 4. e5 Ne4 5. Bb5 -C43 Petrov's Defense: Modern Attack, Trifunovic Variation 1. e4 e5 2. Nf3 Nf6 3. d4 Nxe4 4. Bd3 d5 5. Nxe5 Bd6 6. O-O O-O 7. c4 Bxe5 -C44 Dresden Opening: The Goblin 1. e4 e5 2. Nf3 Nc6 3. c4 Nf6 4. Nxe5 -C44 Irish Gambit 1. e4 e5 2. Nf3 Nc6 3. Nxe5 -C44 King's Knight Opening: Konstantinopolsky 1. e4 e5 2. Nf3 Nc6 3. g3 -C44 King's Knight Opening: Normal Variation 1. e4 e5 2. Nf3 Nc6 -C44 King's Pawn Game: Dresden Opening 1. e4 e5 2. Nf3 Nc6 3. c4 -C44 King's Pawn Game: Pachman Wing Gambit 1. e4 e5 2. Nf3 Nc6 3. b4 -C44 King's Pawn Game: Schulze-Müller Gambit 1. e4 e5 2. Nf3 Nc6 3. Nxe5 Nxe5 4. d4 -C44 King's Pawn Game: Tayler Opening 1. e4 e5 2. Nf3 Nc6 3. Be2 -C44 King's Pawn Game: Tayler Opening 1. e4 e5 2. Nf3 Nc6 3. Be2 Nf6 4. d4 -C44 King's Pawn Game: Tayler Opening, Basman Gambit 1. e4 e5 2. Nf3 Nc6 3. Be2 Nf6 4. d4 exd4 5. e5 -C44 King's Pawn Game: Tayler Opening, Inverted Hanham 1. e4 e5 2. Nf3 Nc6 3. Be2 Nf6 4. d3 d5 5. Nbd2 -C44 Latvian Gambit: Clam Gambit 1. e4 e5 2. Nf3 Nc6 3. d3 f5 4. exf5 -C44 Ponziani Opening 1. e4 e5 2. Nf3 Nc6 3. c3 -C44 Ponziani Opening: Caro Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Qa4 Bd7 -C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 -C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d3 -C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d3 d5 -C44 Ponziani Opening: Jaenisch Counterattack 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d3 d5 5. Nbd2 -C44 Ponziani Opening: Leonhardt Variation 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Qa4 Nf6 -C44 Ponziani Opening: Neumann Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. Bc4 -C44 Ponziani Opening: Ponziani Countergambit 1. e4 e5 2. Nf3 Nc6 3. c3 f5 -C44 Ponziani Opening: Ponziani Countergambit, Schmidt Attack 1. e4 e5 2. Nf3 Nc6 3. c3 f5 4. d4 d6 5. d5 -C44 Ponziani Opening: Romanishin Variation 1. e4 e5 2. Nf3 Nc6 3. c3 Be7 -C44 Ponziani Opening: Réti Variation 1. e4 e5 2. Nf3 Nc6 3. c3 Nge7 -C44 Ponziani Opening: Spanish Variation 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Bb5 -C44 Ponziani Opening: Spanish Variation, Harrwitz Attack, Nikitin Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Bb5 dxe4 5. Nxe5 Qd5 6. Qa4 -C44 Ponziani Opening: Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. c3 d5 4. Qa4 f6 -C44 Ponziani Opening: Vukovic Gambit 1. e4 e5 2. Nf3 Nc6 3. c3 Nf6 4. d4 Nxe4 5. d5 Bc5 -C44 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 -C44 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 -C44 Scotch Game: Benima Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Be7 4. d4 exd4 -C44 Scotch Game: Cochrane Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bb4+ 5. c3 dxc3 6. bxc3 Ba5 7. e5 -C44 Scotch Game: Cochrane-Shumov Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. Ng5 Nh6 6. Nxf7 Nxf7 7. Bxf7+ Kxf7 8. Qh5+ g6 9. Qxc5 d5 -C44 Scotch Game: Göring Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 -C44 Scotch Game: Göring Gambit, Bardeleben Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Bc4 Nf6 6. Nxc3 Bb4 -C44 Scotch Game: Göring Gambit, Double Pawn Sacrifice 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Bc4 -C44 Scotch Game: Göring Gambit, Main Line 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Nxc3 Bb4 -C44 Scotch Game: Hanneken Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bb4+ 5. c3 dxc3 6. O-O cxb2 7. Bxb2 Nf6 8. Ng5 O-O 9. e5 Nxe5 -C44 Scotch Game: Haxo Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 -C44 Scotch Game: Lolli Variation 1. e4 e5 2. Nf3 Nc6 3. d4 Nxd4 -C44 Scotch Game: Lolli Variation 1. e4 e5 2. Nf3 Nc6 3. d4 Nxd4 4. Nxd4 exd4 5. Qxd4 -C44 Scotch Game: Napoleon Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 Nxd4 4. Nxd4 exd4 5. Bc4 -C44 Scotch Game: Relfsson Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bb5 -C44 Scotch Game: Scotch Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 -C44 Scotch Game: Scotch Gambit, Advance Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. e5 -C44 Scotch Game: Scotch Gambit, Cochrane-Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. O-O d6 6. c3 Bg4 -C44 Scotch Game: Scotch Gambit, Dubois Réti Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 -C44 Scotch Game: Scotch Gambit, Göring Gambit Declined 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 d5 -C44 Scotch Game: Scotch Gambit, Kingside Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. e5 Ng4 -C44 Scotch Game: Scotch Gambit, London Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bb4+ -C44 Scotch Game: Scotch Gambit, Sarratt Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. Ng5 -C44 Scotch Game: Sea-Cadet Mate 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. c3 dxc3 5. Nxc3 d6 6. Bc4 Bg4 7. O-O Ne5 8. Nxe5 Bxd1 9. Bxf7+ Ke7 10. Nd5# -C44 Scotch Game: Vitzthum Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. Ng5 Nh6 6. Qh5 -C45 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 -C45 Scotch Game 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 Bb4+ 6. Bd2 -C45 Scotch Game: Alekhine Gambit 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 5. e5 -C45 Scotch Game: Blumenfeld Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. Nb5 -C45 Scotch Game: Braune Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Be3 -C45 Scotch Game: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 -C45 Scotch Game: Classical Variation, Blackburne Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Qd2 -C45 Scotch Game: Classical Variation, Intermezzo Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Nxc6 Qf6 -C45 Scotch Game: Classical Variation, Millennium Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Qg6 -C45 Scotch Game: Fraser Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nf3 -C45 Scotch Game: Ghulam-Kassim Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nxd4 5. Qxd4 d6 6. Bd3 -C45 Scotch Game: Gottschall Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Qd2 d5 8. Nb5 Bxe3 9. Qxe3 O-O 10. Nxc7 Rb8 11. Nxd5 Nxd5 12. exd5 Nb4 -C45 Scotch Game: Horwitz Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 -C45 Scotch Game: Horwitz Attack, Blackburne Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 Bb4+ 6. Bd2 Qxe4+ 7. Be2 Kd8 8. O-O Bxd2 9. Qxd2 -C45 Scotch Game: Malaniuk Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bb4+ -C45 Scotch Game: Meitner Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Nc2 -C45 Scotch Game: Mieses Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 5. Nxc6 bxc6 6. e5 -C45 Scotch Game: Modern Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nc3 Bb4 -C45 Scotch Game: Paulsen Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Bb5 -C45 Scotch Game: Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nf5 -C45 Scotch Game: Paulsen, Gunsberg Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Be3 Qf6 6. c3 Nge7 7. Bb5 Nd8 -C45 Scotch Game: Potter Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Nb3 -C45 Scotch Game: Romanishin Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Bc5 5. Nb3 Bb4+ -C45 Scotch Game: Rosenthal Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nb5 Bb4+ 6. Bd2 Qxe4+ 7. Be2 Kd8 8. O-O Bxd2 9. Nxd2 Qg6 -C45 Scotch Game: Schmidt Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 -C45 Scotch Game: Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 -C45 Scotch Game: Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Qh4 5. Nc3 -C45 Scotch Game: Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Nxd4 Nf6 5. Nxc6 bxc6 6. Nd2 -C46 Three Knights Opening 1. e4 e5 2. Nf3 Nc6 3. Nc3 -C46 Three Knights Opening 1. e4 e5 2. Nf3 Nc6 3. Nc3 Bb4 -C46 Three Knights Opening: Schlechter Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Bb4 4. Nd5 Nf6 -C46 Three Knights Opening: Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 g6 -C46 Three Knights Opening: Steinitz-Rosenthal Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 g6 4. d4 exd4 5. Nd5 -C46 Three Knights Opening: Winawer Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 f5 -C47 Four Knights Game 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 -C47 Four Knights Game: Glek System 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. g3 -C47 Four Knights Game: Glek System 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. g3 d5 5. exd5 Nxd5 6. Bg2 Nxc3 7. bxc3 -C47 Four Knights Game: Gunsberg Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. a3 -C47 Four Knights Game: Gunsberg Variation, Provincial Opening 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. a3 d6 5. h3 -C47 Four Knights Game: Halloween Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nxe5 -C47 Four Knights Game: Halloween Gambit, Oldtimer Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nxe5 Nxe5 5. d4 Ng6 6. e5 Ng8 7. Bc4 Bb4 8. Qf3 f5 -C47 Four Knights Game: Halloween Gambit, Plasma Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nxe5 Nxe5 5. d4 Nc6 6. d5 Ne5 7. f4 Ng6 8. e5 Ng8 9. d6 cxd6 10. exd6 Qf6 11. Nb5 Rb8 -C47 Four Knights Game: Italian Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Nc3 -C47 Four Knights Game: Italian Variation, Noa Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Nc3 Nxe4 5. Bxf7+ -C47 Four Knights Game: Naroditsky Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Nd5 -C47 Four Knights Game: Scotch Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 -C47 Four Knights Game: Scotch Variation Accepted 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 -C47 Four Knights Game: Scotch Variation Accepted, Main Line 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nxd4 Bb4 6. Nxc6 bxc6 7. Bd3 d5 8. exd5 O-O 9. O-O -C47 Four Knights Game: Scotch Variation, Belgrade Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nd5 -C47 Four Knights Game: Scotch Variation, Belgrade Gambit, Modern Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nd5 Nxe4 6. Qe2 f5 -C47 Four Knights Game: Scotch Variation, Krause Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 Bb4 5. Nxe5 -C47 Four Knights Game: Scotch Variation, Krause Gambit, Leonhardt Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 Bb4 5. Nxe5 Qe7 -C47 Four Knights Game: Scotch Variation, Oxford Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 Bb4 5. d5 Nd4 -C47 Four Knights Game: Scotch Variation, Schmid Defense 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. d4 exd4 5. Nxd4 Nxe4 -C48 Four Knights Game: Spanish Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 -C48 Four Knights Game: Spanish Variation, Bardeleben Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bc5 5. O-O O-O 6. Nxe5 Nxe5 7. d4 Bd6 8. f4 Nc6 9. e5 Bb4 -C48 Four Knights Game: Spanish Variation, Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bc5 -C48 Four Knights Game: Spanish Variation, Ranken Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 a6 5. Bxc6 -C48 Four Knights Game: Spanish Variation, Rubinstein Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 -C48 Four Knights Game: Spanish Variation, Rubinstein Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Be2 -C48 Four Knights Game: Spanish Variation, Rubinstein Variation 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Nd4 5. Nxe5 Qe7 6. f4 -C48 Four Knights Game: Spanish Variation, Rubinstein Variation Accepted 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Nxd4 -C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Henneberger Variation 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Nd4 5. O-O -C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Marshall Gambit 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Ba4 Bc5 6. Nxe5 O-O -C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Marshall Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Nxe5 Bc5 6. O-O O-O -C48 Four Knights Game: Spanish Variation, Rubinstein Variation, Maróczy Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Nd4 5. Be2 Nxf3+ 6. Bxf3 Bc5 7. O-O O-O 8. d3 d6 9. Na4 Bb6 -C48 Four Knights Game: Spanish Variation, Spielmann Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 a6 5. Bxc6 dxc6 6. Nxe5 Nxe4 7. Nxe4 Qd4 8. O-O Qxe5 9. Re1 Be6 10. d4 Qd5 -C49 Four Knights Game: Spanish Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Bxc3 -C49 Four Knights Game: Spanish Variation, Alatortsev Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Qe7 7. Ne2 d5 -C49 Four Knights Game: Spanish Variation, Double Spanish 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 -C49 Four Knights Game: Spanish Variation, Double Spanish 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 -C49 Four Knights Game: Spanish Variation, Gunsberg Counterattack 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Bb4 5. O-O O-O 6. Nd5 Nxd5 7. exd5 e4 -C49 Four Knights Game: Spanish Variation, Janowski Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Bxc3 7. bxc3 d6 8. Re1 -C49 Four Knights Game: Spanish Variation, Nimzowitsch Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. Bxc6 -C49 Four Knights Game: Spanish Variation, Svenonius Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 Bxc3 7. bxc3 d5 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Bxc3 8. bxc3 Qe7 9. Re1 Nd8 10. d4 Bg4 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Ne7 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Ne2 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation, Blake Variation 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Ne7 8. Nh4 c6 9. Bc4 d5 10. Bb3 Qd6 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation, Metger Unpin 1. e4 e5 2. Nf3 Nc6 3. Nc3 Nf6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Bxc3 8. bxc3 Qe7 -C49 Four Knights Game: Spanish Variation, Symmetrical Variation, Tarrasch Variation 1. e4 e5 2. Nf3 Nf6 3. Nc3 Nc6 4. Bb5 Bb4 5. O-O O-O 6. d3 d6 7. Bg5 Be6 -C50 Four Knights Game: Italian Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Nc3 Nf6 -C50 Italian Game 1. e4 e5 2. Nf3 Nc6 3. Bc4 -C50 Italian Game: Anti-Fried Liver Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 h6 -C50 Italian Game: Blackburne-Kostić Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nd4 -C50 Italian Game: Classical Variation, Albin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. c3 -C50 Italian Game: Deutz Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d4 -C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 -C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. Nc3 d6 6. d3 -C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Nc3 Nf6 5. O-O O-O -C50 Italian Game: Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Nc3 Nf6 5. O-O O-O 6. d3 -C50 Italian Game: Giuoco Pianissimo, Canal Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 Nf6 5. Nc3 d6 6. Bg5 -C50 Italian Game: Giuoco Pianissimo, Dubois Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 f5 5. Ng5 f4 -C50 Italian Game: Giuoco Pianissimo, Italian Four Knights Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 Nf6 5. Nc3 -C50 Italian Game: Giuoco Pianissimo, Lucchini Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d3 f5 -C50 Italian Game: Giuoco Pianissimo, Normal 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 Bc5 -C50 Italian Game: Giuoco Piano 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 -C50 Italian Game: Hungarian Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Be7 -C50 Italian Game: Hungarian Defense, Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Be7 4. d4 exd4 5. c3 Nf6 6. e5 Ne4 -C50 Italian Game: Jerome Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. Bxf7+ -C50 Italian Game: Paris Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 d6 -C50 Italian Game: Rosentreter Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. d4 -C50 Italian Game: Rousseau Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 f5 -C51 Italian Game: Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 -C51 Italian Game: Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 -C51 Italian Game: Evans Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 -C51 Italian Game: Evans Gambit Declined 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 -C51 Italian Game: Evans Gambit Declined 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. a4 -C51 Italian Game: Evans Gambit Declined, Cordel Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. Bb2 -C51 Italian Game: Evans Gambit Declined, Hicken Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Qg5 7. Qf3 Qxe5 8. Qxf7+ Kd8 9. Bb2 -C51 Italian Game: Evans Gambit Declined, Hirschbach Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Qg5 -C51 Italian Game: Evans Gambit Declined, Lange Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Nh6 -C51 Italian Game: Evans Gambit Declined, Pavlov Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Nh6 7. d4 d6 8. Bxh6 dxe5 9. Bxg7 Rg8 10. Bxf7+ Kxf7 11. Bxe5 Qg5 12. Nd2 -C51 Italian Game: Evans Gambit Declined, Showalter Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. a4 a6 6. Nc3 -C51 Italian Game: Evans Gambit Declined, Vasquez Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bb6 5. b5 Na5 6. Nxe5 Qg5 7. Bxf7+ Ke7 8. Qh5 -C51 Italian Game: Evans Gambit, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Be7 -C51 Italian Game: Evans Gambit, Anderssen Variation, Cordel Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Be7 6. d4 Na5 -C51 Italian Game: Evans Gambit, Fontaine Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 b5 -C51 Italian Game: Evans Gambit, Fraser Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 10. Qa4 -C51 Italian Game: Evans Gambit, Fraser-Mortimer Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 10. Qa4 Bd7 11. Qb3 Na5 12. Bxf7+ Kf8 13. Qc2 -C51 Italian Game: Evans Gambit, Göring Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Na5 10. Bg5 -C51 Italian Game: Evans Gambit, Harding Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. cxd4 Bb4+ 8. Bd2 -C51 Italian Game: Evans Gambit, Hein Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 d5 -C51 Italian Game: Evans Gambit, Mayet Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bf8 -C51 Italian Game: Evans Gambit, McDonnell Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 -C51 Italian Game: Evans Gambit, McDonnell Defense, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 -C51 Italian Game: Evans Gambit, Morphy Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 -C51 Italian Game: Evans Gambit, Mortimer-Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Bg4 10. Qa4 Bd7 11. Qb3 Na5 12. Bxf7+ Kf8 13. Qc2 Kxf7 -C51 Italian Game: Evans Gambit, Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. d5 Na5 10. Bb2 Ne7 -C51 Italian Game: Evans Gambit, Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. Nc3 Na5 10. Bg5 f6 11. Be3 -C51 Italian Game: Evans Gambit, Stone-Ware Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bd6 -C51 Italian Game: Evans Gambit, Ulvestad Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Bc5 6. d4 exd4 7. O-O d6 8. cxd4 Bb6 9. d5 Na5 10. Bb2 -C52 Italian Game: Evans Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 -C52 Italian Game: Evans Gambit, Alapin-Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 7. d4 Bg4 -C52 Italian Game: Evans Gambit, Anderssen Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O Nf6 7. d4 exd4 -C52 Italian Game: Evans Gambit, Bronstein Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 -C52 Italian Game: Evans Gambit, Compromised Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O dxc3 -C52 Italian Game: Evans Gambit, Compromised Defense, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O dxc3 8. Qb3 Qf6 9. e5 Qg6 10. Nxc3 Nge7 11. Ba3 -C52 Italian Game: Evans Gambit, Compromised Defense, Potter Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O dxc3 8. Qb3 Qf6 9. e5 Qg6 10. Nxc3 Nge7 11. Rd1 -C52 Italian Game: Evans Gambit, Dufresne Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d3 -C52 Italian Game: Evans Gambit, Johner Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O b5 -C52 Italian Game: Evans Gambit, Laroche Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 Nf6 -C52 Italian Game: Evans Gambit, Lasker Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 7. d4 Bb6 -C52 Italian Game: Evans Gambit, Leonhardt Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 b5 -C52 Italian Game: Evans Gambit, Levenfish Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 7. Qb3 Qd7 8. dxe5 dxe5 9. O-O Bb6 10. Ba3 Na5 11. Nxe5 -C52 Italian Game: Evans Gambit, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 -C52 Italian Game: Evans Gambit, Mieses Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O Nge7 -C52 Italian Game: Evans Gambit, Pierce Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 -C52 Italian Game: Evans Gambit, Richardson Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O Nf6 7. d4 O-O 8. Nxe5 -C52 Italian Game: Evans Gambit, Sanders-Alapin Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O d6 7. d4 Bd7 -C52 Italian Game: Evans Gambit, Slow Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. O-O -C52 Italian Game: Evans Gambit, Sokolsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 7. Bg5 -C52 Italian Game: Evans Gambit, Tartakower Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 d6 7. Qb3 -C52 Italian Game: Evans Gambit, Waller Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. b4 Bxb4 5. c3 Ba5 6. d4 exd4 7. O-O d6 8. Qb3 -C53 Italian Game: Bird's Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. b4 -C53 Italian Game: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 -C53 Italian Game: Classical Variation, Center Holding Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 -C53 Italian Game: Classical Variation, Closed Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 -C53 Italian Game: Classical Variation, Eisinger Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 6. d5 Nb8 7. d6 -C53 Italian Game: Classical Variation, La Bourdonnais Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 d6 5. d4 exd4 6. cxd4 Bb6 -C53 Italian Game: Classical Variation, Mestel Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 6. Bg5 -C53 Italian Game: Classical Variation, Tarrasch Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Qe7 5. d4 Bb6 6. O-O d6 7. a4 a6 8. h3 Nf6 9. Re1 -C54 Italian Game: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 -C54 Italian Game: Classical Variation, Center Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 -C54 Italian Game: Classical Variation, Ghulam-Kassim Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 Ne4 7. Bd5 Nxf2 8. Kxf2 dxc3+ 9. Kg3 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. Nbd2 O-O 7. O-O -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 h6 6. c3 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a5 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 Bb6 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 O-O -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. a4 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. a4 Ba7 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. a4 O-O -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. Re1 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 a6 7. Re1 Ba7 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 h6 7. Re1 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 h6 7. Nbd2 -C54 Italian Game: Classical Variation, Giuoco Pianissimo 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 O-O 6. c3 d5 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, Albin Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. b4 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. O-O O-O 7. Re1 a6 8. Bb3 Ba7 9. h3 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a4 a5 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. O-O O-O 7. a4 a5 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a5 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 a5 6. c3 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a6 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 a6 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, with a6 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. Nbd2 a6 -C54 Italian Game: Classical Variation, Giuoco Pianissimo, with h6 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d3 d6 6. c3 h6 -C54 Italian Game: Classical Variation, Greco Gambit, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 d5 7. Bb5 Ne4 8. cxd4 Bb4+ -C54 Italian Game: Classical Variation, Greco Gambit, Dubov Italian 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. b4 -C54 Italian Game: Classical Variation, Greco Gambit, Greco Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Nxc3 -C54 Italian Game: Classical Variation, Greco Gambit, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 -C54 Italian Game: Classical Variation, Greco Gambit, Modern Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 -C54 Italian Game: Classical Variation, Greco Gambit, Modern Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. e5 d5 -C54 Italian Game: Classical Variation, Greco Gambit, Moeller-Bayonet Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 Bf6 10. Re1 Ne7 11. Rxe4 d6 12. g4 -C54 Italian Game: Classical Variation, Greco Gambit, Moeller-Therkatz Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 -C54 Italian Game: Classical Variation, Greco Gambit, Traditional Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 -C54 Italian Game: Classical Variation, with d5 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d5 -C54 Italian Game: Giuoco Piano, Aitken Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Nxc3 9. bxc3 Bxc3 10. Ba3 -C54 Italian Game: Giuoco Piano, Bernstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Nxc3 9. bxc3 Bxc3 10. Qb3 d5 -C54 Italian Game: Giuoco Piano, Cracow Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Kf1 -C54 Italian Game: Giuoco Piano, Greco's Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 -C54 Italian Game: Giuoco Piano, Holzhausen Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. d4 Bxd4 6. Nxd4 Nxd4 7. Bg5 d6 8. f4 Qe7 9. fxe5 dxe5 10. Nc3 -C54 Italian Game: Giuoco Piano, Krause Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Bd2 Nxe4 8. Bxb4 Nxb4 9. Bxf7+ Kxf7 10. Qb3+ d5 11. Ne5+ Kf6 12. f3 -C54 Italian Game: Giuoco Piano, Rosentreter Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. d4 Bxd4 6. Nxd4 Nxd4 7. Bg5 h6 8. Bh4 g5 9. f4 -C54 Italian Game: Giuoco Piano, Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. bxc3 d5 10. Ba3 -C54 Italian Game: Giuoco Piano, Therkatz-Herzog Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. cxd4 Bb4+ 7. Nc3 Nxe4 8. O-O Bxc3 9. d5 Bf6 10. Re1 Ne7 11. Rxe4 d6 12. Bg5 Bxg5 13. Nxg5 O-O 14. Nxh7 -C55 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 -C55 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. O-O Bc5 5. d4 Bxd4 6. Nxd4 Nxd4 7. Bg5 d6 -C55 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Nc3 Nxe4 5. Nxe4 d5 -C55 Italian Game: Two Knights Defense, Modern Bishop's Opening 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 -C55 Italian Game: Two Knights Defense, Modern Bishop's Opening 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 Be7 -C55 Italian Game: Two Knights Defense, Modern Bishop's Opening 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d3 h6 5. O-O d6 -C56 Italian Game: Scotch Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O -C56 Italian Game: Scotch Gambit, Anderssen Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 6. Re1 d5 7. Bxd5 Qxd5 8. Nc3 -C56 Italian Game: Scotch Gambit, Anderssen Attack, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 6. Re1 d5 7. Bxd5 Qxd5 8. Nc3 Qa5 9. Nxe4 Be6 10. Bd2 Qd5 11. Bg5 -C56 Italian Game: Scotch Gambit, Canal Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Nxe4 6. Re1 d5 7. Nc3 -C56 Italian Game: Scotch Gambit, Double Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 -C56 Italian Game: Scotch Gambit, Janowski Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O d6 -C56 Italian Game: Scotch Gambit, Max Lange Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 -C56 Italian Game: Scotch Gambit, Max Lange Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. e5 d5 6. Bb5 Ne4 -C56 Italian Game: Scotch Gambit, Max Lange Attack Accepted 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. O-O Nf6 5. d4 exd4 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. fxg7 -C56 Italian Game: Scotch Gambit, Max Lange Attack, Long Variation 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 Qd5 10. Nc3 Qf5 11. Nce4 -C56 Italian Game: Scotch Gambit, Max Lange Attack, Spielmann Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 6. e5 Ng4 -C56 Italian Game: Scotch Gambit, Nakhmanson Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Nxe4 6. Nc3 -C56 Italian Game: Scotch Gambit, Walbrodt-Baird Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d4 exd4 6. O-O -C56 Italian Game: Scotch Gambit, de Riviere Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Be7 -C56 Italian Game: Scotch Invitation Declined 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 d6 -C56 Italian Game: Two Knights Defense, Keidansky Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. e5 d5 6. Bb5 Ne4 7. Nxd4 Bc5 8. Nxc6 Bxf2+ 9. Kf1 Qh4 -C56 Italian Game: Two Knights Defense, Max Lange Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Bc5 6. e5 -C56 Italian Game: Two Knights Defense, Max Lange Attack, Berger Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Bc5 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 Qd5 10. Nc3 Qf5 11. g4 Qg6 12. Nce4 Bb6 13. f4 O-O-O -C56 Italian Game: Two Knights Defense, Max Lange Attack, Krause Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Bc5 6. e5 Ng4 7. c3 -C56 Italian Game: Two Knights Defense, Max Lange Attack, Loman Defense 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Bc5 5. O-O Nf6 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 g6 -C56 Italian Game: Two Knights Defense, Max Lange Attack, Rubinstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. O-O Bc5 6. e5 d5 7. exf6 dxc4 8. Re1+ Be6 9. Ng5 Qd5 10. Nc3 Qf5 11. Nce4 Bf8 -C56 Italian Game: Two Knights Defense, Open Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 -C56 Italian Game: Two Knights Defense, Perreux Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. d4 exd4 5. Ng5 -C56 Italian Game: Two Knights Defense, Yurdansky Attack 1. e4 e5 2. Nf3 Nc6 3. d4 exd4 4. Bc4 Nf6 5. O-O Nxe4 6. Re1 d5 7. Bxd5 Qxd5 8. Nc3 Qa5 9. Nxe4 Be6 10. Bg5 h6 11. Bh4 g5 12. Nf6+ Ke7 13. b4 -C57 Italian Game: Two Knights Defense, Fegatello Attack, Leonhardt Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. Nxf7 Kxf7 7. Qf3+ Ke6 8. Nc3 Nb4 9. Qe4 c6 10. a3 Na6 11. d4 Nc7 -C57 Italian Game: Two Knights Defense, Fried Liver Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. Nxf7 -C57 Italian Game: Two Knights Defense, Fritz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nd4 -C57 Italian Game: Two Knights Defense, Fritz, Gruber Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nd4 6. c3 b5 7. Bf1 Nxd5 8. Ne4 -C57 Italian Game: Two Knights Defense, Kloss Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nb4 -C57 Italian Game: Two Knights Defense, Knight Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 -C57 Italian Game: Two Knights Defense, Knight Attack, Normal Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 -C57 Italian Game: Two Knights Defense, Lolli Attack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. d4 -C57 Italian Game: Two Knights Defense, Pincus Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Nxd5 6. d4 Bb4+ -C57 Italian Game: Two Knights Defense, Ponziani-Steinitz Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Nxe4 -C57 Italian Game: Two Knights Defense, Traxler Counterattack 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 -C57 Italian Game: Two Knights Defense, Traxler Counterattack, Bishop Sacrifice Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Bxf7+ -C57 Italian Game: Two Knights Defense, Traxler Counterattack, King March Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Nxf7 Bxf2+ 6. Kxf2 Nxe4+ 7. Ke3 -C57 Italian Game: Two Knights Defense, Traxler Counterattack, Knight Sacrifice Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Nxf7 -C57 Italian Game: Two Knights Defense, Traxler Variation, Trencianske-Teplice Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 Bc5 5. Bxf7+ Ke7 6. d4 -C57 Italian Game: Two Knights Defense, Ulvestad Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 b5 -C57 Italian Game: Two Knights Defense, Ulvestad Variation, Kurkin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 b5 6. Bf1 h6 7. Nxf7 -C58 Italian Game: Two Knights Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 -C58 Italian Game: Two Knights Defense, Blackburne Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 cxb5 -C58 Italian Game: Two Knights Defense, Colman Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 Rb8 -C58 Italian Game: Two Knights Defense, Maróczy Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. d3 h6 7. Nf3 e4 8. Qe2 Nxc4 9. dxc4 Be7 -C58 Italian Game: Two Knights Defense, Paoli Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 Qc7 9. Bd3 -C58 Italian Game: Two Knights Defense, Polerio Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 -C58 Italian Game: Two Knights Defense, Polerio Defense, Bishop Check Line 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ -C58 Italian Game: Two Knights Defense, Polerio Defense, Bogoljubow Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Qf3 -C58 Italian Game: Two Knights Defense, Polerio Defense, Kieseritzky Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. d3 -C58 Italian Game: Two Knights Defense, Polerio Defense, Yankovich Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. d3 h6 7. Nf3 e4 8. Qe2 Nxc4 9. dxc4 Bc5 10. Nfd2 -C59 Italian Game: Two Knights Defense, Knorre Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 9. Nf3 e4 10. Ne5 Bd6 11. d4 Qc7 12. Bd2 -C59 Italian Game: Two Knights Defense, Polerio Defense, Göring Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 9. Nf3 e4 10. Ne5 Qc7 -C59 Italian Game: Two Knights Defense, Polerio Defense, Suhle Defense 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 -C59 Italian Game: Two Knights Defense, Steinitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bc4 Nf6 4. Ng5 d5 5. exd5 Na5 6. Bb5+ c6 7. dxc6 bxc6 8. Be2 h6 9. Nh3 -C60 Ruy Lopez 1. e4 e5 2. Nf3 Nc6 3. Bb5 -C60 Ruy Lopez: Alapin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bb4 -C60 Ruy Lopez: Alapin Defense, Alapin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bb4 4. c3 Ba5 5. Bxc6 dxc6 -C60 Ruy Lopez: Brentano Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 g5 -C60 Ruy Lopez: Bulgarian Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a5 -C60 Ruy Lopez: Cozio Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nge7 -C60 Ruy Lopez: Cozio Defense, Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nge7 4. Nc3 g6 -C60 Ruy Lopez: Cozio Defense, Tartakower Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 4. d4 exd4 5. Nxd4 Bg7 6. Be3 Nge7 7. Nc3 O-O 8. Qd2 d5 -C60 Ruy Lopez: Fianchetto Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 -C60 Ruy Lopez: Fianchetto Defense, Kevitz Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 4. c3 f5 -C60 Ruy Lopez: Lucena Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Be7 -C60 Ruy Lopez: Nürnberg Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f6 -C60 Ruy Lopez: Pollock Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Na5 -C60 Ruy Lopez: Retreat Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nb8 -C60 Ruy Lopez: Rotary-Albany Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 b6 -C60 Ruy Lopez: Spanish Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d5 -C60 Ruy Lopez: Spanish Countergambit, Harding Countergambit, Fricke Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d5 4. Nxe5 Qg5 5. O-O -C60 Ruy Lopez: Spanish Countergambit, Harding Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d5 4. Nxe5 Qg5 5. Nxc6 -C60 Ruy Lopez: Vinogradov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Qe7 -C61 Ruy Lopez: Bird Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nd4 -C61 Ruy Lopez: Bird Variation, Paulsen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nd4 4. Nxd4 exd4 5. O-O Ne7 -C62 Ruy Lopez: Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 -C62 Ruy Lopez: Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 -C62 Ruy Lopez: Steinitz Defense, Center Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 exd4 5. O-O -C62 Ruy Lopez: Steinitz Defense, Nimzowitsch Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 Bd7 5. Nc3 Nf6 6. Bxc6 -C62 Ruy Lopez: Steinitz Defense, Semi-Duras Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 Bd7 5. c4 -C63 Ruy Lopez: Schliemann Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 -C63 Ruy Lopez: Schliemann Defense, Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 d5 6. Nxe5 dxe4 7. Nxc6 Qg5 -C63 Ruy Lopez: Schliemann Defense, Dyckhoff Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 -C63 Ruy Lopez: Schliemann Defense, Exchange Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Bxc6 -C63 Ruy Lopez: Schliemann Defense, Jaenisch Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. exf5 -C63 Ruy Lopez: Schliemann Defense, Kostić Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 Be7 -C63 Ruy Lopez: Schliemann Defense, Möhring Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 d5 6. Nxe5 dxe4 7. Nxc6 Qd5 -C63 Ruy Lopez: Schliemann Defense, Schönemann Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. d4 -C63 Ruy Lopez: Schliemann Defense, Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 f5 4. Nc3 fxe4 5. Nxe4 Nf6 -C64 Ruy Lopez: Classical Defense, Benelux Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 5. c3 O-O 6. d4 Bb6 -C64 Ruy Lopez: Classical Defense, Boden Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 Qe7 -C64 Ruy Lopez: Classical Defense, Zaitsev Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. O-O Nd4 5. b4 -C64 Ruy Lopez: Classical Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 -C64 Ruy Lopez: Classical Variation, Central Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 -C64 Ruy Lopez: Classical Variation, Charousek Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 Bb6 -C64 Ruy Lopez: Classical Variation, Cordel Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 f5 -C64 Ruy Lopez: Classical Variation, Konikowski Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. c3 d5 -C64 Ruy Lopez: Classical Variation, Modern Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 5. c3 O-O 6. d4 Bb6 7. Bg5 -C64 Ruy Lopez: Classical Variation, Spanish Wing Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Bc5 4. b4 -C65 Ruy Lopez: Berlin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 -C65 Ruy Lopez: Berlin Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O -C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 -C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 d6 5. Bxc6+ -C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Duras Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 d6 5. c4 -C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Kaufmann Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 Bc5 5. Be3 -C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Mortimer Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 Ne7 5. Nxe5 c6 -C65 Ruy Lopez: Berlin Defense, Anti-Berlin Variation, Mortimer Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d3 Ne7 -C65 Ruy Lopez: Berlin Defense, Beverwijk Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 -C65 Ruy Lopez: Berlin Defense, Fishing Pole Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Ng4 -C65 Ruy Lopez: Berlin Defense, Nyholm Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. d4 exd4 5. O-O -C65 Ruy Lopez: Classical Variation, Zukertort Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Bc5 5. c3 -C65 Ruy Lopez: Halloween Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. Nxe5 -C66 Ruy Lopez: Berlin Defense, Closed Bernstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 Be7 7. Bg5 -C66 Ruy Lopez: Berlin Defense, Closed Showalter Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 Be7 7. Bxc6 -C66 Ruy Lopez: Berlin Defense, Closed Wolf Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 exd4 -C66 Ruy Lopez: Berlin Defense, Hedgehog Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Bd7 6. Nc3 Be7 -C66 Ruy Lopez: Berlin Defense, Improved Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 -C66 Ruy Lopez: Berlin Defense, Tarrasch Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 d6 4. d4 Bd7 5. Nc3 Nf6 6. O-O Be7 7. Re1 O-O -C66 Ruy Lopez: Closed Berlin Defense, Chigorin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O d6 5. d4 Nd7 -C67 Ruy Lopez: Berlin Defense, Berlin Wall 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 8. Qxd8+ Kxd8 9. Nc3 Bd7 -C67 Ruy Lopez: Berlin Defense, Cordel Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nf5 -C67 Ruy Lopez: Berlin Defense, Minckwitz Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. dxe5 -C67 Ruy Lopez: Berlin Defense, Pillsbury Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. b3 -C67 Ruy Lopez: Berlin Defense, Rio Gambit Accepted 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 -C67 Ruy Lopez: Berlin Defense, Rio de Janeiro Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 -C67 Ruy Lopez: Berlin Defense, Rio de Janeiro Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. Nc3 O-O 10. Re1 Nc5 11. Nd4 Ne6 12. Be3 Nxd4 13. Bxd4 c5 -C67 Ruy Lopez: Berlin Defense, Rosenthal Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 a6 -C67 Ruy Lopez: Berlin Defense, Trifunovic Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 d5 -C67 Ruy Lopez: Berlin Defense, Winawer Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. Nd4 -C67 Ruy Lopez: Berlin Defense, Zukertort Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Be7 6. Qe2 Nd6 7. Bxc6 bxc6 8. dxe5 Nb7 9. c4 -C67 Ruy Lopez: Berlin Defense, l'Hermet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 -C67 Ruy Lopez: Berlin Defense, l'Hermet Variation, Berlin Wall Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Nf5 8. Qxd8+ Kxd8 -C67 Ruy Lopez: Berlin Defense, l'Hermet Variation, Westerinen Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Bxc6 dxc6 7. dxe5 Ne4 -C67 Ruy Lopez: Open Berlin Defense, Showalter Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. Ba4 -C67 Ruy Lopez: Open Berlin Defense, l'Hermet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O Nxe4 5. d4 Nd6 6. dxe5 -C68 Ruy Lopez: Exchange Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 -C68 Ruy Lopez: Exchange Variation, Alekhine Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. d4 exd4 6. Qxd4 Qxd4 7. Nxd4 Bd6 -C68 Ruy Lopez: Exchange Variation, Keres Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. Nc3 -C68 Ruy Lopez: Exchange Variation, Lutikov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 bxc6 -C68 Ruy Lopez: Exchange Variation, Romanovsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. Nc3 f6 6. d3 -C68 Ruy Lopez: Exchange, Alekhine Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. d4 exd4 6. Qxd4 Qxd4 7. Nxd4 Bd7 -C69 Ruy Lopez: Exchange Variation, Alapin Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O Bg4 6. h3 h5 -C69 Ruy Lopez: Exchange Variation, Bronstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O Qd6 -C69 Ruy Lopez: Exchange Variation, Gligoric Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O f6 -C69 Ruy Lopez: Exchange Variation, King's Bishop Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O Bd6 -C69 Ruy Lopez: Exchange Variation, Normal Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Bxc6 dxc6 5. O-O -C70 Ruy Lopez: Bird's Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nd4 -C70 Ruy Lopez: Morphy Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 -C70 Ruy Lopez: Morphy Defense, Alapin's Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bb4 -C70 Ruy Lopez: Morphy Defense, Caro Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 -C70 Ruy Lopez: Morphy Defense, Classical Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Bc5 -C70 Ruy Lopez: Morphy Defense, Cozio Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nge7 -C70 Ruy Lopez: Morphy Defense, Fianchetto Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 g6 -C70 Ruy Lopez: Morphy Defense, Graz Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 Bc5 -C70 Ruy Lopez: Morphy Defense, Norwegian Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 Na5 -C70 Ruy Lopez: Morphy Defense, Norwegian Variation, Nightingale Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 Na5 6. Bxf7+ -C70 Ruy Lopez: Morphy Defense, Schliemann Defense Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 f5 -C70 Ruy Lopez: Morphy Defense, Schliemann Defense Deferred, Jaenisch Gambit Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 f5 5. exf5 -C71 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 -C71 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. Nc3 -C71 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c4 -C71 Ruy Lopez: Noah's Ark Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 b5 5. Bb3 d6 6. d4 Nxd4 7. Nxd4 exd4 8. Qxd4 c5 -C72 Ruy Lopez: Closed, Kecskemet Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. O-O Bd7 6. c3 Nf6 7. d4 Be7 8. Nbd2 O-O 9. Re1 Be8 -C72 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. O-O -C73 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. Bxc6+ bxc6 6. d4 -C73 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. Bxc6+ bxc6 6. d4 f6 -C74 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 -C74 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 f5 6. exf5 Bxf5 7. O-O -C74 Ruy Lopez: Morphy Defense, Modern Steinitz Defense, Siesta Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 f5 -C75 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 Bd7 -C75 Ruy Lopez: Morphy Defense, Modern Steinitz Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 d6 5. c3 Bd7 6. d4 Nge7 -C76 Ruy Lopez: Morphy Defense, Modern Steinitz Defense, Fianchetto Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 g6 4. c3 a6 5. Ba4 d6 6. d4 Bd7 -C77 Ruy Lopez: Morphy Defense, Anderssen Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. d3 -C77 Ruy Lopez: Morphy Defense, Bayreuth Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Bxc6 -C77 Ruy Lopez: Morphy Defense, Duras Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. d3 d6 6. c4 -C77 Ruy Lopez: Morphy Defense, Jaffe Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. c3 -C77 Ruy Lopez: Morphy Defense, Mackenzie Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. d4 -C77 Ruy Lopez: Morphy Defense, Tarrasch Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Nc3 -C77 Ruy Lopez: Morphy Defense, Wormald Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Qe2 -C77 Ruy Lopez: Wormald Attack, Grünfeld Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Qe2 b5 6. Bb3 Be7 7. d4 d6 8. c3 Bg4 -C78 Ruy Lopez: Brix Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O g6 -C78 Ruy Lopez: Central Countergambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d5 -C78 Ruy Lopez: Morphy Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O -C78 Ruy Lopez: Morphy Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 d6 -C78 Ruy Lopez: Morphy Defense, Arkhangelsk Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 Bb7 -C78 Ruy Lopez: Morphy Defense, Møller Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Bc5 -C78 Ruy Lopez: Morphy Defense, Neo-Arkhangelsk Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 Bc5 -C78 Ruy Lopez: Morphy Defense, Wing Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 Be7 7. a4 -C78 Ruy Lopez: Rabinovich Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O b5 6. Bb3 d6 7. Ng5 d5 8. exd5 Nd4 9. Re1 Bc5 10. Rxe5+ Kf8 -C79 Ruy Lopez: Morphy Defense, Steinitz Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 -C79 Ruy Lopez: Morphy Defense, Steinitz Deferred 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 6. Bxc6+ bxc6 7. d4 Nxe4 -C79 Ruy Lopez: Steinitz Defense Deferred, Boleslavsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 6. Bxc6+ bxc6 7. d4 Nxe4 8. Re1 f5 9. dxe5 d5 10. Nc3 -C79 Ruy Lopez: Steinitz Defense Deferred, Lipnitsky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O d6 6. Bxc6+ bxc6 7. d4 Bg4 -C80 Ruy Lopez: Morphy Defense, Tartakower Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. Qe2 -C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 -C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 -C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 -C80 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 -C80 Ruy Lopez: Open, Berger Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. a4 Nxd4 9. Nxd4 exd4 10. Nc3 -C80 Ruy Lopez: Open, Bernstein Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 -C80 Ruy Lopez: Open, Bernstein Variation, Luther Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 Bc5 10. Qe1 -C80 Ruy Lopez: Open, Friess Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Nxe5 -C80 Ruy Lopez: Open, Harksen Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. c4 -C80 Ruy Lopez: Open, Karpov Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 Nc5 10. c3 d4 11. Ng5 -C80 Ruy Lopez: Open, Knorre Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. Nc3 -C80 Ruy Lopez: Open, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 -C80 Ruy Lopez: Open, Richter Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. d5 -C80 Ruy Lopez: Open, Riga Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 exd4 -C80 Ruy Lopez: Open, Schlechter Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. a4 Nxd4 -C80 Ruy Lopez: Open, Skipworth Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. Re1 d5 -C80 Ruy Lopez: Open, Zukertort Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Ne7 -C81 Ruy Lopez: Open, Howell Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Qe2 -C81 Ruy Lopez: Open, Howell Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Qe2 Be7 10. c4 -C81 Ruy Lopez: Open, Howell Attack, Ekstrom Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Qe2 Be7 10. Rd1 O-O 11. c4 bxc4 12. Bxc4 Qd7 -C82 Ruy Lopez: Open 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 -C82 Ruy Lopez: Open, Berlin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Nc5 -C82 Ruy Lopez: Open, Dilworth Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Nbd2 O-O 11. Bc2 Nxf2 -C82 Ruy Lopez: Open, Italian Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 -C82 Ruy Lopez: Open, Motzko Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Qd3 -C82 Ruy Lopez: Open, Motzko Attack, Nenarokov Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Qd3 Ne7 -C82 Ruy Lopez: Open, St. Petersburg Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Bc5 10. Nbd2 -C83 Ruy Lopez: Open, Breslau Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 10. Re1 O-O 11. Nd4 Nxe5 -C83 Ruy Lopez: Open, Classical Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 -C83 Ruy Lopez: Open, Classical Defense 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. Nbd2 Nc5 10. c3 Be7 -C83 Ruy Lopez: Open, Classical Defense, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 Be7 7. Re1 b5 8. Bb3 d5 9. dxe5 Be6 10. c3 -C83 Ruy Lopez: Open, Malkin Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 10. Nbd2 O-O 11. Qe2 -C83 Ruy Lopez: Open, Tarrasch Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Nxe4 6. d4 b5 7. Bb3 d5 8. dxe5 Be6 9. c3 Be7 10. Re1 O-O 11. Nd4 Qd7 12. Nxe6 fxe6 13. Rxe4 -C84 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 -C84 Ruy Lopez: Closed, Basque Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d4 exd4 7. e5 Ne4 8. c3 -C84 Ruy Lopez: Closed, Center Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d4 -C84 Ruy Lopez: Closed, Center Attack, Basque Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d4 exd4 7. e5 Ne4 8. c3 dxc3 -C84 Ruy Lopez: Closed, Martinez Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. d3 -C84 Ruy Lopez: Closed, Morphy Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Nc3 -C85 Ruy Lopez: Closed, Delayed Exchange 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Bxc6 -C86 Ruy Lopez: Closed, Worrall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Qe2 -C86 Ruy Lopez: Closed, Worrall Attack, Castling Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Qe2 b5 7. Bb3 O-O -C86 Ruy Lopez: Closed, Worrall Attack, Castling Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. Qe2 Be7 6. O-O b5 7. Bb3 O-O 8. c3 d5 9. d3 -C86 Ruy Lopez: Closed, Worrall Attack, Delayed Castling Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Qe2 b5 7. Bb3 d6 -C87 Ruy Lopez: Closed, Averbakh Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 d6 -C88 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 -C88 Ruy Lopez: Closed 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O -C88 Ruy Lopez: Closed, Alekhine Gambit 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 Na5 9. Bc2 c5 10. d4 Qc7 11. Nbd2 O-O 12. Nf1 Bg4 13. Ne3 Bxf3 14. Qxf3 -C88 Ruy Lopez: Closed, Anti-Marshall 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. a4 -C88 Ruy Lopez: Closed, Balla Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 Na5 9. Bc2 c5 10. d4 Qc7 11. a4 -C88 Ruy Lopez: Closed, Leonhardt Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 Na5 9. Bc2 c5 10. d4 Qc7 11. h3 Nc6 12. d5 Nb8 13. Nbd2 g5 -C88 Ruy Lopez: Closed, Rosen Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. d4 -C88 Ruy Lopez: Closed, Trajkovic Counterattack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 Bb7 -C88 Ruy Lopez: Noah's Ark Trap 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. d4 Nxd4 9. Nxd4 exd4 10. Qxd4 c5 -C89 Ruy Lopez: Marshall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 -C89 Ruy Lopez: Marshall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. a4 Bb7 -C89 Ruy Lopez: Marshall Attack, Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 -C89 Ruy Lopez: Marshall Attack, Main Line, Spassky Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 Bd6 13. Re1 Qh4 14. g3 Qh3 15. Be3 Bg4 16. Qd3 Rae8 17. Nd2 Re6 18. a4 Qh5 -C89 Ruy Lopez: Marshall Attack, Modern Main Line 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. d4 Bd6 13. Re1 Qh4 14. g3 Qh3 -C89 Ruy Lopez: Marshall Attack, Modern Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 -C89 Ruy Lopez: Marshall Attack, Original Marshall Attack 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 Nf6 -C89 Ruy Lopez: Marshall Attack, Re3 Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 Nxd5 10. Nxe5 Nxe5 11. Rxe5 c6 12. Bxd5 cxd5 13. d4 Bd6 14. Re3 -C89 Ruy Lopez: Marshall Attack, Steiner Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. c3 d5 9. exd5 e4 -C90 Ruy Lopez: Closed 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 -C90 Ruy Lopez: Closed, Lutikov Variation 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. Bc2 -C90 Ruy Lopez: Closed, Pilnik Variation 1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 O-O 8. d3 d6 9. c3 -C90 Ruy Lopez: Closed, Suetin Variation 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. a3 -C91 Ruy Lopez: Closed, Bogoljubow Variation 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. d4 Bg4 -C91 Ruy Lopez: Closed, Yates Variation 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. d4 -C91 Ruy Lopez: Closed, Yates Variation, Short Attack 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. d4 Bg4 10. a4 -C92 Ruy Lopez: Closed 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 -C92 Ruy Lopez: Closed, Flohr System 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 Bb7 -C92 Ruy Lopez: Closed, Karpov Variation 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 Nd7 -C92 Ruy Lopez: Closed, Kholmov Variation 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 Be6 -C92 Ruy Lopez: Closed, Smyslov-Breyer-Zaitsev Hybrid 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 Bb7 10. d4 Re8 11. Nbd2 Bf8 12. a3 h6 -C92 Ruy Lopez: Closed, Zaitsev System 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 Re8 -C93 Ruy Lopez: Closed, Smyslov Defense 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 h6 -C94 Ruy Lopez: Closed, Breyer Defense 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 Nb8 -C94 Ruy Lopez: Closed, Breyer Defense, Quiet Variation 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 Nb8 10. d3 -C95 Ruy Lopez: Closed, Breyer 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 Nb8 10. d4 -C95 Ruy Lopez: Closed, Breyer Defense 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 Nb8 10. d4 Nbd7 11. Nbd2 Bb7 12. Bc2 c5 -C95 Ruy Lopez: Closed, Breyer Defense 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 Nb8 10. d4 Nbd7 11. Nh4 -C95 Ruy Lopez: Closed, Breyer Defense, Zaitsev Hybrid 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 Nb8 10. d4 Nbd7 -C96 Ruy Lopez: Closed, Borisenko Variation 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 Nc6 -C96 Ruy Lopez: Closed, Chigorin Defense 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 -C96 Ruy Lopez: Closed, Chigorin Defense 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 -C96 Ruy Lopez: Closed, Chigorin Defense, Gajewski Gambit 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 d5 -C96 Ruy Lopez: Closed, Keres Defense 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 Nd7 -C96 Ruy Lopez: Closed, Rossolimo Defense 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 c6 11. d4 Qc7 -C97 Ruy Lopez: Closed, Chigorin Defense 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 -C97 Ruy Lopez: Closed, Chigorin Defense 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 -C97 Ruy Lopez: Closed, Chigorin, Yugoslav System 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 Bd7 13. Nf1 Rfe8 14. Ne3 g6 -C98 Ruy Lopez: Closed, Chigorin Defense 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 Nc6 -C98 Ruy Lopez: Closed, Chigorin Defense 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 Nc6 13. dxc5 -C99 Ruy Lopez: Closed, Chigorin Defense, Panov System 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 cxd4 13. cxd4 diff --git a/crates/openings/data/d.tsv b/crates/openings/data/d.tsv deleted file mode 100644 index a829bac..0000000 --- a/crates/openings/data/d.tsv +++ /dev/null @@ -1,645 +0,0 @@ -eco name pgn -D00 Amazon Attack 1. d4 d5 2. Qd3 -D00 Blackmar-Diemer Gambit 1. d4 d5 2. e4 -D00 Blackmar-Diemer Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 -D00 Blackmar-Diemer Gambit Accepted 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 -D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 -D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Kloss Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. O-O O-O 8. Kh1 -D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Mad Dog Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. h4 -D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Nimzowitsch Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. Ne5 -D00 Blackmar-Diemer Gambit Accepted: Bogoljubow Defense, Studier Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 g6 6. Bc4 Bg7 7. O-O O-O 8. Qe1 -D00 Blackmar-Diemer Gambit Accepted: Euwe Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 e6 -D00 Blackmar-Diemer Gambit Accepted: Euwe Defense, Duthilleul Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 e6 6. Bd3 -D00 Blackmar-Diemer Gambit Accepted: Euwe Defense, Zilbermints Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 e6 6. Bg5 Be7 7. Bd3 Nc6 8. O-O Nxd4 9. Kh1 -D00 Blackmar-Diemer Gambit Accepted: Gunderam Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bf5 -D00 Blackmar-Diemer Gambit Accepted: Gunderam Defense, Stader Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bf5 6. Ne5 e6 7. g4 Be4 -D00 Blackmar-Diemer Gambit Accepted: Holwell Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Qd6 -D00 Blackmar-Diemer Gambit Accepted: Kaulich Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 c5 -D00 Blackmar-Diemer Gambit Accepted: Pietrowsky Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Nc6 -D00 Blackmar-Diemer Gambit Accepted: Ritter Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 b6 -D00 Blackmar-Diemer Gambit Accepted: Ryder Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Qxf3 -D00 Blackmar-Diemer Gambit Accepted: Schlutter Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Nbd7 -D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 -D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense, Ciesielski Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 6. h3 Bxf3 7. Qxf3 c6 8. Qf2 -D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense, Classical Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 6. h3 Bxf3 7. Qxf3 c6 8. Be3 -D00 Blackmar-Diemer Gambit Accepted: Teichmann Defense, Seidel-Hall Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 Bg4 6. h3 Bxf3 7. Qxf3 c6 8. g4 -D00 Blackmar-Diemer Gambit Accepted: Ziegler Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 exf3 5. Nxf3 c6 -D00 Blackmar-Diemer Gambit Declined: Brombacher Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 c5 -D00 Blackmar-Diemer Gambit Declined: Elbert Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e5 -D00 Blackmar-Diemer Gambit Declined: Gedult Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 a6 -D00 Blackmar-Diemer Gambit Declined: Lamb Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 Nc6 -D00 Blackmar-Diemer Gambit Declined: Langeheinicke Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e3 -D00 Blackmar-Diemer Gambit Declined: O'Kelly Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 c6 -D00 Blackmar-Diemer Gambit Declined: Vienna Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 Bf5 -D00 Blackmar-Diemer Gambit Declined: Weinsbach Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e6 -D00 Blackmar-Diemer Gambit Declined: Weinsbach Defense, Pfrang Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. f3 e6 5. fxe4 -D00 Blackmar-Diemer Gambit: Blackmar Gambit 1. d4 d5 2. e4 dxe4 3. f3 -D00 Blackmar-Diemer Gambit: Diemer-Rosenberg Attack 1. d4 d5 2. e4 dxe4 3. Be3 -D00 Blackmar-Diemer Gambit: Fritz Attack 1. d4 d5 2. e4 dxe4 3. Bc4 -D00 Blackmar-Diemer Gambit: Lemberger Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 e5 -D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Endgame Variation 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. dxe5 -D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Lange Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Nxe4 -D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Rasmussen Attack 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Nge2 -D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Sneiders Attack 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Qh5 -D00 Blackmar-Diemer Gambit: Lemberger Countergambit, Soller Attack 1. d4 d5 2. e4 dxe4 3. Nc3 e5 4. Be3 -D00 Blackmar-Diemer Gambit: Netherlands Variation 1. d4 d5 2. e4 dxe4 3. Nc3 f5 -D00 Blackmar-Diemer Gambit: Rasa-Studier Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Be3 -D00 Blackmar-Diemer Gambit: Reversed Albin Countergambit 1. d4 d5 2. e4 dxe4 3. Nc3 c5 -D00 Blackmar-Diemer Gambit: Zeller Defense 1. d4 d5 2. e4 dxe4 3. Nc3 Bf5 -D00 Blackmar-Diemer Gambit: Zeller Defense, Soller Attack 1. d4 d5 2. e4 dxe4 3. Nc3 Bf5 4. f3 Nf6 5. Bc4 -D00 Blackmar-Diemer Gambit: von Popiel Gambit 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Bg5 -D00 Blackmar-Diemer Gambit: von Popiel Gambit, Zilbermints Variation 1. d4 d5 2. e4 dxe4 3. Nc3 Nf6 4. Bg5 Bf5 5. Bxf6 exf6 6. g4 Bg6 7. Qe2 Bb4 8. Qb5+ -D00 Queen's Pawn Game 1. d4 d5 -D00 Queen's Pawn Game 1. d4 d5 2. e3 -D00 Queen's Pawn Game 1. d4 d5 2. e3 Nf6 -D00 Queen's Pawn Game: Accelerated London System 1. d4 d5 2. Bf4 -D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit 1. d4 d5 2. Bf4 c5 -D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit Accepted 1. d4 d5 2. Bf4 c5 3. dxc5 -D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit, Morris Countergambit 1. d4 d5 2. Bf4 c5 3. e4 -D00 Queen's Pawn Game: Accelerated London System, Steinitz Countergambit, Morris Countergambit Accepted 1. d4 d5 2. Bf4 c5 3. e4 dxe4 -D00 Queen's Pawn Game: Chigorin Variation 1. d4 d5 2. Nc3 -D00 Queen's Pawn Game: Chigorin Variation 1. d4 d5 2. Nc3 e6 -D00 Queen's Pawn Game: Chigorin Variation, Alburt Defense 1. d4 d5 2. Nc3 Bf5 -D00 Queen's Pawn Game: Chigorin Variation, Anti-Veresov 1. d4 d5 2. Nc3 Bg4 -D00 Queen's Pawn Game: Chigorin Variation, Fianchetto Defense 1. d4 g6 2. Nf3 Bg7 3. Nc3 d5 -D00 Queen's Pawn Game: Chigorin Variation, Irish Gambit 1. d4 d5 2. Nc3 c5 -D00 Queen's Pawn Game: Chigorin Variation, Shaviliuk Gambit 1. d4 d5 2. Nc3 e5 -D00 Queen's Pawn Game: Chigorin Variation, Shropshire Defense 1. d4 d5 2. Nc3 h5 -D00 Queen's Pawn Game: Hübsch Gambit 1. d4 Nf6 2. Nc3 d5 3. e4 -D00 Queen's Pawn Game: Levitsky Attack 1. d4 d5 2. Bg5 -D00 Queen's Pawn Game: Levitsky Attack, Welling Variation 1. d4 d5 2. Bg5 Bg4 -D00 Queen's Pawn Game: Mason Attack 1. d4 d5 2. f4 -D00 Queen's Pawn Game: Stonewall Attack 1. d4 d5 2. e3 Nf6 3. Bd3 -D00 Queen's Pawn Game: Zurich Gambit 1. d4 d5 2. g4 -D01 Rapport-Jobava System 1. d4 d5 2. Nc3 Nf6 3. Bf4 -D01 Rapport-Jobava System 1. d4 d5 2. Nc3 Nf6 3. Bf4 e6 -D01 Rapport-Jobava System 1. d4 d5 2. Nc3 Nf6 3. Bf4 g6 -D01 Rapport-Jobava System, with e6 1. d4 d5 2. Nc3 e6 3. Bf4 -D01 Richter-Veresov Attack 1. d4 Nf6 2. Nc3 d5 3. Bg5 -D01 Richter-Veresov Attack 1. d4 Nf6 2. Nc3 d5 3. Bg5 Bf5 -D01 Richter-Veresov Attack: Boyce Defense 1. d4 Nf6 2. Nc3 d5 3. Bg5 Ne4 -D01 Richter-Veresov Attack: Malich Gambit 1. d4 Nf6 2. Nc3 d5 3. Bg5 c5 4. Bxf6 gxf6 5. e4 dxe4 6. d5 -D01 Richter-Veresov Attack: Richter Variation 1. d4 Nf6 2. Nc3 d5 3. Bg5 Bf5 4. f3 -D01 Richter-Veresov Attack: Two Knights System 1. d4 Nf6 2. Nc3 d5 3. Bg5 Nbd7 4. Nf3 -D01 Richter-Veresov Attack: Two Knights System, Grünfeld Defense 1. d4 Nf6 2. Nc3 d5 3. Bg5 Nbd7 4. Nf3 g6 -D01 Richter-Veresov Attack: Veresov Variation 1. d4 Nf6 2. Nc3 d5 3. Bg5 Bf5 4. Bxf6 -D02 London System: Poisoned Pawn Variation 1. d4 Nf6 2. Nf3 d5 3. Bf4 c5 4. e3 Qb6 5. Nc3 -D02 Queen's Gambit Declined: Baltic Defense, Pseudo-Slav 1. d4 d5 2. Nf3 Bf5 3. c4 e6 4. Nc3 c6 -D02 Queen's Pawn Game: Anti-Torre 1. Nf3 d5 2. d4 Bg4 -D02 Queen's Pawn Game: Chandler Gambit 1. d4 d5 2. Nf3 c5 3. g3 cxd4 4. Bg2 -D02 Queen's Pawn Game: Chigorin Variation 1. d4 d5 2. Nf3 Nc6 -D02 Queen's Pawn Game: Krause Variation 1. d4 d5 2. Nf3 c5 -D02 Queen's Pawn Game: Levitsky Attack, Euwe Variation, Modern Line 1. d4 d5 2. Nf3 c6 3. Bg5 h6 4. Bh4 Qb6 -D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 -D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 c5 4. e3 -D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 c5 4. e3 Nc6 5. Nbd2 -D02 Queen's Pawn Game: London System 1. d4 d5 2. Nf3 Nf6 3. Bf4 c5 4. e3 Nc6 5. Nbd2 e6 6. c3 -D02 Queen's Pawn Game: London System, Pterodactyl Variation 1. d4 g6 2. Nf3 Bg7 3. Bf4 c5 4. c3 cxd4 5. cxd4 Qa5+ -D02 Queen's Pawn Game: London System, with e6 1. d4 d5 2. Nf3 e6 3. Bf4 -D02 Queen's Pawn Game: London System, with e6 1. d4 d5 2. Nf3 e6 3. Bf4 Nf6 -D02 Queen's Pawn Game: Symmetrical Variation 1. d4 d5 2. Nf3 Nf6 -D02 Queen's Pawn Game: Symmetrical Variation, Pseudo-Catalan 1. d4 d5 2. Nf3 Nf6 3. g3 -D02 Queen's Pawn Game: Symmetrical Variation, Pseudo-Catalan 1. d4 d5 2. Nf3 Nf6 3. g3 c6 4. Bg2 Bg4 -D02 Queen's Pawn Game: Symmetrical Variation, Pseudo-Catalan 1. Nf3 d5 2. g3 c6 3. Bg2 Nf6 4. O-O Bg4 5. d4 e6 -D02 Queen's Pawn Game: Zilbermints Countergambit 1. d4 d5 2. Nf3 Nf6 3. c4 b5 -D02 Queen's Pawn Game: Zukertort Variation 1. d4 d5 2. Nf3 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. Nbd2 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. Nbd2 Nc6 6. c3 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 6. Nbd2 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 6. Nbd2 Bd6 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nbd7 6. Nbd2 Be7 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nc6 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 c5 5. c3 Nc6 6. Bd3 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. e3 Nbd7 5. Bd3 -D03 Queen's Pawn Game: Torre Attack 1. d4 d5 2. Nf3 Nf6 3. Bg5 e6 4. Nbd2 Be7 5. c3 Nbd7 6. e3 -D03 Queen's Pawn Game: Torre Attack, Gossip Variation 1. d4 d5 2. Nf3 Nf6 3. Bg5 Ne4 -D03 Queen's Pawn Game: Torre Attack, Grünfeld Variation 1. d4 d5 2. Nf3 Nf6 3. Bg5 g6 -D03 Queen's Pawn Game: Torre Attack, Grünfeld Variation 1. d4 d5 2. Nf3 Nf6 3. Bg5 g6 4. e3 -D04 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 -D04 Queen's Pawn Game: Colle System, Anti-Colle 1. d4 d5 2. Nf3 Nf6 3. e3 Bf5 -D04 Queen's Pawn Game: Colle System, Grünfeld Formation 1. d4 d5 2. Nf3 Nf6 3. e3 g6 4. Bd3 Bg7 -D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 -D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 -D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 -D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 c5 5. Bb2 Nc6 -D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 c5 5. Bb2 Nc6 6. Bd3 -D05 Queen's Pawn Game: Colle System 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. b3 c5 5. Bb2 Nc6 6. Nbd2 -D05 Queen's Pawn Game: Colle System 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. b3 Be7 7. Bb2 O-O 8. Nbd2 d5 -D05 Queen's Pawn Game: Colle System, Traditional Colle 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. c3 -D05 Queen's Pawn Game: Zukertort Variation 1. d4 d5 2. Nf3 c5 3. e3 Nf6 4. Nbd2 e6 5. b3 -D05 Rubinstein Opening 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. b3 -D05 Rubinstein Opening: Bogoljubow Defense 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. b3 Nc6 6. O-O Bd6 7. Bb2 O-O -D05 Rubinstein Opening: Classical Defense 1. d4 Nf6 2. Nf3 e6 3. e3 c5 4. Bd3 d5 5. b3 Nc6 6. O-O Be7 7. Bb2 O-O -D05 Rubinstein Opening: Semi-Slav Defense 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 Bd6 5. O-O O-O 6. b3 Nbd7 7. Bb2 -D05 Rubinstein Opening: Semi-Slav Defense 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 Bd6 5. O-O O-O 6. b3 Nbd7 7. Bb2 c6 -D05 Rubinstein Opening: Semi-Slav Defense 1. d4 d5 2. Nf3 Nf6 3. e3 e6 4. Bd3 Bd6 5. O-O O-O 6. b3 Nbd7 7. Bb2 c6 8. Nbd2 -D06 Queen's Gambit 1. d4 d5 2. c4 -D06 Queen's Gambit Declined: Austrian Attack, Salvio Countergambit 1. d4 d5 2. c4 c5 3. dxc5 d4 -D06 Queen's Gambit Declined: Austrian Defense 1. d4 d5 2. c4 c5 -D06 Queen's Gambit Declined: Austrian Defense, Gusev Countergambit 1. d4 d5 2. c4 c5 3. cxd5 Nf6 -D06 Queen's Gambit Declined: Austrian Defense, Haberditz Variation 1. d4 d5 2. c4 c5 3. cxd5 Nf6 4. e4 Nxe4 5. dxc5 Qa5+ -D06 Queen's Gambit Declined: Baltic Defense 1. d4 d5 2. c4 Bf5 -D06 Queen's Gambit Declined: Baltic Defense, Argentinian Gambit 1. d4 d5 2. c4 Bf5 3. cxd5 Bxb1 4. Qa4+ c6 5. dxc6 Nxc6 -D06 Queen's Gambit Declined: Baltic Defense, Pseudo-Chigorin 1. d4 d5 2. c4 Bf5 3. Nc3 e6 4. Nf3 Nc6 -D06 Queen's Gambit Declined: Baltic Defense, Queen Attack 1. d4 d5 2. c4 Bf5 3. Qb3 -D06 Queen's Gambit Declined: Baltic Defense, Queen Attack Deferred 1. d4 d5 2. c4 Bf5 3. Nc3 e6 4. Qb3 -D06 Queen's Gambit Declined: Marshall Defense 1. d4 d5 2. c4 Nf6 -D06 Queen's Gambit Declined: Marshall Defense, Tan Gambit 1. d4 d5 2. c4 Nf6 3. cxd5 c6 -D06 Queen's Gambit Declined: Zilbermints Gambit 1. d4 d5 2. c4 b5 -D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 -D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 -D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 dxc4 -D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 e6 4. Nf3 Nf6 -D07 Queen's Gambit Declined: Chigorin Defense 1. d4 d5 2. c4 Nc6 3. Nc3 e6 4. Nf3 Nf6 5. a3 -D07 Queen's Gambit Declined: Chigorin Defense, Exchange Variation 1. d4 d5 2. c4 Nc6 3. cxd5 Qxd5 -D07 Queen's Gambit Declined: Chigorin Defense, Exchange Variation, Costa's Line 1. d4 d5 2. c4 Nc6 3. cxd5 Qxd5 4. e3 e5 5. Nc3 Bb4 6. Bd2 Bxc3 7. Bxc3 exd4 8. Ne2 -D07 Queen's Gambit Declined: Chigorin Defense, Janowski Variation 1. d4 d5 2. c4 Nc6 3. Nc3 dxc4 4. Nf3 -D07 Queen's Gambit Declined: Chigorin Defense, Lazard Gambit 1. d4 d5 2. c4 Nc6 3. Nf3 e5 -D07 Queen's Gambit Declined: Chigorin Defense, Main Line 1. d4 d5 2. c4 Nc6 3. Nf3 Bg4 -D07 Queen's Gambit Declined: Chigorin Defense, Main Line, Alekhine Variation 1. d4 d5 2. c4 Nc6 3. Nf3 Bg4 4. Qa4 -D07 Queen's Gambit Declined: Chigorin Defense, Modern Gambit 1. d4 d5 2. c4 Nc6 3. Nc3 dxc4 4. Nf3 Nf6 -D07 Queen's Gambit Declined: Chigorin Defense, Tartakower Gambit 1. d4 d5 2. c4 Nc6 3. Nc3 e5 -D08 Queen's Gambit Declined: Albin Countergambit 1. d4 d5 2. c4 e5 -D08 Queen's Gambit Declined: Albin Countergambit, Balogh Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 Qe7 -D08 Queen's Gambit Declined: Albin Countergambit, Janowski Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 f6 -D08 Queen's Gambit Declined: Albin Countergambit, Krenosz Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 Bg4 6. h3 Bxf3 7. Nxf3 Bb4+ 8. Bd2 Qe7 -D08 Queen's Gambit Declined: Albin Countergambit, Lasker Trap 1. d4 d5 2. c4 e5 3. dxe5 d4 4. e3 Bb4+ 5. Bd2 dxe3 -D08 Queen's Gambit Declined: Albin Countergambit, Modern Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. Nbd2 -D08 Queen's Gambit Declined: Albin Countergambit, Normal Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 -D08 Queen's Gambit Declined: Albin Countergambit, Spassky Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. e4 -D08 Queen's Gambit Declined: Albin Countergambit, Tartakower Defense 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 c5 -D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 -D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation, Be6 Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 Be6 -D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation, Bf5 Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 Bf5 -D09 Queen's Gambit Declined: Albin Countergambit, Fianchetto Variation, Bg4 Line 1. d4 d5 2. c4 e5 3. dxe5 d4 4. Nf3 Nc6 5. g3 Bg4 -D10 Slav Defense 1. d4 d5 2. c4 c6 -D10 Slav Defense 1. d4 d5 2. c4 c6 3. Nc3 -D10 Slav Defense 1. d4 d5 2. c4 c6 3. Nc3 dxc4 -D10 Slav Defense: Diemer Gambit 1. d4 d5 2. c4 c6 3. e4 -D10 Slav Defense: Exchange Variation 1. d4 d5 2. c4 c6 3. cxd5 -D10 Slav Defense: Exchange Variation, Boor Attack 1. d4 d5 2. c4 c6 3. cxd5 cxd5 4. Nc3 Nf6 5. f3 -D10 Slav Defense: Slav Gambit, Alekhine Attack 1. d4 d5 2. c4 c6 3. Nc3 dxc4 4. e4 -D10 Slav Defense: Winawer Countergambit 1. d4 d5 2. c4 c6 3. Nc3 e5 -D10 Slav Defense: Winawer Countergambit, Anti-Winawer Gambit 1. d4 d5 2. c4 c6 3. Nc3 e5 4. e4 -D11 Slav Defense: Bonet Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Bg5 -D11 Slav Defense: Breyer Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nbd2 -D11 Slav Defense: Modern Line 1. d4 d5 2. c4 c6 3. Nf3 -D11 Slav Defense: Modern Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. g3 dxc4 5. Bg2 g6 -D11 Slav Defense: Modern Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. g3 Bg4 5. Bg2 e6 6. O-O -D11 Slav Defense: Modern Line 1. d4 d5 2. Nf3 Nf6 3. g3 c6 4. Bg2 Bg4 5. O-O Nbd7 6. c4 -D11 Slav Defense: Quiet Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 -D11 Slav Defense: Quiet Variation, Pin Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bg4 -D12 Slav Defense: Quiet Variation, Amsterdam Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. cxd5 cxd5 6. Nc3 e6 7. Ne5 Nfd7 -D12 Slav Defense: Quiet Variation, Landau Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. cxd5 cxd5 6. Qb3 Qc8 7. Bd2 e6 8. Na3 -D12 Slav Defense: Quiet Variation, Schallopp Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 -D12 Slav Defense: Quiet Variation, Schallopp Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. Nc3 e6 -D13 Slav Defense: Exchange Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. cxd5 cxd5 -D13 Slav Defense: Exchange Variation, Schallopp Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 Bf5 5. cxd5 cxd5 6. Nc3 -D14 Slav Defense: Exchange Variation, Symmetrical Line 1. d4 d5 2. c4 c6 3. cxd5 cxd5 4. Nc3 Nf6 5. Nf3 Nc6 6. Bf4 Bf5 -D14 Slav Defense: Exchange Variation, Trifunovic Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. cxd5 cxd5 5. Nc3 Nc6 6. Bf4 Bf5 7. e3 e6 8. Qb3 Bb4 -D15 Slav Defense: Alekhine Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. e3 -D15 Slav Defense: Chebanenko Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 a6 -D15 Slav Defense: Chebanenko Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 a6 5. e3 Bf5 -D15 Slav Defense: Chebanenko Variation, Advance System 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 a6 5. c5 -D15 Slav Defense: Geller Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. e4 -D15 Slav Defense: Geller Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. e4 b5 6. e5 -D15 Slav Defense: Schlechter Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 g6 -D15 Slav Defense: Süchting Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 Qb6 -D15 Slav Defense: Three Knights Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 -D15 Slav Defense: Two Knights Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 -D16 Slav Defense: Alapin Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 -D16 Slav Defense: Smyslov Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Na6 -D16 Slav Defense: Soultanbeieff Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 e6 -D16 Slav Defense: Steiner Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bg4 -D17 Slav Defense: Czech Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 -D17 Slav Defense: Czech Variation, Bled Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Nh4 -D17 Slav Defense: Czech Variation, Carlsbad Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 Nbd7 7. Nxc4 Qc7 8. g3 e5 -D17 Slav Defense: Czech Variation, Carlsbad Variation, Morozevich Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 Nbd7 7. Nxc4 Qc7 8. g3 e5 9. dxe5 Nxe5 10. Bf4 Nfd7 11. Bg2 g5 -D17 Slav Defense: Czech Variation, Krause Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 -D17 Slav Defense: Czech Variation, Krause Attack, Fazekas Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 Na6 7. e4 -D17 Slav Defense: Czech Variation, Wiesbaden Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 e6 -D17 Slav Defense: Czech Variation, Wiesbaden Variation, Sharp Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. Ne5 e6 7. f3 Bb4 8. e4 -D18 Slav Defense: Czech Variation, Classical System 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 -D18 Slav Defense: Czech Variation, Lasker Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 Na6 -D19 Slav Defense: Czech Variation, Classical System, Main Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O O-O 9. Qe2 -D19 Slav Defense: Czech Variation, Dutch Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O -D19 Slav Defense: Czech Variation, Dutch Variation, Sämisch Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 dxc4 5. a4 Bf5 6. e3 e6 7. Bxc4 Bb4 8. O-O O-O 9. Qe2 Ne4 10. g4 -D20 Queen's Gambit Accepted 1. d4 d5 2. c4 dxc4 -D20 Queen's Gambit Accepted: Accelerated Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Qa4+ -D20 Queen's Gambit Accepted: Central Variation, Alekhine System 1. d4 d5 2. c4 dxc4 3. e4 Nf6 -D20 Queen's Gambit Accepted: Central Variation, Greco Variation 1. d4 d5 2. c4 dxc4 3. e4 b5 -D20 Queen's Gambit Accepted: Central Variation, McDonnell Defense 1. d4 d5 2. c4 dxc4 3. e4 e5 -D20 Queen's Gambit Accepted: Central Variation, McDonnell Defense, Somov Gambit 1. d4 d5 2. c4 dxc4 3. e4 e5 4. Bxc4 -D20 Queen's Gambit Accepted: Central Variation, Modern Defense 1. d4 d5 2. c4 dxc4 3. e4 Nc6 -D20 Queen's Gambit Accepted: Central Variation, Rubinstein Defense 1. d4 d5 2. c4 dxc4 3. e4 c5 -D20 Queen's Gambit Accepted: Central Variation, Rubinstein Defense, Yefimov Gambit 1. d4 d5 2. c4 dxc4 3. e4 c5 4. d5 b5 -D20 Queen's Gambit Accepted: Linares Variation 1. d4 d5 2. c4 dxc4 3. e4 c5 4. d5 Nf6 5. Nc3 b5 -D20 Queen's Gambit Accepted: Old Variation 1. d4 d5 2. c4 dxc4 3. e3 -D20 Queen's Gambit Accepted: Old Variation, Billinger Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. a3 -D20 Queen's Gambit Accepted: Old Variation, Christensen Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. Nf3 -D20 Queen's Gambit Accepted: Old Variation, Korchnoi Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. Kf1 -D20 Queen's Gambit Accepted: Old Variation, Novikov Gambit 1. d4 d5 2. c4 dxc4 3. e3 e5 4. Bxc4 exd4 5. Qb3 Qe7 6. Nd2 -D20 Queen's Gambit Accepted: Saduleto Variation 1. d4 d5 2. c4 dxc4 3. e4 -D20 Queen's Gambit Accepted: Schwartz Defense 1. d4 d5 2. c4 dxc4 3. e4 f5 -D21 Queen's Gambit Accepted: Alekhine Defense, Borisenko-Furman Variation 1. d4 d5 2. c4 dxc4 3. Nf3 a6 4. e4 -D21 Queen's Gambit Accepted: Godes Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nd7 -D21 Queen's Gambit Accepted: Gunsberg Defense 1. d4 d5 2. c4 dxc4 3. Nf3 c5 -D21 Queen's Gambit Accepted: Normal Variation 1. d4 d5 2. c4 dxc4 3. Nf3 -D21 Queen's Gambit Accepted: Rosenthal Variation 1. d4 d5 2. c4 dxc4 3. Nf3 e6 -D21 Queen's Gambit Accepted: Slav Gambit 1. d4 d5 2. c4 dxc4 3. Nf3 b5 -D22 Queen's Gambit Accepted: Alekhine Defense 1. d4 d5 2. c4 dxc4 3. Nf3 a6 -D22 Queen's Gambit Accepted: Alekhine Defense, Alatortsev Variation 1. d4 d5 2. c4 dxc4 3. Nf3 a6 4. e3 Bg4 5. Bxc4 e6 6. d5 -D22 Queen's Gambit Accepted: Alekhine Defense, Haberditz Variation 1. d4 d5 2. c4 dxc4 3. Nf3 a6 4. e3 b5 -D23 Queen's Gambit Accepted 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 -D23 Queen's Gambit Accepted: Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Qa4+ -D23 Queen's Gambit Accepted: Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Qa4+ c6 5. Qxc4 -D23 Queen's Gambit Accepted: Mannheim Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Qa4+ c6 5. Qxc4 e6 6. Qc2 -D24 Queen's Gambit Accepted 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. e4 -D24 Queen's Gambit Accepted 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. Bg5 -D24 Queen's Gambit Accepted: Bogoljubow Defense 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Nc3 a6 5. e4 -D24 Queen's Gambit Accepted: Gunsberg Defense, Prianishenmo Gambit 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Nc3 c5 5. d5 e6 6. e4 exd5 7. e5 -D24 Queen's Gambit Accepted: Showalter Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. Nc3 -D25 Queen's Gambit Accepted: Janowski-Larsen Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 Bg4 -D25 Queen's Gambit Accepted: Normal Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 -D25 Queen's Gambit Accepted: Smyslov Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 g6 -D25 Queen's Gambit Accepted: Winawer Defense 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 Be6 -D26 Queen's Gambit Accepted: Classical Defense 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 -D26 Queen's Gambit Accepted: Classical Defense, Normal Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O -D26 Queen's Gambit Accepted: Classical Defense, Steinitz Variation, Development Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O Nc6 -D26 Queen's Gambit Accepted: Classical Defense, Steinitz Variation, Exchange Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O cxd4 -D26 Queen's Gambit Accepted: Classical, Furman Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. Qe2 a6 7. dxc5 Bxc5 8. O-O Nc6 9. e4 b5 10. e5 -D26 Queen's Gambit Accepted: Normal Variation, .. a6 Sideline 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 a6 6. Nc3 b5 -D26 Queen's Gambit Accepted: Normal Variation, .. a6 Sideline 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 a6 6. Nc3 b5 7. Bb3 Bb7 8. O-O -D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 -D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 Be7 6. O-O a6 -D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 Be7 6. O-O O-O -D26 Queen's Gambit Accepted: Normal Variation, Traditional System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 Be7 6. O-O O-O 7. Nc3 -D27 Queen's Gambit Accepted: Classical Defense, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 -D27 Queen's Gambit Accepted: Classical Defense, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Nc3 -D27 Queen's Gambit Accepted: Classical Defense, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 a6 6. Nc3 b5 7. Bb3 Bb7 8. O-O c5 -D27 Queen's Gambit Accepted: Classical Defense, Rubinstein Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. a4 -D27 Queen's Gambit Accepted: Classical Defense, Rubinstein Variation 1. d4 d5 2. c4 dxc4 3. Nf3 e6 4. e3 Nf6 5. Bxc4 Be7 6. O-O O-O 7. Nc3 a6 8. a4 c5 -D27 Queen's Gambit Accepted: Classical Defense, Russian Gambit 1. d4 d5 2. c4 dxc4 3. e3 Nf6 4. Bxc4 e6 5. Nf3 c5 6. O-O a6 7. e4 -D27 Queen's Gambit Accepted: Furman Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. dxc5 Bxc5 -D28 Queen's Gambit Accepted: Classical Defense, Alekhine System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 -D28 Queen's Gambit Accepted: Classical Defense, Alekhine System 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 -D28 Queen's Gambit Accepted: Classical, Flohr Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Nc6 9. Rd1 c4 10. Bc2 Nb4 11. Nc3 Nxc2 12. Qxc2 Bb7 13. d5 Qc7 -D29 Queen's Gambit Accepted: Classical Defense, Alekhine System, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Bb7 -D29 Queen's Gambit Accepted: Classical Defense, Alekhine System, Main Line 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Bb7 9. Nc3 -D29 Queen's Gambit Accepted: Classical Defense, Alekhine System, Smyslov Variation 1. d4 d5 2. c4 dxc4 3. Nf3 Nf6 4. e3 e6 5. Bxc4 c5 6. O-O a6 7. Qe2 b5 8. Bb3 Bb7 9. Rd1 Nbd7 10. Nc3 Bd6 -D30 Queen's Gambit Declined 1. d4 d5 2. c4 e6 -D30 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 c6 4. Qc2 dxc4 5. Qxc4 Nf6 6. g3 -D30 Queen's Gambit Declined: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 h6 -D30 Queen's Gambit Declined: Capablanca Variation 1. d4 Nf6 2. Nf3 e6 3. c4 d5 4. Bg5 c6 5. Nbd2 Nbd7 6. e3 -D30 Queen's Gambit Declined: Semmering Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 Nbd7 6. Bd3 c5 -D30 Queen's Gambit Declined: Spielmann Variation 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. e3 c6 5. Nbd2 g6 -D30 Queen's Gambit Declined: Stonewall Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 Ne4 6. Bd3 f5 -D30 Queen's Gambit Declined: Tarrasch Defense, Pseudo-Tarrasch 1. d4 d5 2. c4 e6 3. Nf3 c5 -D30 Queen's Gambit Declined: Tarrasch Defense, Pseudo-Tarrasch Bishop Attack 1. d4 d5 2. c4 e6 3. Nf3 c5 4. cxd5 exd5 5. Bg5 -D30 Queen's Gambit Declined: Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 -D30 Queen's Gambit Declined: Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 dxc4 5. Qa4+ c6 6. Qxc4 -D30 Queen's Gambit Declined: Vienna Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Bg5 Bb4+ -D30 Semi-Slav Defense: Quiet Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 -D30 Semi-Slav Defense: Quiet Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. e3 e6 5. Nbd2 Nbd7 -D31 Queen's Gambit Declined: Alapin Variation 1. d4 e6 2. c4 b6 3. Nc3 d5 -D31 Queen's Gambit Declined: Charousek Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 -D31 Queen's Gambit Declined: Charousek Variation, Miladinovic Gambit 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. e4 dxe4 5. f3 -D31 Queen's Gambit Declined: Janowski Variation 1. d4 d5 2. c4 e6 3. Nc3 a6 -D31 Queen's Gambit Declined: Queen's Knight Variation 1. d4 d5 2. c4 e6 3. Nc3 -D31 Queen's Gambit Declined: Semi-Slav, Abrahams Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. a4 Bb4 6. e3 b5 7. Bd2 a5 -D31 Queen's Gambit Declined: Semi-Slav, Junge Variation 1. d4 d5 2. c4 e6 3. Nf3 c6 4. Nc3 dxc4 5. a4 Bb4 6. e3 b5 7. Bd2 Qb6 -D31 Queen's Gambit Declined: Semi-Slav, Koomen Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. e3 b5 6. a4 Bb4 7. Bd2 Qe7 -D31 Semi-Slav Defense: Accelerated Move Order 1. d4 d5 2. c4 e6 3. Nc3 c6 -D31 Semi-Slav Defense: Anti-Noteboom, Stonewall Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 f5 -D31 Semi-Slav Defense: Anti-Noteboom, Stonewall Variation, Portisch Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 f5 5. g4 -D31 Semi-Slav Defense: Gunderam Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. f3 -D31 Semi-Slav Defense: Marshall Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 -D31 Semi-Slav Defense: Marshall Gambit, Forgotten Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. Nxe4 Bb4+ 6. Nc3 -D31 Semi-Slav Defense: Marshall Gambit, Main Line 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. Nxe4 Bb4+ 6. Bd2 -D31 Semi-Slav Defense: Marshall Gambit, Tolush Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e4 dxe4 5. Nxe4 Bb4+ 6. Bd2 Qxd4 7. Bxb4 Qxe4+ 8. Be2 c5 9. Bxc5 Qxg2 -D31 Semi-Slav Defense: Noteboom Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 -D31 Semi-Slav Defense: Noteboom Variation, Abrahams Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. a4 Bb4 6. e3 Bxc3+ 7. bxc3 b5 8. axb5 cxb5 -D31 Semi-Slav Defense: Noteboom Variation, Anti-Noteboom Gambit 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. g3 -D31 Semi-Slav Defense: Noteboom Variation, Anti-Noteboom Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. Bg5 -D31 Semi-Slav Defense: Noteboom Variation, Anti-Noteboom Variation, Belyavsky Line 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 dxc4 5. Bg5 f6 -D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 -D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. Bg5 Be7 -D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. Bg5 Be7 7. Bxe7 Ngxe7 -D32 Queen's Gambit Declined: Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 c5 5. cxd5 exd5 6. Nc3 a6 7. Be2 Nc6 -D32 Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 c5 -D32 Tarrasch Defense: Grünfeld Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. dxc5 d4 7. Na4 b5 -D32 Tarrasch Defense: Marshall Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. e4 -D32 Tarrasch Defense: Schara Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 cxd4 -D32 Tarrasch Defense: Symmetrical Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. e3 Nf6 5. Nf3 Nc6 -D32 Tarrasch Defense: Symmetrical Variation 1. c4 c5 2. Nf3 Nc6 3. Nc3 Nf6 4. e3 e6 5. d4 d5 6. cxd5 exd5 -D32 Tarrasch Defense: Tarrasch Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. dxc5 d4 6. Na4 b5 -D32 Tarrasch Defense: Two Knights Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 -D32 Tarrasch Defense: von Hennig Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 cxd4 5. Qxd4 Nc6 6. Qd1 exd5 7. Qxd5 Be6 -D33 Tarrasch Defense: Dubov Tarrasch 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 cxd4 8. Nxd4 Bc5 -D33 Tarrasch Defense: Prague Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 -D33 Tarrasch Defense: Rubinstein System 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 -D33 Tarrasch Defense: Swedish Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 c4 -D33 Tarrasch Defense: Swedish Variation, Central Break 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 c4 7. e4 -D33 Tarrasch Defense: Wagner Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Bg4 -D34 Queen's Gambit Declined: Tarrasch Defense, Stoltz Variation 1. d4 d5 2. c4 e6 3. Nf3 c5 4. cxd5 exd5 5. g3 Nc6 6. Bg2 Nf6 7. O-O Be7 8. Nc3 O-O 9. Bg5 Be6 10. Rc1 b6 -D34 Tarrasch Defense: Classical Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O -D34 Tarrasch Defense: Classical Variation, Advance Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 c4 -D34 Tarrasch Defense: Classical Variation, Bogoljubow Variation 1. d4 Nf6 2. c4 e6 3. Nc3 c5 4. Nf3 d5 5. cxd5 exd5 6. g3 Nc6 7. Bg2 Be7 8. O-O O-O 9. Bg5 Be6 10. Rc1 c4 -D34 Tarrasch Defense: Classical Variation, Carlsbad Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 -D34 Tarrasch Defense: Classical Variation, Chandler Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 h6 11. Be3 Re8 12. Rc1 Be6 -D34 Tarrasch Defense: Classical Variation, Classical Tarrasch Gambit 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. dxc5 d4 -D34 Tarrasch Defense: Classical Variation, Endgame Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 Be6 -D34 Tarrasch Defense: Classical Variation, Main Line 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 h6 11. Be3 Re8 -D34 Tarrasch Defense: Classical Variation, Petursson Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 Re8 -D34 Tarrasch Defense: Classical Variation, Réti Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. dxc5 Bxc5 10. Na4 -D34 Tarrasch Defense: Classical Variation, Spassky Variation 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 8. O-O O-O 9. Bg5 cxd4 10. Nxd4 h6 11. Be3 Bg4 -D34 Tarrasch Defense: Prague Variation, Main Line 1. d4 d5 2. c4 e6 3. Nc3 c5 4. cxd5 exd5 5. Nf3 Nc6 6. g3 Nf6 7. Bg2 Be7 -D35 Queen's Gambit Declined: Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 -D35 Queen's Gambit Declined: Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bd6 6. cxd5 exd5 -D35 Queen's Gambit Declined: Exchange Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. e3 Be7 5. cxd5 exd5 6. Bd3 O-O 7. Nf3 c6 -D35 Queen's Gambit Declined: Exchange Variation 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. cxd5 exd5 6. Bg5 Be7 7. e3 -D35 Queen's Gambit Declined: Exchange Variation, Carlsen Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 Be7 6. e3 h6 7. Bh4 Bg4 -D35 Queen's Gambit Declined: Exchange Variation, Chameleon Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 Be7 6. e3 O-O 7. Bd3 Nbd7 8. Qc2 Re8 9. Nge2 Nf8 10. O-O-O -D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 -D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 -D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 -D35 Queen's Gambit Declined: Exchange Variation, Positional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 -D35 Queen's Gambit Declined: Exchange Variation, Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bf4 -D35 Queen's Gambit Declined: Harrwitz Attack 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bf4 -D35 Queen's Gambit Declined: Normal Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 Be7 7. e3 Nbd7 8. Bd3 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 Be7 7. e3 O-O 8. Bd3 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. Qc2 Be7 7. e3 O-O 8. Bd3 h6 9. Bh4 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 8. Qc2 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 8. Bd3 O-O 9. Qc2 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. cxd5 exd5 6. Bg5 c6 7. e3 Be7 8. Bd3 Nf8 9. Qc2 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 7. Bd3 Nbd7 8. Nge2 O-O 9. O-O Re8 10. Qc2 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 7. Bd3 Nbd7 8. Nge2 O-O 9. O-O Re8 10. Qc2 Nf8 -D36 Queen's Gambit Declined: Exchange Variation, Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. cxd5 exd5 5. Bg5 c6 6. e3 Be7 7. Bd3 Nbd7 8. Nge2 O-O 9. O-O h6 10. Bh4 Re8 11. Qc2 -D37 Queen's Gambit Declined: Barmen Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 -D37 Queen's Gambit Declined: Harrwitz Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 -D37 Queen's Gambit Declined: Harrwitz Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 c5 7. dxc5 Bxc5 8. Qc2 Nc6 9. Rd1 Qa5 10. a3 -D37 Queen's Gambit Declined: Harrwitz Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 c5 7. dxc5 Bxc5 8. Qc2 Nc6 9. a3 Qa5 10. O-O-O -D37 Queen's Gambit Declined: Harrwitz Attack, Fianchetto Defense 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bf4 O-O 6. e3 b6 -D37 Queen's Gambit Declined: Harrwitz Attack, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 c5 7. dxc5 Bxc5 -D37 Queen's Gambit Declined: Harrwitz Attack, Orthodox Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 Be7 5. Bf4 O-O 6. e3 c6 -D37 Queen's Gambit Declined: Harrwitz Attack, Two Knights Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bf4 O-O 6. e3 Nbd7 -D37 Queen's Gambit Declined: Harrwitz Attack, Two Knights Defense, Blockade Line 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Nf3 Be7 5. Bf4 O-O 6. e3 Nbd7 7. c5 -D37 Queen's Gambit Declined: Knight Defense, Alekhine Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Nbd7 5. Bg5 h6 6. Bh4 dxc4 -D37 Queen's Gambit Declined: Miles Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. Qc2 -D37 Queen's Gambit Declined: Three Knights Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 -D37 Queen's Gambit Declined: Three Knights Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 Be7 5. e3 O-O -D37 Queen's Gambit Declined: Three Knights, Vienna Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 dxc4 -D37 Queen's Gambit Declined: Vienna Variation, Quiet Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 dxc4 5. e3 -D38 Queen's Gambit Declined: Ragozin Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 -D38 Queen's Gambit Declined: Ragozin Defense, Alekhine Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 5. Qa4+ -D38 Queen's Gambit Declined: Westphalian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 5. Bg5 Nbd7 6. e3 c5 -D39 Queen's Gambit Declined: Ragozin Defense, Vienna Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Bb4 5. Bg5 dxc4 -D40 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 -D40 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. e3 Nc6 6. a3 cxd4 7. exd4 Bd6 -D40 Queen's Gambit Declined: Semi-Tarrasch Defense, Levenfish Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. e3 Nc6 6. Bd3 Bd6 7. O-O O-O 8. Qe2 Qe7 9. dxc5 Bxc5 10. e4 -D40 Queen's Gambit Declined: Semi-Tarrasch Defense, Pillsbury Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. Bg5 -D40 Queen's Gambit Declined: Semi-Tarrasch Defense, Symmetrical Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. e3 Nc6 6. Bd3 Bd6 7. O-O O-O -D40 Queen's Gambit Declined: Semi-Tarrasch Defense, with e3 1. d4 d5 2. c4 c5 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nc6 6. Bd3 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. c4 c5 2. Nf3 Nf6 3. Nc3 Nc6 4. g3 d5 5. d4 e6 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. g3 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. g3 Nc6 7. Bg2 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Endgame Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 cxd4 6. Qxd4 exd5 7. e4 dxe4 8. Qxd8+ -D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e4 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Kmoch Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Nf3 c5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 cxd4 8. cxd4 Bb4+ 9. Bd2 Bxd2+ 10. Qxd2 O-O 11. Bb5 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense, Pillsbury Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e3 -D41 Queen's Gambit Declined: Semi-Tarrasch Defense, San Sebastian Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 c5 7. Nf3 cxd4 8. cxd4 Bb4+ 9. Bd2 Qa5 -D42 Queen's Gambit Declined: Semi-Tarrasch Defense, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c5 5. cxd5 Nxd5 6. e3 Nc6 7. Bd3 -D43 Semi-Slav Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 -D43 Semi-Slav Defense: Anti-Moscow Gambit 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 h6 6. Bh4 -D43 Semi-Slav Defense: Hastings Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 h6 6. Bxf6 Qxf6 7. Qb3 -D43 Semi-Slav Defense: Moscow Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 h6 6. Bxf6 Qxf6 -D44 Semi-Slav Defense Accepted 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 -D44 Semi-Slav Defense: Botvinnik Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 -D44 Semi-Slav Defense: Botvinnik Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 -D44 Semi-Slav Defense: Botvinnik Variation, Alatortsev System 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 Nd5 -D44 Semi-Slav Defense: Botvinnik Variation, Ekstrom Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. exf6 gxh4 10. Ne5 -D44 Semi-Slav Defense: Botvinnik Variation, Lilienthal Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 hxg5 10. Bxg5 Nbd7 11. g3 -D44 Semi-Slav Defense: Botvinnik Variation, Szabo Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 c6 5. Bg5 dxc4 6. e4 b5 7. e5 h6 8. Bh4 g5 9. Nxg5 hxg5 10. Bxg5 Nbd7 11. Qf3 -D45 Semi-Slav Defense: Accelerated Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 a6 -D45 Semi-Slav Defense: Main Line 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 -D45 Semi-Slav Defense: Normal Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 -D45 Semi-Slav Defense: Normal Variation 1. Nf3 d5 2. e3 Nf6 3. c4 c6 4. Nc3 e6 5. b3 Bd6 6. Bb2 O-O 7. d4 Nbd7 -D45 Semi-Slav Defense: Normal Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 Nf6 5. e3 Nbd7 6. b3 Bd6 7. Bb2 O-O 8. Be2 -D45 Semi-Slav Defense: Rubinstein System 1. d4 d5 2. c4 e6 3. Nc3 c6 4. Nf3 Nf6 5. e3 Nbd7 6. Ne5 -D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 -D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 -D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 Bb7 -D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. e3 e6 5. Nc3 Nbd7 6. Qc2 Bd6 7. b3 -D45 Semi-Slav Defense: Stoltz Variation 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. e3 e6 5. Nc3 Nbd7 6. Qc2 Bd6 7. b3 O-O 8. Bb2 -D45 Semi-Slav Defense: Stoltz Variation, Center Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Qc2 Bd6 7. e4 -D45 Semi-Slav Defense: Stoltz Variation, Center Variation, Mikhalchishin Line 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Qc2 Bd6 7. e4 dxe4 8. Nxe4 Nxe4 9. Qxe4 e5 10. dxe5 -D45 Semi-Slav Defense: Stoltz Variation, Shabalov Attack 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Qc2 Bd6 7. g4 -D45 Semi-Slav Defense: Stonewall Defense 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. Nc3 e6 5. e3 Ne4 6. Bd3 f5 -D46 Semi-Slav Defense: Bogoljubow Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Be7 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Bd6 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Bd6 7. Qc2 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. b3 Bd6 7. Bb2 O-O 8. Bd3 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 Bb7 8. Bd3 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 Bd6 7. b3 O-O 8. Bb2 Re8 9. Bd3 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 Bd6 7. b3 O-O 8. Bb2 Qe7 9. Bd3 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nf3 e6 4. e3 Nf6 5. Nc3 Bd6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Nbd7 9. O-O O-O 10. Qc2 -D46 Semi-Slav Defense: Chigorin Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bd6 9. O-O Bb7 10. a3 O-O 11. Qc2 -D46 Semi-Slav Defense: Main Line 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 -D46 Semi-Slav Defense: Main Line 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Qc2 b6 7. b3 Bb7 8. Bd3 Be7 9. O-O O-O 10. Bb2 -D46 Semi-Slav Defense: Romih Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 Bb4 -D47 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 -D47 Semi-Slav Defense: Meran Variation, Lundin Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 b4 -D47 Semi-Slav Defense: Meran Variation, Wade Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bb7 -D47 Semi-Slav Defense: Meran Variation, Wade Variation, Kaidanov Gambit 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bb7 9. e4 b4 10. Na4 c5 11. e5 Nd5 12. O-O cxd4 13. Nxd4 -D47 Semi-Slav Defense: Meran Variation, Wade Variation, Larsen Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 Bb7 9. e4 b4 10. Na4 c5 11. e5 Nd5 -D47 Semi-Slav Defense: Semi-Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 -D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 -D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 -D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 a6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 c5 9. O-O Bb7 10. Qe2 -D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 a6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 c5 9. O-O Bb7 10. Qe2 Nbd7 -D48 Semi-Slav Defense: Meran Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 a6 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 c5 9. a4 -D48 Semi-Slav Defense: Meran Variation, Old Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 -D48 Semi-Slav Defense: Meran Variation, Pirc Variation 1. d4 d5 2. c4 e6 3. Nc3 c6 4. e3 Nf6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 b4 -D48 Semi-Slav Defense: Meran Variation, Reynolds' Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. d5 -D49 Semi-Slav Defense: Meran Variation, Blumenfeld Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 -D49 Semi-Slav Defense: Meran Variation, Rabinovich Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Ng4 -D49 Semi-Slav Defense: Meran Variation, Rellstab Attack 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. Nf3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 12. Nxe5 axb5 13. O-O Qd5 14. Qe2 Ba6 15. Bg5 -D49 Semi-Slav Defense: Meran Variation, Sozin Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 -D49 Semi-Slav Defense: Meran Variation, Sozin Variation 1. d4 d5 2. Nf3 Nf6 3. c4 c6 4. Nc3 e6 5. e3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 12. Nxe5 axb5 13. O-O -D49 Semi-Slav Defense: Meran Variation, Stahlberg Variation 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 e6 5. Nf3 Nbd7 6. Bd3 dxc4 7. Bxc4 b5 8. Bd3 a6 9. e4 c5 10. e5 cxd4 11. Nxb5 Nxe5 12. Nxe5 axb5 13. Qf3 -D50 Queen's Gambit Declined: Been-Koomen Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 -D50 Queen's Gambit Declined: Modern Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 -D50 Queen's Gambit Declined: Pseudo-Tarrasch Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. cxd5 -D50 Queen's Gambit Declined: Pseudo-Tarrasch Variation, Canal Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. cxd5 Qb6 -D50 Queen's Gambit Declined: Pseudo-Tarrasch Variation, Primitive Pillsbury Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. Nf3 cxd4 6. Qxd4 -D50 Queen's Gambit Declined: Semi-Tarrasch Defense, Krause Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c5 5. Nf3 cxd4 6. Nxd4 e5 7. Ndb5 a6 8. Qa4 -D51 Queen's Gambit Declined: Alekhine Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. Nf3 c6 6. e4 -D51 Queen's Gambit Declined: Capablanca Variation, Anti-Cambridge Springs Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 6. a3 -D51 Queen's Gambit Declined: Manhattan Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 Bb4 -D51 Queen's Gambit Declined: Modern Variation, Knight Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 -D51 Queen's Gambit Declined: Modern Variation, Knight Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 -D51 Queen's Gambit Declined: Modern Variation, Knight Defense 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 -D51 Queen's Gambit Declined: Rochlin Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. Nf3 c6 6. Rc1 Qa5 7. Bd2 -D52 Queen's Gambit Declined 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 -D52 Queen's Gambit Declined: Cambridge Springs Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 -D52 Queen's Gambit Declined: Cambridge Springs Defense 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. cxd5 -D52 Queen's Gambit Declined: Cambridge Springs Defense, Argentine Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 6. Nf3 Qa5 7. Nd2 Bb4 8. Qc2 O-O 9. Bh4 -D52 Queen's Gambit Declined: Cambridge Springs Defense, Bogoljubow Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. Nd2 Bb4 8. Qc2 -D52 Queen's Gambit Declined: Cambridge Springs Defense, Capablanca Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Nbd7 5. e3 c6 6. Nf3 Qa5 7. Bxf6 -D52 Queen's Gambit Declined: Cambridge Springs Defense, Rubinstein Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. Nd2 dxc4 -D52 Queen's Gambit Declined: Cambridge Springs Defense, Yugoslav Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Nc3 e6 5. Bg5 Nbd7 6. e3 Qa5 7. cxd5 Nxd5 -D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 -D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Nf3 -D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Nf3 c6 6. e3 dxc4 7. Bxc4 -D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. Bg5 Be7 -D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 dxc4 5. Bg5 Be7 6. e4 -D53 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. Bg5 Be7 6. e3 O-O -D53 Queen's Gambit Declined: Lasker Defense 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 Ne4 -D53 Queen's Gambit Declined: Modern Variation, Heral Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. Bxf6 -D53 Queen's Gambit Declined: Uhlmann Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. Rc1 dxc4 -D54 Queen's Gambit Declined: Neo-Orthodox Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 O-O 6. Rc1 -D55 Queen's Gambit Declined: Anti-Tartakower Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 h6 7. Bxf6 -D55 Queen's Gambit Declined: Anti-Tartakower Variation, Petrosian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bxf6 Bxf6 7. e3 O-O 8. Rc1 c6 9. Bd3 Nd7 10. O-O dxc4 11. Bxc4 -D55 Queen's Gambit Declined: Modern Variation, Normal Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 -D55 Queen's Gambit Declined: Neo-Orthodox Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 h6 -D55 Queen's Gambit Declined: Neo-Orthodox Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bh4 O-O 7. e3 -D55 Queen's Gambit Declined: Pillsbury Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 d5 5. cxd5 exd5 6. Bg5 Be7 7. e3 O-O 8. Bd3 Bb7 9. Ne5 -D56 Queen's Gambit Declined 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. Bg5 Be7 6. e3 O-O 7. Rc1 h6 8. Bh4 -D56 Queen's Gambit Declined: Lasker Defense 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 Ne4 -D56 Queen's Gambit Declined: Lasker Defense 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Nc6 5. Bg5 Be7 6. e3 O-O 7. Rc1 h6 8. Bh4 Ne4 -D56 Queen's Gambit Declined: Lasker Defense, Russian Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 h6 7. Bh4 Ne4 8. Bxe7 Qxe7 9. Qc2 Nf6 10. Bd3 dxc4 11. Bxc4 c5 12. O-O Nc6 13. Rfd1 Bd7 -D56 Queen's Gambit Declined: Lasker Defense, Teichmann Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bh4 O-O 7. e3 Ne4 8. Bxe7 Qxe7 9. Qc2 -D57 Queen's Gambit Declined: Lasker Defense, Bernstein Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 h6 6. Bh4 O-O 7. Nf3 Ne4 8. Bxe7 Qxe7 9. cxd5 Nxc3 10. bxc3 exd5 11. Qb3 Qd6 -D57 Queen's Gambit Declined: Lasker Defense, Bernstein Variation, Mar del Plata Gambit 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 h6 7. Bh4 Ne4 8. Bxe7 Qxe7 9. cxd5 Nxc3 10. bxc3 exd5 11. Qb3 Rd8 12. c4 Be6 -D57 Queen's Gambit Declined: Lasker Defense, Main Line 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 Ne4 8. Bxe7 Qxe7 9. cxd5 Nxc3 10. bxc3 -D58 Queen's Gambit Declined: Tartakower Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 -D58 Queen's Gambit Declined: Tartakower Defense, Exchange Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 8. cxd5 exd5 -D59 Queen's Gambit Declined: Tartakower Defense 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 8. cxd5 Nxd5 9. Bxe7 Qxe7 10. Nxd5 exd5 11. Rc1 Be6 -D59 Queen's Gambit Declined: Tartakower Defense, Makogonov Exchange Variation 1. d4 d5 2. c4 e6 3. Nc3 Be7 4. Nf3 Nf6 5. Bg5 h6 6. Bh4 O-O 7. e3 b6 8. cxd5 Nxd5 -D60 Queen's Gambit Declined: Orthodox Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 -D60 Queen's Gambit Declined: Orthodox Defense, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Bd3 -D60 Queen's Gambit Declined: Orthodox Defense, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Bd3 c6 -D60 Queen's Gambit Declined: Orthodox Defense, Rauzer Variation 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Qb3 -D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 -D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c5 -D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c6 -D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c6 8. a3 -D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 a6 8. cxd5 exd5 9. Bd3 Re8 -D61 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Qc2 c6 8. Rd1 a6 -D62 Queen's Gambit Declined: Orthodox Defense, Rubinstein Variation, Flohr Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Qc2 c5 8. cxd5 -D63 Queen's Gambit Declined: Orthodox Defense, Capablanca Variation 1. Nf3 d5 2. d4 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 b6 8. cxd5 exd5 9. Bb5 -D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 -D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. c5 -D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. c5 c6 -D63 Queen's Gambit Declined: Orthodox Defense, Henneberger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. c5 c6 9. Bd3 -D63 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 -D63 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 -D63 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 Nbd7 6. Nf3 O-O 7. Rc1 h6 8. Bh4 c5 -D63 Queen's Gambit Declined: Orthodox Defense, Pillsbury Variation 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 b6 8. cxd5 exd5 9. Bd3 -D63 Queen's Gambit Declined: Orthodox Defense, Swiss, Carlsbad Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 a6 8. cxd5 -D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 Nf6 2. c4 e6 3. Nc3 d5 4. Nf3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. a3 a6 9. Qc2 -D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 -D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 a6 -D64 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. Nf3 d5 2. d4 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 Ne4 -D65 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 a6 9. cxd5 -D65 Queen's Gambit Declined: Orthodox Defense, Rubinstein Attack 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Qc2 a6 9. cxd5 exd5 10. Bd3 -D66 Queen's Gambit Declined: Orthodox Defense, Bd3 Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 -D66 Queen's Gambit Declined: Orthodox Defense, Bd3 Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 h6 9. Bh4 -D66 Queen's Gambit Declined: Orthodox Defense, Fianchetto Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 c6 5. Nf3 Be7 6. e3 Nbd7 7. Rc1 O-O 8. Bd3 dxc4 9. Bxc4 b5 -D67 Queen's Gambit Declined: Orthodox Defense, Alekhine Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. Ne4 -D67 Queen's Gambit Declined: Orthodox Defense, Bd3 Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 -D67 Queen's Gambit Declined: Orthodox Defense, Capablanca System 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 -D67 Queen's Gambit Declined: Orthodox Defense, Janowski Variation 1. d4 d5 2. Nf3 Nf6 3. c4 e6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. h4 -D67 Queen's Gambit Declined: Orthodox Defense, Main Line 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O -D68 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 -D68 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 d5 2. c4 e6 3. Nf3 Nf6 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 13. Qb1 -D68 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. Nc3 Be7 5. Bg5 O-O 6. e3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 13. Qc2 -D69 Queen's Gambit Declined: Orthodox Defense, Classical Variation 1. d4 d5 2. c4 e6 3. Nc3 Nf6 4. Bg5 Be7 5. e3 O-O 6. Nf3 Nbd7 7. Rc1 c6 8. Bd3 dxc4 9. Bxc4 Nd5 10. Bxe7 Qxe7 11. O-O Nxc3 12. Rxc3 e5 13. dxe5 Nxe5 14. Nxe5 Qxe5 -D70 Neo-Grünfeld Defense: Goglidze Attack 1. d4 Nf6 2. c4 g6 3. f3 d5 -D70 Neo-Grünfeld Defense: with Nf3 1. d4 Nf6 2. c4 g6 3. Nf3 d5 -D70 Neo-Grünfeld Defense: with g3 1. d4 Nf6 2. c4 g6 3. g3 d5 -D71 Neo-Grünfeld Defense: Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 d5 5. cxd5 Nxd5 -D71 Neo-Grünfeld Defense: Exchange Variation 1. c4 Nf6 2. g3 g6 3. Bg2 Bg7 4. d4 d5 5. cxd5 Nxd5 6. Nf3 -D72 Neo-Grünfeld Defense: with g3 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. cxd5 Nxd5 6. e4 Nb6 7. Ne2 -D73 Neo-Grünfeld Defense: with g3 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 -D74 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d5 6. cxd5 Nxd5 7. O-O -D75 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. g3 d5 6. cxd5 Nxd5 7. Bg2 c5 8. O-O -D75 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. g3 O-O 5. Bg2 d5 6. cxd5 Nxd5 7. O-O c5 8. dxc5 -D76 Neo-Grünfeld Defense: Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d5 6. cxd5 Nxd5 7. O-O Nb6 -D77 Neo-Grünfeld Defense: Classical Variation 1. d4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O d5 6. c4 -D77 Neo-Grünfeld Defense: Classical Variation, Modern Defense 1. d4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O d5 6. c4 dxc4 -D77 Neo-Grünfeld Defense: Classical Variation, Polgar Variation 1. d4 Nf6 2. Nf3 g6 3. g3 Bg7 4. Bg2 O-O 5. O-O d5 6. c4 Nc6 -D78 Neo-Grünfeld Defense: Classical Variation, Original Defense 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Nc3 Nc6 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Nc3 Nc6 9. Bf4 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Nc3 Ne4 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 c6 6. O-O d5 7. cxd5 cxd5 8. Ne5 Nc6 9. Nc3 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 e6 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 e6 9. Nc3 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 Bf5 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 Bf5 9. Nc3 -D79 Neo-Grünfeld Defense: Ultra-Delayed Exchange Variation 1. d4 Nf6 2. c4 g6 3. g3 d5 4. Bg2 Bg7 5. Nf3 O-O 6. O-O c6 7. cxd5 cxd5 8. Ne5 Ng4 -D80 Grünfeld Defense 1. d4 Nf6 2. c4 g6 3. Nc3 d5 -D80 Grünfeld Defense: Gibbon Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. g4 -D80 Grünfeld Defense: Lundin Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bg5 Ne4 5. Nxe4 dxe4 6. Qd2 c5 -D80 Grünfeld Defense: Lutikov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. f3 -D80 Grünfeld Defense: Lutikov Variation, Murrey Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. f3 c5 5. cxd5 Nxd5 6. Na4 -D80 Grünfeld Defense: Stockholm Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bg5 -D80 Grünfeld Defense: Zaitsev Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. h4 -D81 Grünfeld Defense: Russian Variation, Accelerated Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Qb3 -D82 Grünfeld Defense: Brinckmann Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 -D83 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O -D83 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit, Botvinnik Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. Rc1 c5 7. dxc5 Be6 -D83 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit, Capablanca Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. Rc1 -D83 Grünfeld Defense: Brinckmann Attack, Reshevsky Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. Rc1 O-O 6. e3 c5 7. dxc5 Qa5 -D84 Grünfeld Defense: Brinckmann Attack, Grünfeld Gambit Accepted 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Bf4 Bg7 5. e3 O-O 6. cxd5 Nxd5 7. Nxd5 Qxd5 8. Bxc7 -D85 Grünfeld Defense: Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 -D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Nf3 -D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Nf3 c5 -D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. Nc3 d5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 c5 8. Rb1 -D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation, Kramnik's Line 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. Nc3 d5 5. cxd5 Nxd5 6. e4 Nxc3 7. bxc3 c5 8. h3 -D85 Grünfeld Defense: Exchange Variation, Modern Exchange Variation, Pawn Grab Line 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Nf3 c5 8. Rb1 O-O 9. Be2 Nc6 10. d5 Bxc3+ -D85 Grünfeld Defense: Exchange Variation, Nadanian Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. Na4 -D86 Grünfeld Defense: Exchange Variation, Classical Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 -D86 Grünfeld Defense: Exchange Variation, Larsen Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 Qd7 -D86 Grünfeld Defense: Exchange Variation, Larsen Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 Qd7 9. O-O b6 -D86 Grünfeld Defense: Exchange Variation, Simagin's Improved Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 Nc6 -D86 Grünfeld Defense: Exchange Variation, Simagin's Lesser Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 O-O 8. Ne2 b6 -D87 Grünfeld Defense: Exchange Variation, Seville Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 Nc6 9. Be3 O-O 10. O-O Bg4 11. f3 Na5 12. Bxf7+ -D87 Grünfeld Defense: Exchange Variation, Spassky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 O-O -D88 Grünfeld Defense: Exchange Variation, Spassky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 Nc6 9. Be3 O-O 10. O-O cxd4 11. cxd4 -D89 Grünfeld Defense: Exchange Variation, Sokolsky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 O-O 9. O-O Nc6 10. Be3 Bg4 11. f3 Na5 12. Bd3 cxd4 13. cxd4 Be6 14. d5 -D89 Grünfeld Defense: Exchange Variation, Spassky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. cxd5 Nxd5 5. e4 Nxc3 6. bxc3 Bg7 7. Bc4 c5 8. Ne2 Nc6 9. Be3 O-O 10. O-O Bg4 11. f3 Na5 12. Bd3 cxd4 13. cxd4 Be6 -D90 Grünfeld Defense: Flohr Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qa4+ -D90 Grünfeld Defense: Three Knights Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 -D90 Grünfeld Defense: Three Knights Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 -D91 Grünfeld Defense: Three Knights Variation, Petrosian System 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Bg5 -D92 Grünfeld Defense: Three Knights Variation, Hungarian Attack 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Bf4 -D93 Grünfeld Defense: Three Knights Variation, Hungarian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Bf4 O-O 6. e3 -D94 Grünfeld Defense: Flohr Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 g6 5. Nf3 Bg7 6. Bd3 O-O 7. O-O Bf5 -D94 Grünfeld Defense: Makogonov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. b4 -D94 Grünfeld Defense: Opocensky Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Bd2 -D94 Grünfeld Defense: Smyslov Defense 1. d4 d5 2. c4 c6 3. Nc3 Nf6 4. e3 g6 5. Nf3 Bg7 6. Bd3 O-O 7. O-O Bg4 -D94 Grünfeld Defense: Three Knights Variation, Burille Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 -D94 Grünfeld Defense: Three Knights Variation, Paris Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Bd3 -D95 Grünfeld Defense: Botvinnik Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Qb3 e6 -D95 Grünfeld Defense: Pachman Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. e3 Bg7 5. Qb3 dxc4 6. Bxc4 O-O 7. Nf3 Nbd7 8. Ng5 -D95 Grünfeld Defense: Three Knights Variation, Vienna Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. e3 O-O 6. Qb3 -D96 Grünfeld Defense: Russian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 -D97 Grünfeld Defense: Russian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 -D97 Grünfeld Defense: Russian Variation, Byrne Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Nc6 -D97 Grünfeld Defense: Russian Variation, Hungarian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 a6 -D97 Grünfeld Defense: Russian Variation, Levenfish Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 b6 -D97 Grünfeld Defense: Russian Variation, Prins Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Na6 -D97 Grünfeld Defense: Russian Variation, Szabo Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 c6 -D98 Grünfeld Defense: Russian Variation, Keres Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 8. Be3 Nfd7 9. Be2 Nb6 10. Qd3 Nc6 11. O-O-O -D98 Grünfeld Defense: Russian Variation, Smyslov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 -D99 Grünfeld Defense: Russian Variation, Smyslov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 8. Be3 Nfd7 9. Qb3 -D99 Grünfeld Defense: Russian Variation, Yugoslav Variation 1. d4 Nf6 2. c4 g6 3. Nc3 d5 4. Nf3 Bg7 5. Qb3 dxc4 6. Qxc4 O-O 7. e4 Bg4 8. Be3 Nfd7 9. Qb3 c5 diff --git a/crates/openings/data/e.tsv b/crates/openings/data/e.tsv deleted file mode 100644 index 93a82e1..0000000 --- a/crates/openings/data/e.tsv +++ /dev/null @@ -1,368 +0,0 @@ -eco name pgn -E00 Catalan Opening 1. d4 Nf6 2. c4 e6 3. g3 -E00 Catalan Opening 1. d4 Nf6 2. c4 e6 3. g3 d5 -E00 Catalan Opening: Hungarian Gambit 1. d4 Nf6 2. c4 e6 3. g3 e5 -E00 Indian Defense 1. d4 Nf6 2. c4 e6 3. Qb3 -E00 Indian Defense: Devin Gambit 1. d4 Nf6 2. c4 e6 3. g4 -E00 Indian Defense: Seirawan Attack 1. d4 Nf6 2. c4 e6 3. Bg5 -E01 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 -E01 Catalan Opening: Tarrasch Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 c5 5. Nf3 Nc6 -E02 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 -E03 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Qa4+ Nbd7 6. Qxc4 -E03 Catalan Opening: Open Defense, Alekhine Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Qa4+ Nbd7 6. Qxc4 a6 7. Qc2 -E04 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Nf3 -E04 Catalan Opening: Open Defense 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 c6 5. Bg2 dxc4 -E04 Catalan Opening: Open Defense, Modern Sharp Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Nf3 Nc6 6. Qa4 Bb4+ -E05 Catalan Opening: Open Defense, Classical Line 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 dxc4 5. Nf3 Be7 -E05 Catalan Opening: Open Defense, Classical Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O dxc4 -E06 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 -E06 Catalan Opening: Closed 1. c4 e6 2. Nf3 d5 3. g3 Nf6 4. Bg2 Be7 5. d4 O-O 6. O-O c6 -E06 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Bb4+ 5. Bd2 Be7 6. Bg2 O-O 7. O-O c6 8. Bf4 b6 -E06 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O c6 7. Qc2 b6 8. Nbd2 Bb7 9. e4 Na6 -E07 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 -E07 Catalan Opening: Closed, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Nc3 c6 8. Qd3 -E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 -E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. b3 -E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. b3 b6 -E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O c6 7. Qc2 b6 8. Rd1 Nbd7 9. Bf4 -E08 Catalan Opening: Closed 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. Bf4 b6 9. Nbd2 Bb7 10. e4 -E08 Catalan Opening: Closed, Spassky Gambit 1. d4 Nf6 2. c4 e6 3. g3 Be7 4. Bg2 d5 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. b3 b6 9. Rd1 Bb7 10. Nc3 b5 -E08 Catalan Opening: Closed, Zagoryansky Variation 1. d4 e6 2. c4 Nf6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Rd1 b6 9. a4 -E09 Catalan Opening: Closed Variation, Rabinovich Variation 1. d4 d5 2. c4 c6 3. Nf3 Nf6 4. Qc2 e6 5. Nbd2 Be7 6. g3 Nbd7 7. Bg2 O-O 8. O-O b5 -E09 Catalan Opening: Closed Variation, Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Nbd2 b6 -E09 Catalan Opening: Closed, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Nbd2 -E09 Catalan Opening: Closed, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O c6 7. Qc2 b6 8. Nbd2 Bb7 9. e4 Nbd7 -E09 Catalan Opening: Closed, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Be7 5. Bg2 O-O 6. O-O Nbd7 7. Qc2 c6 8. Bf4 b6 9. Nbd2 Bb7 10. e4 dxe4 11. Nxe4 Nxe4 12. Qxe4 -E09 Catalan Opening: Closed, Sokolsky Variation 1. d4 Nf6 2. c4 e6 3. g3 d5 4. Bg2 Be7 5. Nf3 O-O 6. O-O Nbd7 7. Qc2 c6 8. Nbd2 b6 9. b3 a5 10. Bb2 Ba6 -E10 Blumenfeld Countergambit 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 -E10 Blumenfeld Countergambit Accepted 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 5. dxe6 fxe6 6. cxb5 d5 -E10 Blumenfeld Countergambit: Duz-Khotimirsky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 5. Bg5 -E10 Blumenfeld Countergambit: Spielmann Variation 1. d4 Nf6 2. c4 e6 3. Nf3 c5 4. d5 b5 5. Bg5 exd5 6. cxd5 h6 -E10 Indian Defense: Anti-Nimzo-Indian 1. d4 Nf6 2. c4 e6 3. Nf3 -E10 Indian Defense: Dzindzi-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nf3 a6 -E10 Indian Defense: Döry Indian 1. d4 Nf6 2. c4 e6 3. Nf3 Ne4 -E11 Bogo-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ -E11 Bogo-Indian Defense: Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Bxd2+ -E11 Bogo-Indian Defense: Grünfeld Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nbd2 -E11 Bogo-Indian Defense: Haiti Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Nc6 -E11 Bogo-Indian Defense: Monticelli Trap 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Bxd2+ 7. Qxd2 O-O 8. Nc3 Ne4 9. Qc2 Nxc3 10. Ng5 -E11 Bogo-Indian Defense: New England Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nfd2 -E11 Bogo-Indian Defense: Nimzowitsch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Qe7 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 Be7 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 O-O -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 O-O 7. O-O -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 O-O 7. Qc2 c6 8. O-O -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. b3 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. Rc1 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. Rd1 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. g3 Bb4+ 4. Bd2 Be7 5. Bg2 d5 6. Nf3 Nbd7 7. O-O O-O 8. Qc2 c6 9. Rd1 h6 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Bb4+ 5. Bd2 Be7 6. Bg2 O-O 7. O-O c6 8. Qc2 Nbd7 9. Bf4 b6 10. Nbd2 -E11 Bogo-Indian Defense: Retreat Variation 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. g3 Bb4+ 5. Bd2 Be7 6. Bg2 O-O 7. O-O c6 8. Qc2 Nbd7 9. Bf4 b6 10. Nbd2 Ba6 -E11 Bogo-Indian Defense: Vitolins Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 c5 -E11 Bogo-Indian Defense: Wade-Smyslov Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 a5 -E12 Queen's Indian Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 -E12 Queen's Indian Defense: Kasparov Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 -E12 Queen's Indian Defense: Kasparov Variation, Botvinnik Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb7 5. Bg5 h6 6. Bh4 g5 7. Bg3 Nh5 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Andersson Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 Ne4 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 exd5 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Hedgehog Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 g6 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Kasparov Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. Qc2 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Marco Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 Be7 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Modern Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Petrosian Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. e3 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Polovodin Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb7 5. a3 d5 6. cxd5 Nxd5 7. e4 -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Rashkovsky Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. Qa4+ -E12 Queen's Indian Defense: Kasparov-Petrosian Variation, Romanishin Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Bb7 5. Nc3 d5 6. cxd5 Nxd5 7. Bd2 -E12 Queen's Indian Defense: Miles Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Bf4 -E12 Queen's Indian Defense: Petrosian Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 -E12 Queen's Indian Defense: Petrosian Variation, Farago Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. a3 Ba6 5. Qc2 Bb7 -E13 Queen's Indian Defense: Kasparov Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. Nc3 Bb4 5. Bg5 h6 6. Bh4 Bb7 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. c4 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. c4 Be7 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O c5 6. c4 g6 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. O-O Be7 6. c4 O-O 7. Nc3 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 e6 3. e3 b6 4. Bd3 Bb7 5. Nbd2 c5 6. b3 Be7 7. Bb2 d6 8. O-O O-O 9. c4 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bb7 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bd6 6. Bd3 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 b6 5. Nc3 Bd6 6. Bd3 O-O 7. O-O Bb7 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 Be7 5. Nc3 O-O 6. b3 b6 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 Be7 5. b3 O-O 6. Bd3 b6 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 d5 4. e3 Be7 5. b3 O-O 6. Bb2 b6 7. Nbd2 Bb7 8. Bd3 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nbd2 b6 5. a3 Bxd2+ 6. Qxd2 Bb7 7. e3 -E14 Queen's Indian Defense, with e3 1. Nf3 d5 2. e3 Nf6 3. c4 e6 4. Nc3 Be7 5. d4 O-O 6. b3 b6 7. cxd5 exd5 8. Bb2 Bb7 9. Bd3 -E14 Queen's Indian Defense, with e3 1. d4 Nf6 2. Nf3 d5 3. c4 e6 4. e3 b6 5. b3 Bb7 6. Bd3 Nbd7 7. O-O Bd6 8. Bb2 O-O 9. Nbd2 -E14 Queen's Indian Defense, with e3, Bb4+ Line 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nbd2 b6 5. e3 Bb7 -E14 Queen's Indian Defense: Averbakh Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 c5 6. O-O Be7 7. b3 O-O 8. Bb2 cxd4 9. Nxd4 -E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 -E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 -E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 -E14 Queen's Indian Defense: Spassky System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 d5 -E14 Queen's Indian Defense: Spassky System3 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 c5 -E14 Queen's Indian Defense: Spassky System3 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. e3 Bb7 5. Bd3 c5 6. Nc3 cxd4 7. exd4 Be7 8. O-O d5 9. cxd5 Nxd5 -E15 Queen's Indian Defense: Buerger Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 c5 6. d5 exd5 7. Ng5 -E15 Queen's Indian Defense: Fianchetto Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 -E15 Queen's Indian Defense: Fianchetto Variation, Check Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 Bb4+ -E15 Queen's Indian Defense: Fianchetto Variation, Check Variation, Intermezzo Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 Bb4+ 6. Bd2 Be7 -E15 Queen's Indian Defense: Fianchetto Variation, Check Variation, Modern Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 Bb4+ 6. Bd2 Qe7 -E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 -E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation, Nimzowitsch Attack 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. Qa4 -E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation, Quiet Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. b3 -E15 Queen's Indian Defense: Fianchetto Variation, Nimzowitsch Variation, Timman's Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Ba6 5. Qb3 -E15 Queen's Indian Defense: Fianchetto Variation, Rubinstein Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 c5 6. d5 exd5 7. Nh4 -E15 Queen's Indian Defense: Fianchetto Variation, Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 c5 -E15 Queen's Indian Defense: Fianchetto Variation, Traditional Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 -E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ -E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Nbd2 O-O 7. O-O -E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Nbd2 O-O 7. O-O d5 -E16 Queen's Indian Defense: Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Nbd2 O-O 7. O-O a5 -E16 Queen's Indian Defense: Riumin Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Be7 -E16 Queen's Indian Defense: Riumin Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Be7 7. O-O O-O 8. Nc3 -E16 Queen's Indian Defense: Riumin Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Bb4+ 6. Bd2 Be7 7. O-O O-O 8. Nc3 d5 -E16 Queen's Indian Defense: Yates Variation 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Bd2 a5 5. g3 b6 6. Bg2 Bb7 -E17 Queen's Indian Defense: Anti-Queen's Indian System 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. Nc3 -E17 Queen's Indian Defense: Classical Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O -E17 Queen's Indian Defense: Classical Variation, Polugaevsky Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. d5 exd5 8. Nh4 -E17 Queen's Indian Defense: Classical Variation, Taimanov Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. d5 exd5 8. Nd4 -E17 Queen's Indian Defense: Euwe Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. b3 -E17 Queen's Indian Defense: Fianchetto Variation, Kramnik Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Re1 -E17 Queen's Indian Defense: Opocensky Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. Nc3 Ne4 7. Bd2 -E17 Queen's Indian Defense: Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 -E18 Queen's Indian Defense: Classical Variation, Tiviakov Defense 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 Na6 -E18 Queen's Indian Defense: Classical Variation, Traditional Variation 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 -E18 Queen's Indian Defense: Classical Variation, Traditional Variation, Nimzowitsch Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 d5 -E19 Queen's Indian Defense: Classical Variation, Traditional Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nf3 b6 4. g3 Bb7 5. Bg2 Be7 6. O-O O-O 7. Nc3 Ne4 8. Qc2 Nxc3 9. Qxc3 -E20 Nimzo-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 -E20 Nimzo-Indian Defense: Dilworth Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e4 -E20 Nimzo-Indian Defense: Kmoch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 -E20 Nimzo-Indian Defense: Mikenas Attack 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qd3 -E20 Nimzo-Indian Defense: Romanishin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. g3 -E20 Nimzo-Indian Defense: Romanishin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. g3 O-O 6. Bg2 -E20 Nimzo-Indian Defense: Romanishin Variation, English Hybrid 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. g3 cxd4 6. Nxd4 O-O 7. Bg2 d5 8. cxd5 Nxd5 -E21 Nimzo-Indian Defense: Three Knights Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 -E21 Nimzo-Indian Defense: Three Knights Variation, Euwe Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. d5 Ne4 -E21 Nimzo-Indian Defense: Three Knights Variation, Korchnoi Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 c5 5. d5 -E21 Nimzo-Indian Defense: Three Knights Variation, Shocron Gambit 1. d4 Nf6 2. c4 e6 3. Nf3 Bb4+ 4. Nc3 c5 5. d5 b5 -E22 Nimzo-Indian Defense: Spielmann Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 -E23 Nimzo-Indian Defense: Spielmann Variation, Carlsbad Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 6. Nf3 Ne4 7. Bd2 Nxd2 -E23 Nimzo-Indian Defense: Spielmann Variation, Romanovsky Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 -E23 Nimzo-Indian Defense: Spielmann Variation, Stahlberg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 6. Nf3 Ne4 7. Bd2 Nxc5 -E23 Nimzo-Indian Defense: Spielmann Variation, Stahlberg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qb3 c5 5. dxc5 Nc6 6. Nf3 Ne4 7. Bd2 Nxc5 8. Qc2 f5 9. g3 -E24 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 -E24 Nimzo-Indian Defense: Sämisch Variation, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. e3 O-O 8. cxd5 Nxd5 -E25 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. cxd5 -E25 Nimzo-Indian Defense: Sämisch Variation, Keres Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. cxd5 Nxd5 8. dxc5 -E25 Nimzo-Indian Defense: Sämisch Variation, Romanovsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. f3 d5 5. a3 Bxc3+ 6. bxc3 c5 7. cxd5 Nxd5 8. dxc5 f5 -E26 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 c5 6. e3 -E26 Nimzo-Indian Defense: Sämisch Variation, O'Kelly Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 c5 6. e3 b6 -E27 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. a3 Bxc3+ 5. bxc3 O-O -E28 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. a3 Bxc3+ 6. bxc3 -E29 Nimzo-Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. a3 Bxc3+ 7. bxc3 O-O -E29 Nimzo-Indian Defense: Sämisch Variation, Capablanca Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. a3 Bxc3+ 7. bxc3 O-O 8. Ne2 b6 9. e4 Ne8 -E30 Nimzo-Indian Defense: Leningrad Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Bg5 -E30 Nimzo-Indian Defense: Leningrad Variation, Averbakh Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Bg5 h6 5. Bh4 c5 6. d5 b5 -E31 Nimzo-Indian Defense: Leningrad Variation, Benoni Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Bg5 h6 5. Bh4 c5 6. d5 d6 -E32 Nimzo-Indian Defense: Classical Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 -E32 Nimzo-Indian Defense: Classical Variation, Keres Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. a3 Bxc3+ 6. Qxc3 b6 -E32 Nimzo-Indian Defense: Classical Variation, Vitolins-Adorjan Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. a3 Bxc3+ 6. Qxc3 b5 -E33 Nimzo-Indian Defense: Classical Variation, Milner-Barry Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 d6 -E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 -E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 -E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 O-O 6. e3 -E33 Nimzo-Indian Defense: Classical Variation, Zurich Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 Nc6 5. Nf3 d6 6. Bd2 -E34 Nimzo-Indian Defense: Classical Variation, Belyavsky Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. cxd5 Qxd5 6. Nf3 Qf5 7. Qd1 e5 -E34 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 -E35 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. cxd5 exd5 -E36 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 -E36 Nimzo-Indian Defense: Classical Variation, Noa Variation, Botvinnik Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Nc6 -E36 Nimzo-Indian Defense: Classical Variation, Noa Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 -E36 Nimzo-Indian Defense: Classical Variation, Romanishin Gambit 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 c5 -E37 Nimzo-Indian Defense: Classical Variation, Modern Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 7. Qc2 c5 -E37 Nimzo-Indian Defense: Classical Variation, Noa Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 7. Qc2 -E37 Nimzo-Indian Defense: Classical Variation, Noa Variation, San Remo Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 d5 5. a3 Bxc3+ 6. Qxc3 Ne4 7. Qc2 Nc6 8. e3 e5 -E38 Nimzo-Indian Defense: Classical Variation, Berlin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 -E38 Nimzo-Indian Defense: Classical Variation, Berlin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 O-O 5. e3 d5 6. Nf3 c5 -E38 Nimzo-Indian Defense: Classical Variation, Berlin Variation, Steiner Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 5. dxc5 Bxc3+ -E39 Nimzo-Indian Defense: Classical Variation, Berlin Variation, Macieja System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 5. dxc5 O-O 6. a3 Bxc5 7. Nf3 b6 -E39 Nimzo-Indian Defense: Classical Variation, Berlin Variation, Pirc Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Qc2 c5 5. dxc5 O-O -E40 Nimzo-Indian Defense: Rubinstein System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 -E40 Nimzo-Indian Defense: Rubinstein System, Taimanov Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 Nc6 -E41 Nimzo-Indian Defense: Rubinstein System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 -E41 Nimzo-Indian Defense: Rubinstein System, Hübner Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. Nf3 Bxc3+ 7. bxc3 d6 -E41 Nimzo-Indian Defense: Rubinstein System, Hübner Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Bd3 Nc6 6. Nf3 Bxc3+ 7. bxc3 d6 8. O-O O-O -E42 Nimzo-Indian Defense: Rubinstein System, Rubinstein Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Ne2 -E42 Nimzo-Indian Defense: Rubinstein System, Rubinstein Variation, Main Line 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Ne2 cxd4 6. exd4 O-O 7. a3 -E42 Nimzo-Indian Defense: Rubinstein System, Rubinstein Variation, Sherbakov Attack 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 c5 5. Ne2 cxd4 6. exd4 O-O 7. c5 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O c5 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O c5 8. Na4 cxd4 9. a3 Be7 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 Ne4 5. Qc2 f5 6. Nf3 b6 7. Bd3 Bb7 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 c5 6. Nf3 b6 7. O-O Bb7 8. Na4 Qe7 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 Bxc3+ 5. bxc3 b6 6. e3 Bb7 7. Bd3 O-O 8. O-O -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 b6 5. e3 Ne4 6. Qc2 -E43 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. Nf3 b6 5. e3 Ne4 6. Qc2 Bb7 7. Bd3 Bxc3+ 8. bxc3 f5 9. O-O -E43 Nimzo-Indian Defense: St. Petersburg Variation, with Ne4 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 Ne4 -E44 Nimzo-Indian Defense: St. Petersburg Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 -E44 Nimzo-Indian Defense: St. Petersburg Variation, American Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 Ne4 -E44 Nimzo-Indian Defense: St. Petersburg Variation, Romanishin-Psakhis Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 c5 6. a3 Ba5 -E45 Nimzo-Indian Defense: St. Petersburg Variation, Fischer Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Ne2 Ba6 -E46 Nimzo-Indian Defense: Normal Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O -E46 Nimzo-Indian Defense: Reshevsky Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Ne2 -E46 Nimzo-Indian Defense: Simagin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Ne2 d5 6. a3 Bd6 -E47 Nimzo-Indian Defense: Normal Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 -E48 Nimzo-Indian Defense: Normal Variation, Classical Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 -E48 Nimzo-Indian Defense: Ragozin Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 Nc6 7. O-O -E49 Nimzo-Indian Defense: Normal Variation, Botvinnik System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. a3 Bxc3+ 7. bxc3 -E50 Nimzo-Indian Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 -E51 Nimzo-Indian Defense: Normal Variation, Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 -E51 Nimzo-Indian Defense: Normal Variation, Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 6. Bd2 Nc6 -E51 Nimzo-Indian Defense: Normal Variation, Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 6. Bd2 Nc6 7. a3 -E51 Nimzo-Indian Defense: Normal Variation, Sämisch Deferred 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Nf3 d5 6. a3 -E51 Nimzo-Indian Defense: Ragozin Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 Nc6 7. O-O dxc4 -E52 Nimzo-Indian Defense: Normal Variation, Schlechter Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 b6 -E52 Nimzo-Indian Defense: Normal Variation, Schlechter Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 b6 5. Bd3 Bb7 6. Nf3 O-O 7. O-O d5 -E53 Nimzo-Indian Defense: Normal Variation, Gligoric System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 -E53 Nimzo-Indian Defense: Normal Variation, Gligoric System 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nbd7 -E53 Nimzo-Indian Defense: Normal Variation, Gligoric System, Keres Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O b6 -E54 Nimzo-Indian Defense: Normal Variation, Gligoric System, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 -E54 Nimzo-Indian Defense: Normal Variation, Gligoric System, Exchange Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 cxd4 9. exd4 -E54 Nimzo-Indian Defense: Normal Variation, Gligoric System, Smyslov Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 Qe7 -E55 Nimzo-Indian Defense: Normal Variation, Gligoric System, Bronstein Variation 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O dxc4 8. Bxc4 Nbd7 -E56 Nimzo-Indian Defense: Normal Variation, Gligoric System, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 -E57 Nimzo-Indian Defense: Normal Variation, Gligoric System, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 8. a3 dxc4 9. Bxc4 cxd4 -E58 Nimzo-Indian Defense: Normal Variation, Bernstein Defense, Exchange Line 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 8. a3 Bxc3 9. bxc3 -E59 Nimzo-Indian Defense: Normal Variation, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. Nf3 c5 7. O-O Nc6 8. a3 Bxc3 9. bxc3 dxc4 10. Bxc4 -E59 Nimzo-Indian Defense: Normal Variation, Bernstein Defense 1. d4 Nf6 2. c4 e6 3. Nc3 Bb4 4. e3 O-O 5. Bd3 d5 6. a3 Bxc3+ 7. bxc3 dxc4 8. Bxc4 c5 9. Nf3 Nc6 10. O-O Qc7 11. Qc2 -E60 Grünfeld Defense: Counterthrust Variation 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 d5 -E60 Indian Defense: Anti-Grünfeld, Adorjan Gambit 1. d4 Nf6 2. c4 g6 3. d5 b5 -E60 Indian Defense: Anti-Grünfeld, Advance Variation 1. d4 Nf6 2. c4 g6 3. d5 -E60 Indian Defense: Anti-Grünfeld, Alekhine Variation 1. d4 Nf6 2. c4 g6 3. f3 -E60 Indian Defense: Anti-Grünfeld, Alekhine Variation, Leko Gambit 1. d4 Nf6 2. c4 g6 3. f3 e5 -E60 Indian Defense: Anti-Grünfeld, Basman-Williams Attack 1. d4 Nf6 2. c4 g6 3. h4 -E60 Indian Defense: West Indian Defense 1. d4 Nf6 2. c4 g6 -E60 King's Indian Defense: Fianchetto Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 -E60 King's Indian Defense: Fianchetto Variation, Immediate Fianchetto 1. d4 Nf6 2. c4 g6 3. g3 -E60 King's Indian Defense: Normal Variation, King's Knight Variation 1. d4 Nf6 2. Nf3 g6 3. c4 -E60 King's Indian Defense: Santasiere Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. b4 -E60 King's Indian Defense: Semi-Classical Variation, Benoni Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 c6 -E60 King's Indian Defense: Semi-Classical Variation, Hollywood Variation 1. d4 Nf6 2. Nf3 g6 3. c4 Bg7 4. Nc3 O-O 5. e3 d6 6. Be2 Nc6 -E60 Queen's Pawn, Mengarini Attack 1. d4 Nf6 2. c4 g6 3. Qc2 -E61 King's Indian Defense 1. d4 Nf6 2. c4 g6 3. Nc3 -E61 King's Indian Defense: Fianchetto Variation, Benjamin Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 c6 7. O-O Qb6 -E61 King's Indian Defense: Semi-Classical Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 -E61 King's Indian Defense: Semi-Classical Variation, Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 Nbd7 7. O-O e5 8. dxe5 dxe5 -E61 King's Indian Defense: Semi-Classical Variation, Queenside Storm Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 O-O 5. e3 d6 6. Be2 Nbd7 7. O-O e5 8. b4 -E61 King's Indian Defense: Smyslov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. Bg5 -E62 King's Indian Defense: Fianchetto Variation, Carlsbad Variation 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 Nc6 -E62 King's Indian Defense: Fianchetto Variation, Delayed Fianchetto 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 -E62 King's Indian Defense: Fianchetto Variation, Kavalek Defense 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c6 7. Nc3 Qa5 -E62 King's Indian Defense: Fianchetto Variation, Larsen Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 c6 7. O-O Bf5 -E62 King's Indian Defense: Fianchetto Variation, Lesser Simagin (Spassky) 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 Nc6 7. O-O Bf5 -E62 King's Indian Defense: Fianchetto Variation, Simagin Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 Nc6 7. O-O Bg4 -E62 King's Indian Defense: Fianchetto Variation, Uhlmann-Szabo System 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 e5 -E63 King's Indian Defense: Fianchetto Variation, Panno Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 -E63 King's Indian Defense: Fianchetto Variation, Panno Variation, Blockade Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 8. d5 Na5 9. Nd2 c5 10. Qc2 e5 -E63 King's Indian Defense: Fianchetto Variation, Panno Variation, Donner Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 8. d5 Na5 9. Nd2 c5 10. Qc2 Rb8 11. b3 b5 12. Bb2 bxc4 13. bxc4 Bh6 -E63 King's Indian Defense: Fianchetto Variation, Panno Variation, Korchnoi Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nc6 7. Nc3 a6 8. h3 Rb8 9. Be3 b5 10. Nd2 -E64 King's Indian Defense: Fianchetto Variation, Double Fianchetto Attack 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 d6 5. Bg2 O-O 6. O-O Nbd7 7. Nc3 e5 8. b3 -E64 King's Indian Defense: Fianchetto Variation, Hungarian Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 d6 5. Bg2 O-O 6. O-O Nbd7 7. Nc3 a6 -E64 King's Indian Defense: Fianchetto Variation, Pterodactyl Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 c5 5. Bg2 Qa5+ -E64 King's Indian Defense: Fianchetto Variation, Yugoslav System 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 d6 5. Bg2 O-O 6. O-O c5 -E64 King's Indian Defense: Fianchetto Variation, Yugoslav Variation, Rare Line 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 c5 -E65 King's Indian Defense: Fianchetto Variation, Yugoslav Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c5 7. Nc3 -E65 King's Indian Defense: Fianchetto Variation, Yugoslav Variation, Exchange Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c5 7. Nc3 Nc6 8. dxc5 dxc5 -E66 King's Indian Defense: Fianchetto Variation, Yugoslav Variation, Advance Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O c5 7. Nc3 Nc6 8. d5 -E67 King's Indian Defense: Fianchetto Variation, Classical Fianchetto 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nbd7 7. Nc3 e5 -E67 King's Indian Defense: Fianchetto Variation, Debrecen Defense 1. d4 Nf6 2. c4 g6 3. g3 Bg7 4. Bg2 O-O 5. Nc3 d6 6. Nf3 Nbd7 -E68 King's Indian Defense: Fianchetto Variation, Classical Variation 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nbd7 7. Nc3 e5 8. e4 -E68 King's Indian Defense: Fianchetto Variation, Long Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. Nf3 d6 5. g3 O-O 6. Bg2 Nbd7 7. O-O e5 8. e4 Re8 9. h3 exd4 10. Nxd4 Nc5 11. Re1 a5 -E69 King's Indian Defense: Fianchetto Variation, Classical Main Line 1. d4 Nf6 2. c4 g6 3. Nf3 Bg7 4. g3 O-O 5. Bg2 d6 6. O-O Nbd7 7. Nc3 e5 8. e4 c6 9. h3 -E70 King's Indian Defense: Accelerated Averbakh Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Bg5 -E70 King's Indian Defense: Kramer Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nge2 -E70 King's Indian Defense: Normal Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 -E70 King's Indian Defense: Normal Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 -E71 King's Indian Defense: Karpov System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. h3 O-O 6. Be3 -E71 King's Indian Defense: Makogonov Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. h3 -E72 King's Indian Defense: Normal Variation, Deferred Fianchetto 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. g3 -E72 King's Indian Defense: Pomar System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. g3 O-O 6. Bg2 e5 7. Nge2 -E73 King's Indian Defense: Averbakh Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 -E73 King's Indian Defense: Averbakh Variation, Flexible Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 h6 -E73 King's Indian Defense: Averbakh Variation, Geller Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Nbd7 -E73 King's Indian Defense: Averbakh Variation, Modern Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Na6 -E73 King's Indian Defense: Averbakh Variation, Modern Defense, Burgess Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Na6 7. Qd2 c6 -E73 King's Indian Defense: Averbakh Variation, Nc6 Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 Nc6 -E73 King's Indian Defense: Averbakh Variation, Spanish Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 a6 -E73 King's Indian Defense: Normal Variation, Standard Development 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 -E73 King's Indian Defense: Semi-Averbakh System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Be3 -E74 King's Indian Defense: Averbakh Variation, Benoni Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 -E74 King's Indian Defense: Averbakh Variation, Benoni Defense, Advance Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 7. d5 -E74 King's Indian Defense: Averbakh Variation, Benoni Defense, Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 7. dxc5 -E75 King's Indian Defense: Averbakh Variation, Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. Bg5 c5 7. d5 e6 -E76 King's Indian Defense: Four Pawns Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 -E76 King's Indian Defense: Four Pawns Attack, Dynamic Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. d5 -E76 King's Indian Defense: Four Pawns Attack, Modern Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 Na6 -E77 King's Indian Defense: Four Pawns Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Be2 O-O 6. f4 -E77 King's Indian Defense: Four Pawns Attack, Florentine Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. d5 e6 8. Be2 exd5 9. e5 -E77 King's Indian Defense: Four Pawns Attack, Normal Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. d5 e6 8. Be2 -E77 King's Indian Defense: Six Pawns Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Be2 c5 7. d5 e6 8. dxe6 fxe6 9. g4 Nc6 10. h4 -E78 King's Indian Defense: Four Pawns Attack, Fluid Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. Be2 -E79 King's Indian Defense: Four Pawns Attack, Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f4 O-O 6. Nf3 c5 7. Be2 cxd4 8. Nxd4 Nc6 9. Be3 -E80 King's Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 -E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 -E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 h6 8. Bf4 -E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 e6 8. Qd2 exd5 9. Nxd5 -E81 King's Indian Defense: Steiner Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Bg5 c5 7. d5 e6 8. Qd2 h6 9. Bxh6 -E81 King's Indian Defense: Sämisch Variation, Bobotsov-Korchnoi-Petrosian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Nge2 -E81 King's Indian Defense: Sämisch Variation, Byrne Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 c6 7. Bd3 a6 -E81 King's Indian Defense: Sämisch Variation, Normal Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O -E81 King's Indian Defense: Sämisch Variation, Sämisch Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 c5 -E81 King's Indian Defense: Sämisch Variation, Sämisch Gambit Accepted 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 c5 7. dxc5 dxc5 8. Qxd8 Rxd8 9. Bxc5 -E82 King's Indian Defense: Sämisch Variation, Double Fianchetto 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 b6 -E83 King's Indian Defense: Sämisch Variation, Panno Formation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 7. Nge2 a6 -E83 King's Indian Defense: Sämisch Variation, Ruban Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 7. Nge2 Rb8 -E83 King's Indian Defense: Sämisch Variation, Yates Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 -E84 King's Indian Defense: Sämisch Variation, Panno Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 Nc6 7. Nge2 a6 8. Qd2 Rb8 -E85 King's Indian Defense: Sämisch Variation, Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 -E86 King's Indian Defense: Sämisch Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. Nge2 c6 -E87 King's Indian Defense: Sämisch Variation, Bronstein Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 Nh5 8. Qd2 Qh4+ 9. g3 Nxg3 10. Qf2 Nxf1 11. Qxh4 Nxe3 12. Ke2 -E87 King's Indian Defense: Sämisch Variation, Closed Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 -E87 King's Indian Defense: Sämisch Variation, Orthodox Variation, Bronstein Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 Nh5 8. Qd2 Qh4+ 9. g3 Nxg3 10. Qf2 Nxf1 11. Qxh4 Nxe3 12. Ke2 Nxc4 -E88 King's Indian Defense: Sämisch Variation, Closed Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. d5 c6 -E89 King's Indian Defense: Sämisch Variation, Closed Variation, Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. f3 O-O 6. Be3 e5 7. Nge2 c6 8. d5 cxd5 -E90 King's Indian Defense: Larsen Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be3 -E90 King's Indian Defense: Normal Variation, Rare Defenses 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 -E90 King's Indian Defense: Zinnowitz Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Bg5 -E91 King's Indian Defense: Kazakh Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 Na6 -E91 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 -E92 King's Indian Defense: Exchange Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. dxe5 -E92 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 -E92 King's Indian Defense: Orthodox Variation, Gligoric-Taimanov System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. Be3 -E92 King's Indian Defense: Petrosian Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 -E92 King's Indian Defense: Petrosian Variation, Stein Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 a5 -E93 King's Indian Defense: Petrosian Variation, Keres Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 Nbd7 8. Bg5 h6 9. Bh4 g5 10. Bg3 Nh5 11. h4 -E93 King's Indian Defense: Petrosian Variation, Normal Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. d5 Nbd7 -E94 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O -E94 King's Indian Defense: Orthodox Variation, Donner Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O c6 -E94 King's Indian Defense: Orthodox Variation, Glek Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Na6 -E94 King's Indian Defense: Orthodox Variation, Positional Defense 1. d4 Nf6 2. c4 d6 3. Nc3 Nbd7 4. e4 e5 5. Nf3 g6 6. Be2 Bg7 7. O-O O-O -E94 King's Indian Defense: Orthodox Variation, Positional Defense, Closed Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 Nbd7 7. O-O e5 8. d5 -E94 King's Indian Defense: Orthodox Variation, Ukrainian Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O a5 -E95 King's Indian Defense: Orthodox Variation 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nbd7 8. Re1 -E96 King's Indian Defense: Orthodox Variation, Positional Defense, Main Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nbd7 8. Re1 c6 9. Bf1 a5 -E97 King's Indian Defense: Orthodox Variation, Aronin-Taimanov Defense 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 -E97 King's Indian Defense: Orthodox Variation, Bayonet Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. b4 -E97 King's Indian Defense: Orthodox Variation, Bayonet Attack, Sokolov's Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. b4 Nh5 10. Re1 -E97 King's Indian Defense: Orthodox Variation, Bayonet Attack, Yepishin's Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. b4 Nh5 10. Qc2 -E97 King's Indian Defense: Orthodox Variation, Korchnoi Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Bd2 -E97 King's Indian Defense: Orthodox Variation, Modern System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Nd2 -E98 King's Indian Defense: Orthodox Variation, Classical System 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 -E98 King's Indian Defense: Orthodox Variation, Classical System, Kozul Gambit 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. Be3 f5 11. f3 f4 12. Bf2 g5 13. Rc1 Ng6 14. c5 -E98 King's Indian Defense: Orthodox Variation, Classical System, Neo-Classical Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. Be3 -E99 King's Indian Defense: Orthodox Variation, Classical System, Benko Attack 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. f3 f5 11. g4 -E99 King's Indian Defense: Orthodox Variation, Classical System, Traditional Line 1. d4 Nf6 2. c4 g6 3. Nc3 Bg7 4. e4 d6 5. Nf3 O-O 6. Be2 e5 7. O-O Nc6 8. d5 Ne7 9. Ne1 Nd7 10. f3 f5 diff --git a/crates/openings/src/lib.rs b/crates/openings/src/lib.rs deleted file mode 100644 index 5c719eb..0000000 --- a/crates/openings/src/lib.rs +++ /dev/null @@ -1,273 +0,0 @@ -//! Opening names from the Lichess `chess-openings` table: a position's ECO code and -//! name, looked up by the position itself, so a line reaching a named position by -//! another move order gets its name too. A line is named by its deepest named -//! position, as the table's README says ("go back through the moves until a named -//! position is found"). -//! -//! The five TSV files in `data/` (`eco`, `name`, `pgn`) were downloaded unmodified from -//! at revision -//! `f06a50d5c7c140e50b068049fa31d289e2c3d347` (2026-10-27), on 2026-10-28; the data set is -//! in the public domain (CC0 1.0). Their SHA-256 sums are in `THIRD_PARTY_NOTICES.md`. -//! The table is parsed on first use (3 865 lines, a fraction of a second). -//! -//! Every position on the way to a named one is a book position: the game review gives -//! no !! or ! for a move into it (chess.com's «book» moves). - -use std::collections::{HashMap, HashSet}; -use std::sync::OnceLock; - -use serde::{Deserialize, Serialize}; -use shakmaty::san::SanPlus; -use shakmaty::zobrist::Zobrist64; -use shakmaty::{Chess, EnPassantMode, Position}; - -const FILES: [&str; 5] = [ - include_str!("../data/a.tsv"), - include_str!("../data/b.tsv"), - include_str!("../data/c.tsv"), - include_str!("../data/d.tsv"), - include_str!("../data/e.tsv"), -]; - -/// A named opening position of the table. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Opening { - /// "B30". - pub eco: String, - /// "Sicilian Defense: Nyezhmetdinov-Rossolimo Attack". - pub name: String, - /// The table's moves to the position, in SAN ("1. e4 c5 2. Nf3 Nc6 3. Bb5"). - pub line: String, - /// Half-moves of `line`. - pub plies: u8, -} - -impl Opening { - /// The part of the name before the colon ("Sicilian Defense"). - pub fn family(&self) -> &str { - self.name.split(':').next().unwrap_or(&self.name).trim() - } - - /// The part after the colon ("Nyezhmetdinov-Rossolimo Attack"), if any. - pub fn variation(&self) -> Option<&str> { - self.name.split_once(':').map(|(_, v)| v.trim()) - } -} - -/// The key of a position for the table: the same as `chess_import::position::key` -/// (Zobrist, en passant only when legal), so keys from either side match. -pub fn key(pos: &Chess) -> u64 { - pos.zobrist_hash::(EnPassantMode::Legal).0 -} - -struct Table { - entries: Vec, - /// Position key → entry. A position reached by two lines of the table keeps the - /// first (the files are in ECO order). - by_key: HashMap, - /// Every position of every line after its first move, named or not. - book: HashSet, -} - -fn table() -> &'static Table { - static TABLE: OnceLock = OnceLock::new(); - TABLE.get_or_init(|| { - let mut t = Table { - entries: Vec::with_capacity(4000), - by_key: HashMap::with_capacity(4000), - book: HashSet::with_capacity(20000), - }; - for text in FILES { - for line in text.lines().skip(1) { - let mut cols = line.split('\t'); - let (Some(eco), Some(name), Some(pgn)) = (cols.next(), cols.next(), cols.next()) - else { - continue; - }; - let Some((pos, plies)) = play(pgn, &mut t.book) else { - continue; - }; - let k = key(&pos); - if t.by_key.contains_key(&k) { - continue; - } - t.by_key.insert(k, t.entries.len()); - t.entries.push(Opening { - eco: eco.to_owned(), - name: name.to_owned(), - line: pgn.to_owned(), - plies, - }); - } - } - t - }) -} - -/// Plays a table line ("1. e4 c5 2. Nf3"), adding its positions to `book`; `None` if a -/// move is not legal. -fn play(pgn: &str, book: &mut HashSet) -> Option<(Chess, u8)> { - let mut pos = Chess::default(); - let mut plies = 0u8; - for tok in pgn.split_whitespace() { - if tok.ends_with('.') { - continue; - } - let m = tok.parse::().ok()?.san.to_move(&pos).ok()?; - pos.play_unchecked(m); - book.insert(key(&pos)); - plies = plies.checked_add(1)?; - } - Some((pos, plies)) -} - -/// Number of named positions. -pub fn count() -> usize { - table().entries.len() -} - -/// The entry of a named position (by its [`key`]). -pub fn by_position(k: u64) -> Option { - table().by_key.get(&k).copied() -} - -/// The position (by its [`key`]) lies on a line of the table: a move into it is a book -/// move. -pub fn in_book(k: u64) -> bool { - table().book.contains(&k) -} - -/// Entry `id` (from [`by_position`] or [`deepest`]). -pub fn get(id: usize) -> &'static Opening { - &table().entries[id] -} - -/// The name of a line (the positions `keys`, in order): its deepest named position, -/// its index in `keys` and its entry — but a deeper position whose name is only a -/// more general one ("Sicilian Defense" after 3.d4 in the "Modern Variations") does -/// not take the name back: the most precise name met stays. -pub fn deepest(keys: &[u64]) -> Option<(usize, usize)> { - let mut out: Option<(usize, usize)> = None; - for (i, k) in keys.iter().enumerate() { - if let Some(id) = by_position(*k) - && out.is_none_or(|(_, cur)| !more_general(id, cur)) - { - out = Some((i, id)); - } - } - out -} - -/// Entry `a`'s name is a more general form of entry `b`'s ("Sicilian Defense" of -/// "Sicilian Defense: Modern Variations"; "…: Najdorf Variation" of "…: Najdorf -/// Variation, English Attack"). -pub fn more_general(a: usize, b: usize) -> bool { - is_prefix_name(&get(a).name, &get(b).name) -} - -/// `general` names a family or a variation `precise` is part of. -pub fn is_prefix_name(general: &str, precise: &str) -> bool { - precise.len() > general.len() - && precise.starts_with(general) - && matches!(precise[general.len()..].chars().next(), Some(':' | ',')) -} - -#[cfg(test)] -mod tests { - use super::*; - use shakmaty::san::San; - - fn keys(moves: &[&str]) -> Vec { - let mut pos = Chess::default(); - let mut out = vec![key(&pos)]; - for s in moves { - let m = s.parse::().unwrap().to_move(&pos).unwrap(); - pos.play_unchecked(m); - out.push(key(&pos)); - } - out - } - - #[test] - fn the_table_loads() { - // 3 865 lines; a few positions are reached by two lines of the table. - assert!(count() > 3800, "{}", count()); - let start = by_position(key(&Chess::default())); - assert!(start.is_none(), "the start position has no name"); - } - - #[test] - fn the_deepest_named_position_names_the_line_whatever_the_move_order() { - // 1.e4 c5 2.Nf3 Nc6 3.Bb5: the Rossolimo; 3...g6 is named too, 4.O-O is not. - let k = keys(&["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O"]); - let (at, id) = deepest(&k).expect("named"); - let o = get(id); - assert_eq!(o.eco, "B31"); - assert!( - o.name - .starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), - "{}", - o.name - ); - assert_eq!(at, 6, "the position after 3...g6"); - assert_eq!(o.family(), "Sicilian Defense"); - assert!( - o.variation() - .is_some_and(|v| v.starts_with("Nyezhmetdinov")) - ); - assert_eq!(o.plies, 6); - assert_eq!(o.line, "1. e4 c5 2. Nf3 Nc6 3. Bb5 g6"); - // A transposition: 1.Nf3 d5 2.d4 reaches the table's 1.d4 d5 2.Nf3. - let a = deepest(&keys(&["Nf3", "d5", "d4"])).expect("named"); - let b = deepest(&keys(&["d4", "d5", "Nf3"])).expect("named"); - assert_eq!(a.1, b.1); - assert_eq!(get(a.1).line, "1. d4 d5 2. Nf3"); - // A family without a variation. - let o = get(deepest(&keys(&["e4", "c5"])).expect("named").1); - assert_eq!(o.name, "Sicilian Defense"); - assert_eq!(o.variation(), None); - // Nothing before the first move. - assert_eq!(deepest(&keys(&[])), None); - // A deeper position with a more general name keeps the precise one: the - // table names 1.e4 c5 2.Nf3 d6 3.d4 just «Sicilian Defense». - let line = keys(&["e4", "c5", "Nf3", "d6", "d4"]); - let after_d4 = by_position(line[5]).map(|id| get(id).name.clone()); - assert_eq!(after_d4.as_deref(), Some("Sicilian Defense")); - let (at, id) = deepest(&line).expect("named"); - assert_eq!( - (at, get(id).name.as_str()), - (4, "Sicilian Defense: Modern Variations") - ); - assert!(is_prefix_name( - "Sicilian Defense", - "Sicilian Defense: Modern Variations" - )); - assert!(is_prefix_name("A: B", "A: B, C")); - assert!(!is_prefix_name("Sicilian Defense", "Sicilian Defense")); - assert!(!is_prefix_name("English", "English Opening")); - } - - #[test] - fn book_positions_and_keys() { - // The Greco Gambit lines pass 6...Bb4+; 7...d5 is on none of them. - let k = keys(&[ - "e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+", - ]); - assert!( - in_book(k[12]) && by_position(k[12]).is_none(), - "on the way, not named" - ); - let more = keys(&[ - "e4", "e5", "Nf3", "Nc6", "Bc4", "Bc5", "c3", "Nf6", "d4", "exd4", "cxd4", "Bb4+", - "Nc3", "d5", - ]); - assert!(in_book(more[13]) && !in_book(more[14])); - assert!( - !in_book(k[0]), - "the start position is no move into the book" - ); - // The key is the one the rest of the program uses. - let pos = Chess::default(); - assert_eq!(key(&pos), chess_import::position::key(&pos)); - } -} diff --git a/crates/play/Cargo.toml b/crates/play/Cargo.toml index 9764312..4713787 100644 --- a/crates/play/Cargo.toml +++ b/crates/play/Cargo.toml @@ -13,7 +13,3 @@ chess-core.workspace = true shakmaty.workspace = true uci.workspace = true getrandom = "0.3" - -# Random numbers in a browser (crypto.getRandomValues). -[target.'cfg(target_family = "wasm")'.dependencies] -getrandom = { version = "0.3", features = ["wasm_js"] } diff --git a/crates/play/src/lib.rs b/crates/play/src/lib.rs index dd344bb..f4b9f39 100644 --- a/crates/play/src/lib.rs +++ b/crates/play/src/lib.rs @@ -1,16 +1,12 @@ //! A game against the computer (docs/design/play-mode.md, android-play.md §31): how it //! ends, how long the opponent "thinks", its resignation judged by an engine, and Rodent -//! (`rodent`). Shared by the desktop and the Android apps; nothing here draws. The -//! engines that play or judge run as processes, each driven from a thread: a browser -//! cannot start them. +//! (`rodent`). Shared by the desktop and the Android apps; nothing here draws. pub mod rodent; mod rodent4_files; -use std::sync::mpsc::{Receiver, Sender}; -use std::time::Duration; -#[cfg(not(target_family = "wasm"))] -use std::{sync::mpsc::channel, time::Instant}; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::time::{Duration, Instant}; use shakmaty::zobrist::Zobrist64; use shakmaty::{Chess, Color, EnPassantMode, Position}; @@ -263,8 +259,6 @@ pub struct Judge { impl Judge { /// The engine of `config` with `options` set (an Android Stockfish: its `EvalFile`); /// `wake` is called when an answer comes (the app draws again). - /// (A process driven from a thread: not in a browser.) - #[cfg(not(target_family = "wasm"))] pub fn start( config: uci::EngineConfig, options: Vec<(String, String)>, diff --git a/crates/play/src/rodent.rs b/crates/play/src/rodent.rs index 9341a24..6865562 100644 --- a/crates/play/src/rodent.rs +++ b/crates/play/src/rodent.rs @@ -4,15 +4,11 @@ //! thread of its own. Shared by the desktop and the Android apps; nothing here draws. use std::collections::BTreeMap; -use std::time::Duration; -#[cfg(not(target_family = "wasm"))] -use std::{ - sync::mpsc::{Sender, channel}, - sync::{Arc, Condvar, Mutex, MutexGuard}, - time::Instant, -}; +use std::sync::mpsc::{Sender, channel}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; -use shakmaty::Move; +use shakmaty::{Chess, Move}; pub use crate::rodent4_files::{COMMIT, FILES, PERSONALITY_BOOKS}; @@ -560,19 +556,17 @@ pub enum Failure { Search(String), } -#[cfg(not(target_family = "wasm"))] /// A move asked for: the game for the engine, its position now, the pause. struct Request { generation: u64, pos: uci::EnginePosition, - now: shakmaty::Chess, + now: Chess, pause: Duration, } /// Rodent's move, or none (no legal move it gave), and the time it took. pub type Answer = (Option, Duration); -#[cfg(not(target_family = "wasm"))] #[derive(Default)] struct State { /// The request asked last (bumped by `forget`). @@ -583,14 +577,12 @@ struct State { failure: Option, } -#[cfg(not(target_family = "wasm"))] #[derive(Default)] struct Shared { state: Mutex, changed: Condvar, } -#[cfg(not(target_family = "wasm"))] impl Shared { fn lock(&self) -> MutexGuard<'_, State> { self.state.lock().unwrap_or_else(|e| e.into_inner()) @@ -602,7 +594,6 @@ impl Shared { } } -#[cfg(not(target_family = "wasm"))] /// Rodent playing one game, in its own thread (a UCI child process): it thinks during /// the pause a move should take (a game's own clock is not its business: Maia's pause /// rule paces it) and answers after it. Only the newest request counts; the answer to @@ -612,7 +603,6 @@ pub struct RodentPlayer { shared: Arc, } -#[cfg(not(target_family = "wasm"))] impl RodentPlayer { /// The engine of `config` (its folder, or its home in the environment: Android) /// playing `style_id` at `uci_elo` (none: full strength), with its opening book when @@ -719,7 +709,7 @@ impl RodentPlayer { /// Asks for a move in `now` (`pos`: the game to it for the engine) after `pause`; /// the request's number, for [`RodentPlayer::wait`]. - pub fn ask(&self, pos: uci::EnginePosition, now: shakmaty::Chess, pause: Duration) -> u64 { + pub fn ask(&self, pos: uci::EnginePosition, now: Chess, pause: Duration) -> u64 { let generation = { let mut s = self.shared.lock(); s.generation += 1; @@ -852,14 +842,14 @@ mod tests { let start = || uci::EnginePosition::startpos(Vec::::new()); let pause = Duration::from_millis(400); // Asked twice: the first is passed over, the second answered with a legal move. - let first = player.ask(start(), shakmaty::Chess::default(), pause); - let second = player.ask(start(), shakmaty::Chess::default(), pause); + let first = player.ask(start(), Chess::default(), pause); + let second = player.ask(start(), Chess::default(), pause); assert_eq!(player.wait(first), None); let (m, spent) = player.wait(second).expect("an answer"); assert!(m.is_some(), "{:?}", player.failure()); assert!(spent >= pause); // A request forgotten ends its wait at once. - let third = player.ask(start(), shakmaty::Chess::default(), pause); + let third = player.ask(start(), Chess::default(), pause); player.forget(); assert_eq!(player.wait(third), None); assert_eq!(player.failure(), None); diff --git a/crates/prep/Cargo.toml b/crates/prep/Cargo.toml deleted file mode 100644 index 9ada134..0000000 --- a/crates/prep/Cargo.toml +++ /dev/null @@ -1,18 +0,0 @@ -[package] -name = "prep" -description = "Preparing against an opponent: a player's opening repertoire in a database, the names of the openings, and the opening errors the engine finds (the desktop and Android apps share it)" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[dependencies] -chess-core.workspace = true -chess-import.workspace = true -game-review.workspace = true -uci.workspace = true -chess-openings.workspace = true -serde.workspace = true -serde_json.workspace = true diff --git a/crates/prep/examples/prep_report.rs b/crates/prep/examples/prep_report.rs deleted file mode 100644 index 04debab..0000000 --- a/crates/prep/examples/prep_report.rs +++ /dev/null @@ -1,337 +0,0 @@ -//! A check of the `prep` crate on a real database, printed as text: the candidates -//! for a name, the repertoire tree of each colour, the opening table, and, with an -//! engine, the opening errors by opening and the repeated ones. -//! -//! ```text -//! cargo run --release -p prep --example prep_report -- "" \ -//! [--engine ] [--plies 20] [--processes N] [--min-games 3] [--no-cache] -//! ``` -//! -//! The report and the evaluations are cached under `~/.cache/chesspenguin/prep/` -//! like the application would (`--no-cache` ignores and does not write it). - -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::time::Instant; - -use prep::{ColorReport, Options, Player, PositionCache, PrepReport, Side, Tree}; - -struct Args { - db: PathBuf, - player: String, - engine: Option, - plies: usize, - processes: usize, - min_games: u32, - cache: bool, -} - -fn args() -> Args { - let mut it = std::env::args().skip(1); - let mut a = Args { - db: PathBuf::new(), - player: String::new(), - engine: None, - plies: prep::DEFAULT_PLIES, - processes: game_review::processes(game_review::MAX_PROCESSES), - min_games: 3, - cache: true, - }; - let mut positional = Vec::new(); - while let Some(arg) = it.next() { - match arg.as_str() { - "--engine" => a.engine = it.next().map(PathBuf::from), - "--plies" => a.plies = it.next().and_then(|v| v.parse().ok()).unwrap_or(a.plies), - "--processes" => { - a.processes = it - .next() - .and_then(|v| v.parse().ok()) - .unwrap_or(a.processes) - } - "--min-games" => { - a.min_games = it - .next() - .and_then(|v| v.parse().ok()) - .unwrap_or(a.min_games) - } - "--no-cache" => a.cache = false, - _ => positional.push(arg), - } - } - if positional.len() < 2 { - eprintln!("usage: prep_report [--engine path] …"); - std::process::exit(2); - } - a.db = PathBuf::from(&positional[0]); - a.player = positional[1].clone(); - a -} - -fn open(path: &Path) -> chess_import::Database { - let t = Instant::now(); - let opened = - chess_import::open(path, &mut |_| {}, &AtomicBool::new(false)).unwrap_or_else(|e| { - eprintln!("cannot open {}: {e}", path.display()); - std::process::exit(1); - }); - println!( - "[open] {} ({}): {} games, {:.2} s", - path.display(), - opened.format.label(), - opened.db.games(), - t.elapsed().as_secs_f64() - ); - opened.db -} - -fn tally(t: &prep::Tally) -> String { - format!("{} (+{} ={} -{})", t.games, t.wins, t.draws, t.losses) -} - -fn print_tree(tree: &Tree, node: usize, depth: usize, min_games: u32, report: &PrepReport) { - for &c in &tree.nodes[node].children { - let n = &tree.nodes[c as usize]; - if n.tally.games < min_games { - continue; - } - let name = match (n.named, n.opening) { - (true, Some(o)) => format!(" — {}", report.openings[o].name), - _ => String::new(), - }; - println!( - "{:indent$}{} {} {}{}{}{}", - "", - prep::move_label(usize::from(n.ply) - 1, &n.san), - tally(&n.tally), - n.last_date, - n.average_elo() - .map_or(String::new(), |e| format!(" Elo {e}")), - if n.transposition { " ↔" } else { "" }, - name, - indent = depth * 2 - ); - if depth < 8 { - print_tree(tree, c as usize, depth + 1, min_games, report); - } - } -} - -fn print_color(report: &PrepReport, cr: &ColorReport, min_games: u32) { - let colour = if cr.white { "White" } else { "Black" }; - println!( - "\n==== {colour}: {} games, {} tree nodes ====", - cr.games.len(), - cr.tree.nodes.len() - ); - println!("-- repertoire (nodes with at least {min_games} games; ↔ = transposition)"); - print_tree(&cr.tree, 0, 0, min_games, report); - println!("-- openings"); - for f in &cr.families { - println!( - "{} {}{}", - tally(&f.tally), - if f.name.is_empty() { - "(unnamed)" - } else { - &f.name - }, - errors_text(&f.errors) - ); - for v in &f.variations { - let (name, line, eco) = match v.opening { - Some(o) => { - let o = &report.openings[o]; - (o.name.as_str(), o.line.as_str(), o.eco.as_str()) - } - None => ("(unnamed)", "", ""), - }; - let games: Vec = v - .games - .iter() - .map(|&g| format!("#{}", report.games[g as usize].index + 1)) - .collect(); - println!( - " {} {eco} {name} [{line}]{} — {}", - tally(&v.tally), - errors_text(&v.errors), - games.join(" ") - ); - } - } - if !cr.errors.is_empty() || report.engine.is_some() { - println!( - "-- errors: {} inaccuracies, {} mistakes, {} blunders in the player's moves", - cr.counts.inaccuracies, cr.counts.mistakes, cr.counts.blunders - ); - for e in &cr.errors { - let g = &report.games[e.game as usize]; - println!( - " #{} {} {:?}: {} (best {}) {} → {} [{}]", - g.index + 1, - g.move_label(e.ply as usize), - e.judgement, - e.san, - e.best_san, - e.before.format(), - e.after.format(), - e.opening.map_or("", |o| report.openings[o].name.as_str()) - ); - } - println!("-- repeated errors (same position, same move, two or more games)"); - for r in &cr.repeated { - let games: Vec = r - .games - .iter() - .map(|&g| format!("#{}", report.games[g as usize].index + 1)) - .collect(); - println!( - " {}× {} {:?} (best {}) {} — {} [{}]", - r.times(), - prep::move_label(r.ply as usize, &r.san), - r.judgement, - r.best_san, - tally(&r.tally), - games.join(" "), - r.opening.map_or("", |o| report.openings[o].name.as_str()) - ); - } - } -} - -fn errors_text(e: &prep::ErrorCounts) -> String { - if e.total() == 0 { - String::new() - } else { - format!(" ?!{} ?{} ??{}", e.inaccuracies, e.mistakes, e.blunders) - } -} - -fn main() { - let a = args(); - let db = open(&a.db); - let never = AtomicBool::new(false); - let cache_dir = a.cache.then(|| { - std::env::home_dir() - .unwrap_or_else(|| PathBuf::from(".")) - .join(".cache/chesspenguin/prep") - }); - - let t = Instant::now(); - let (list, total) = prep::candidates(&db, &a.player, 10); - println!( - "[candidates] {total} for «{}», {:.1} ms:", - a.player, - t.elapsed().as_secs_f64() * 1000.0 - ); - for c in &list { - println!(" {} · {} games (id {})", c.name, c.games, c.id); - } - let Some(chosen) = list - .iter() - .find(|c| c.name.to_lowercase() == a.player.to_lowercase()) - .or(list.first()) - else { - eprintln!("no such player"); - std::process::exit(1); - }; - let player = Player::new([chosen.id]); - println!("[player] {} ({} games)", chosen.name, chosen.games); - - let options = Options { - plies: a.plies, - side: Side::Any, - period: prep::Period::All, - }; - let t = Instant::now(); - let cached = cache_dir - .as_deref() - .and_then(|d| PrepReport::load(d, &db, &player, &options)); - let mut report = match cached { - Some(r) => { - println!( - "[report] from the cache, {:.1} ms", - t.elapsed().as_secs_f64() * 1000.0 - ); - r - } - None => { - let progress = AtomicUsize::new(0); - let r = prep::build(&db, &player, &options, &progress, &never).expect("not cancelled"); - println!( - "[report] built: {} games ({} skipped), {} plies, {} openings named, {:.1} ms", - r.games.len(), - r.skipped, - r.plies, - r.openings.len(), - t.elapsed().as_secs_f64() * 1000.0 - ); - r - } - }; - - for cr in [&report.white, &report.black] { - print_color(&report, cr, a.min_games); - } - - if let Some(engine) = &a.engine { - let mut cache = cache_dir - .as_deref() - .map(PositionCache::load) - .unwrap_or_default(); - println!( - "\n[engine] {} positions, {} distinct; {} cached evaluations on disk", - report.games.iter().map(|g| g.keys.len()).sum::(), - report.distinct_positions(), - cache.len() - ); - let settings = game_review::JobSettings::new(a.processes, None); - let t = Instant::now(); - let mut last_shown = Instant::now(); - let mut first = true; - let result = prep::analyse( - &mut report, - &mut cache, - cache_dir.as_deref(), - uci::EngineConfig::new(engine.clone()), - &settings, - &never, - &mut |p| { - if first { - println!( - "[engine] {} positions to evaluate, {} engine processes", - p.total, a.processes - ); - first = false; - } - if last_shown.elapsed().as_secs_f64() >= 5.0 { - println!( - " {} / {} ({:.0} s, nps {})", - p.done, - p.total, - t.elapsed().as_secs_f64(), - p.nps - ); - last_shown = Instant::now(); - } - }, - ); - match result { - Ok(()) => println!( - "[engine] done in {:.1} s; {} evaluations in the cache; engine {}", - t.elapsed().as_secs_f64(), - cache.len(), - report.engine.as_ref().map_or("?", |e| e.name.as_str()) - ), - Err(e) => println!("[engine] failed: {e:?}"), - } - for cr in [&report.white, &report.black] { - print_color(&report, cr, u32::MAX); - } - } - if let Some(dir) = &cache_dir { - match report.save(dir) { - Ok(()) => println!("[cache] report saved in {}", dir.display()), - Err(e) => println!("[cache] not saved: {e}"), - } - } -} diff --git a/crates/prep/src/errors.rs b/crates/prep/src/errors.rs deleted file mode 100644 index b213644..0000000 --- a/crates/prep/src/errors.rs +++ /dev/null @@ -1,550 +0,0 @@ -//! Opening errors found by the engine: every distinct position of the first plies of -//! the player's games is evaluated once (the games repeat their openings, so about -//! half the positions are shared), and the player's moves are judged from the -//! evaluations before and after them with the rules of the game analysis. The same -//! error in several games — the same position and the same move — is what matters -//! most for preparation, so those are listed on their own. -//! -//! Evaluations are kept per position in a cache file shared by every report: another -//! player of the same database, or the same player later, is judged from the cache. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; - -use chess_core::shakmaty::san::SanPlus; -use chess_core::shakmaty::uci::UciMove; -use chess_core::shakmaty::{Chess, Position}; -use game_review::{Eval, Judgement, PosEval, SEARCH_VERSION}; -use serde::{Deserialize, Serialize}; - -use crate::games::{GameInfo, Tally}; - -/// Nodes of an evaluation that needs no engine (checkmate, stalemate): better than any -/// search. -pub const EXACT: u64 = u64::MAX; - -/// The engine's result for one position. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct PositionEval { - /// Nodes of the search ([`EXACT`] for a position without legal moves). - pub nodes: u64, - pub eval: Eval, - /// The engine's line in UCI; the first move is its best move. - pub pv: Vec, - pub depth: u32, -} - -impl PositionEval { - pub fn from_engine(nodes: u64, e: &PosEval) -> PositionEval { - PositionEval { - nodes, - eval: e.eval, - pv: e.pv.iter().take(8).cloned().collect(), - depth: e.depth, - } - } - - pub fn best(&self) -> Option<&str> { - self.pv.first().map(String::as_str) - } -} - -/// How many inaccuracies, mistakes and blunders. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ErrorCounts { - pub inaccuracies: u32, - pub mistakes: u32, - pub blunders: u32, -} - -impl ErrorCounts { - pub fn add(&mut self, j: Judgement) { - match j { - Judgement::Inaccuracy => self.inaccuracies += 1, - Judgement::Mistake => self.mistakes += 1, - Judgement::Blunder => self.blunders += 1, - Judgement::Great | Judgement::Brilliant => {} - } - } - - pub fn total(&self) -> u32 { - self.inaccuracies + self.mistakes + self.blunders - } -} - -/// A move of the player judged an inaccuracy, a mistake or a blunder. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct OpeningError { - /// Index into [`crate::PrepReport::games`]. - pub game: u32, - /// The move's place in the line (0-based; see [`GameInfo::move_label`]). - pub ply: u32, - /// The position before the move. - pub key: u64, - pub uci: String, - pub san: String, - /// The engine's move instead. - pub best_uci: String, - pub best_san: String, - pub judgement: Judgement, - pub before: Eval, - pub after: Eval, - /// The game's opening ([`crate::PrepReport::openings`]). - pub opening: Option, -} - -/// The same error in several games: the same position and the same move. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct RepeatedError { - pub key: u64, - pub ply: u32, - pub uci: String, - pub san: String, - pub best_san: String, - pub judgement: Judgement, - /// The games (indices into [`crate::PrepReport::games`]), in order. - pub games: Vec, - /// How those games ended. - pub tally: Tally, - /// The opening of the first of them. - pub opening: Option, -} - -impl RepeatedError { - pub fn times(&self) -> u32 { - self.games.len() as u32 - } -} - -/// Judges the player's moves in `games[g]` for `g` in `which` from `evals`: the -/// move is not the engine's best, and the evaluations before and after it say it -/// lost enough (the rules of the game analysis, [`game_review::judge`]). Only the -/// prefix before the opponent's first inaccuracy/mistake/blunder is eligible. -/// A missing opponent evaluation or best move stops the prefix too: later player -/// errors are not published until those preceding moves have been checked. -pub fn judge_games( - games: &[GameInfo], - which: &[u32], - evals: &HashMap, -) -> Vec { - let mut out = Vec::new(); - for &g in which { - let game = &games[g as usize]; - let mut pos = Chess::default(); - for (i, uci) in game.ucis.iter().enumerate() { - let Some(m) = uci - .parse::() - .ok() - .and_then(|u| u.to_move(&pos).ok()) - else { - break; - }; - let evaluated = evals - .get(&game.keys[i]) - .and_then(|before| Some((before, evals.get(&game.keys[i + 1])?, before.best()?))); - if !game.player_moves_at(i) && evaluated.is_none() { - break; - } - if let Some((before, after, best)) = evaluated - && best != uci - && let Some(judgement) = game_review::judge(before.eval, after.eval, pos.turn()) - { - if !game.player_moves_at(i) { - break; - } - let best_san = best - .parse::() - .ok() - .and_then(|u| u.to_move(&pos).ok()) - .map(|bm| SanPlus::from_move(pos.clone(), bm).to_string()) - .unwrap_or_else(|| best.to_owned()); - out.push(OpeningError { - game: g, - ply: i as u32, - key: game.keys[i], - uci: uci.clone(), - san: game.sans.get(i).cloned().unwrap_or_default(), - best_uci: best.to_owned(), - best_san, - judgement, - before: before.eval, - after: after.eval, - opening: game.opening, - }); - } - pos.play_unchecked(m); - } - } - out -} - -/// The errors made in two or more games (same position, same move), most repeated -/// first, then the worst first. -pub fn repeated(errors: &[OpeningError], games: &[GameInfo]) -> Vec { - let mut groups: HashMap<(u64, &str), Vec<&OpeningError>> = HashMap::new(); - for e in errors { - groups.entry((e.key, e.uci.as_str())).or_default().push(e); - } - let mut out: Vec = groups - .into_values() - .filter(|g| g.len() >= 2) - .map(|g| { - let first = g[0]; - let mut tally = Tally::default(); - let mut list: Vec = g.iter().map(|e| e.game).collect(); - list.sort_unstable(); - list.dedup(); - for &game in &list { - tally.add(games[game as usize].outcome); - } - RepeatedError { - key: first.key, - ply: first.ply, - uci: first.uci.clone(), - san: first.san.clone(), - best_san: first.best_san.clone(), - judgement: first.judgement, - games: list, - tally, - opening: first.opening, - } - }) - .filter(|r| r.games.len() >= 2) - .collect(); - out.sort_by(|a, b| { - b.games - .len() - .cmp(&a.games.len()) - .then(b.judgement.cmp(&a.judgement)) - .then(a.ply.cmp(&b.ply)) - .then(a.games.cmp(&b.games)) - }); - out -} - -// ----- the cache of evaluations by position -------------------------------------- - -const CACHE_FILE: &str = "positions.json"; -const CACHE_VERSION: u32 = 1; -/// Positions kept at most (about 100 bytes each on disk). -const CACHE_LIMIT: usize = 1_000_000; - -#[derive(Serialize, Deserialize)] -struct CacheFile { - version: u32, - /// The version of the fixed search the evaluations come from ([`SEARCH_VERSION`]; - /// 0: from before it). Those of another one are not used. - #[serde(default)] - search: u32, - positions: Vec<(u64, PositionEval)>, -} - -/// Engine evaluations by position, shared by every report: the best quality (most -/// nodes) seen for each position is kept. -#[derive(Default)] -pub struct PositionCache { - entries: HashMap, - dirty: bool, -} - -impl PositionCache { - fn path(dir: &Path) -> PathBuf { - dir.join(CACHE_FILE) - } - - /// The cache in `dir` (empty when there is none, or it cannot be read). - pub fn load(dir: &Path) -> PositionCache { - let entries = std::fs::read(Self::path(dir)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) - .filter(|f| f.version == CACHE_VERSION && f.search == SEARCH_VERSION) - .map(|f| f.positions.into_iter().collect()) - .unwrap_or_default(); - PositionCache { - entries, - dirty: false, - } - } - - pub fn len(&self) -> usize { - self.entries.len() - } - - pub fn is_empty(&self) -> bool { - self.entries.is_empty() - } - - pub fn get(&self, key: u64) -> Option<&PositionEval> { - self.entries.get(&key) - } - - /// Keeps `eval` unless the cache has one with more nodes; says whether it was kept. - pub fn insert(&mut self, key: u64, eval: PositionEval) -> bool { - if self - .entries - .get(&key) - .is_some_and(|e| e.nodes >= eval.nodes) - { - return false; - } - self.entries.insert(key, eval); - self.dirty = true; - true - } - - /// Something was added since the load or the last save. - pub fn dirty(&self) -> bool { - self.dirty - } - - /// Writes the cache to `dir` (through a temporary file, so a crash never leaves - /// half a file); nothing when nothing changed. - pub fn save(&mut self, dir: &Path) -> std::io::Result<()> { - if !self.dirty { - return Ok(()); - } - let mut positions: Vec<(u64, PositionEval)> = - self.entries.iter().map(|(k, v)| (*k, v.clone())).collect(); - if positions.len() > CACHE_LIMIT { - // Over the limit the searches with the fewest nodes go first. - positions.sort_by_key(|a| std::cmp::Reverse(a.1.nodes)); - positions.truncate(CACHE_LIMIT); - } - let file = CacheFile { - version: CACHE_VERSION, - search: SEARCH_VERSION, - positions, - }; - let bytes = serde_json::to_vec(&file).map_err(std::io::Error::other)?; - write_atomic(&Self::path(dir), &bytes)?; - self.dirty = false; - Ok(()) - } -} - -/// Writes through a temporary file and a rename. -pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, bytes)?; - std::fs::rename(&tmp, path) -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tree::tests::game; - - fn eval(nodes: u64, cp: i32, best: &str) -> PositionEval { - PositionEval { - nodes, - eval: Eval::Cp(cp), - pv: vec![best.to_owned()], - depth: 10, - } - } - - #[test] - fn the_same_error_in_two_games_is_repeated() { - // Three games of the player with White: 1.e4 e5 2.Qh5?! twice, 2.Nf3 once. - let games = vec![ - game(0, true, &["e4", "e5", "Qh5", "Nc6"], "1-0", "", 0), - game(1, true, &["e4", "e5", "Qh5", "Nf6"], "0-1", "", 0), - game(2, true, &["e4", "e5", "Nf3", "Nc6"], "1/2-1/2", "", 0), - game(3, false, &["e4", "e5", "Qh5", "Nc6"], "0-1", "", 0), - ]; - let mut evals = HashMap::new(); - evals.insert(games[0].keys[0], eval(1000, 30, "e2e4")); - evals.insert(games[0].keys[1], eval(1000, 30, "e7e5")); - // 2.Qh5 drops from +0.3 to −1.0: a mistake; 2.Nf3 is the engine's move. - evals.insert(games[0].keys[2], eval(1000, 30, "g1f3")); - evals.insert(games[0].keys[3], eval(1000, -100, "b8c6")); - evals.insert(games[1].keys[3], eval(1000, -100, "g8f6")); - evals.insert(games[2].keys[3], eval(1000, 30, "b8c6")); - let errors = judge_games(&games, &[0, 1, 2], &evals); - assert_eq!(errors.len(), 2); - assert_eq!(errors[0].game, 0); - assert_eq!(errors[0].ply, 2); - assert_eq!(errors[0].san, "Qh5"); - assert_eq!(errors[0].best_san, "Nf3"); - assert_eq!(errors[0].judgement, Judgement::Mistake); - assert_eq!(errors[1].game, 1); - let rep = repeated(&errors, &games); - assert_eq!(rep.len(), 1); - assert_eq!(rep[0].games, vec![0, 1]); - assert_eq!(rep[0].times(), 2); - assert_eq!((rep[0].tally.wins, rep[0].tally.losses), (1, 1)); - // Black's moves in game 3 are the player's: 2.Qh5 is the opponent's there. - let evals_black = evals.clone(); - assert!(judge_games(&games, &[3], &evals_black).is_empty()); - // A position without an evaluation after the move is not judged (the two - // games share the position after 2.Qh5). - let mut partial = evals.clone(); - partial.remove(&games[1].keys[3]); - assert!(judge_games(&games, &[0, 1, 2], &partial).is_empty()); - // One game less: nothing repeats. - assert!(repeated(&judge_games(&games, &[0, 2], &evals), &games).is_empty()); - } - - fn line_evals(game: &GameInfo, values: &[i32]) -> HashMap { - game.keys - .iter() - .enumerate() - .map(|(ply, &key)| { - ( - key, - eval( - 1000, - values[ply], - game.ucis.get(ply).map_or("", String::as_str), - ), - ) - }) - .collect() - } - - #[test] - fn every_opponent_error_category_stops_later_errors_for_both_colours() { - for white in [true, false] { - for (loss, category) in [ - (60, Judgement::Inaccuracy), - (150, Judgement::Mistake), - (500, Judgement::Blunder), - ] { - let game = game(0, white, &["e4", "e5", "Qh5", "Nc6"], "*", "", 0); - let (opponent_ply, player_ply, values) = if white { - (1, 2, vec![0, 0, loss, -150, -150]) - } else { - (0, 1, vec![0, -loss, 150, 150, 150]) - }; - let mut evals = line_evals(&game, &values); - evals.get_mut(&game.keys[opponent_ply]).unwrap().pv = - vec![if white { "c7c5" } else { "d2d4" }.to_owned()]; - evals.get_mut(&game.keys[player_ply]).unwrap().pv = - vec![if white { "g1f3" } else { "c7c5" }.to_owned()]; - let mover = if white { - chess_core::shakmaty::Color::Black - } else { - chess_core::shakmaty::Color::White - }; - assert_eq!( - game_review::judge( - Eval::Cp(values[opponent_ply]), - Eval::Cp(values[opponent_ply + 1]), - mover - ), - Some(category) - ); - assert!(judge_games(std::slice::from_ref(&game), &[0], &evals).is_empty()); - // The engine's own best move is exempt even if evaluations differ. - evals.get_mut(&game.keys[opponent_ply]).unwrap().pv = - vec![game.ucis[opponent_ply].clone()]; - let errors = judge_games(std::slice::from_ref(&game), &[0], &evals); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].ply, player_ply as u32); - } - } - } - - #[test] - fn earlier_player_errors_survive_but_the_whole_later_suffix_is_excluded() { - for white in [true, false] { - let game = game( - 0, - white, - &["e4", "e5", "Qh5", "Nc6", "Bc4", "Nf6"], - "*", - "", - 0, - ); - let values = if white { - vec![0, -150, 0, -150, -150, -300, -300] - } else { - vec![0, 0, 150, 0, 150, 0, 150] - }; - let mut evals = line_evals(&game, &values); - let first_player = usize::from(!white); - let opponent = first_player + 1; - let alternatives = if white { - ["d2d4", "c7c5", "g1f3", "d2d3"] - } else { - ["c7c5", "g1f3", "g8f6", "d7d6"] - }; - for (ply, best) in [first_player, opponent, first_player + 2, first_player + 4] - .into_iter() - .zip(alternatives) - { - evals.get_mut(&game.keys[ply]).unwrap().pv = vec![best.to_owned()]; - } - let errors = judge_games(std::slice::from_ref(&game), &[0], &evals); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].ply, first_player as u32); - } - } - - #[test] - fn incomplete_opponent_prefix_withholds_errors_until_checked() { - let game = game(0, true, &["e4", "e5", "Qh5", "Nc6"], "*", "", 0); - let mut complete = line_evals(&game, &[0, 0, 0, -150, -150]); - complete.get_mut(&game.keys[2]).unwrap().pv = vec!["g1f3".to_owned()]; - for missing in [game.keys[1], game.keys[2]] { - let mut partial = complete.clone(); - partial.remove(&missing); - assert!(judge_games(std::slice::from_ref(&game), &[0], &partial).is_empty()); - } - let mut missing_best = complete.clone(); - missing_best.get_mut(&game.keys[1]).unwrap().pv.clear(); - assert!(judge_games(std::slice::from_ref(&game), &[0], &missing_best).is_empty()); - assert_eq!( - judge_games(std::slice::from_ref(&game), &[0], &complete).len(), - 1 - ); - } - - #[test] - fn opponent_allowing_mate_is_judged_from_the_actual_mover() { - for white in [true, false] { - let game = game(0, white, &["e4", "e5", "Qh5", "Nc6"], "*", "", 0); - let opponent = usize::from(white); - let mut evals = line_evals(&game, &[0, 0, 0, 0, 0]); - evals.get_mut(&game.keys[opponent]).unwrap().pv = - vec![if white { "c7c5" } else { "d2d4" }.to_owned()]; - evals.get_mut(&game.keys[opponent + 1]).unwrap().eval = Eval::Mate { white, moves: 3 }; - evals.get_mut(&game.keys[opponent + 1]).unwrap().pv = - vec![if white { "g1f3" } else { "c7c5" }.to_owned()]; - // The player's next move lets that forced mate go, normally an error. - assert!(judge_games(std::slice::from_ref(&game), &[0], &evals).is_empty()); - } - } - - #[test] - fn the_position_cache_keeps_the_best_quality_and_survives_a_save() { - let dir = std::env::temp_dir().join(format!("prep-cache-test-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut c = PositionCache::load(&dir); - assert!(c.is_empty()); - assert!(c.insert(1, eval(1000, 10, "e2e4"))); - assert!(!c.insert(1, eval(250, 20, "d2d4")), "fewer nodes: not kept"); - assert!(c.insert(1, eval(3000, 30, "c2c4"))); - assert!(c.insert(2, eval(EXACT, 0, ""))); - assert_eq!(c.get(1).map(|e| e.nodes), Some(3000)); - assert!(c.dirty()); - c.save(&dir).expect("saved"); - assert!(!c.dirty()); - let d = PositionCache::load(&dir); - assert_eq!(d.len(), 2); - assert_eq!(d.get(1), c.get(1)); - assert_eq!(d.get(2).map(|e| e.nodes), Some(EXACT)); - assert_eq!(d.get(3), None); - // A cache from before the fixed search of the game analysis is not used. - let path = PositionCache::path(&dir); - let mut json: serde_json::Value = - serde_json::from_slice(&std::fs::read(&path).expect("cache")).expect("json"); - json.as_object_mut().expect("cache").remove("search"); - std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written"); - assert!(PositionCache::load(&dir).is_empty()); - let _ = std::fs::remove_dir_all(&dir); - } -} diff --git a/crates/prep/src/games.rs b/crates/prep/src/games.rs deleted file mode 100644 index 1ceddc6..0000000 --- a/crates/prep/src/games.rs +++ /dev/null @@ -1,230 +0,0 @@ -//! The player's games as the report sees them: the first plies of the main line with -//! the keys of its positions, the result from the player's side, the date and the -//! opponent's rating. Games from a set-up position are left out. - -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - -use chess_core::shakmaty::san::SanPlus; -use chess_core::shakmaty::{Chess, Position}; -use chess_import::Database; -use chess_import::pgn_catalog::date_number; -use chess_import::position::{key, uci}; -use serde::{Deserialize, Serialize}; - -use crate::openings::{self, OpeningSet}; - -/// A game's result from the player's side. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Outcome { - Win, - Draw, - Loss, - Unknown, -} - -impl Outcome { - /// From the result tag and the player's colour. - pub fn of(result: &str, white: bool) -> Outcome { - match (result.trim(), white) { - ("1-0", true) | ("0-1", false) => Outcome::Win, - ("1-0", false) | ("0-1", true) => Outcome::Loss, - ("1/2-1/2" | "½-½", _) => Outcome::Draw, - _ => Outcome::Unknown, - } - } -} - -/// Games and their results from the player's side. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct Tally { - pub games: u32, - pub wins: u32, - pub draws: u32, - pub losses: u32, -} - -impl Tally { - pub fn add(&mut self, outcome: Outcome) { - self.games += 1; - match outcome { - Outcome::Win => self.wins += 1, - Outcome::Draw => self.draws += 1, - Outcome::Loss => self.losses += 1, - Outcome::Unknown => {} - } - } - - /// Points per game, 0..1, over the games with a result. - pub fn score(&self) -> Option { - let decided = self.wins + self.draws + self.losses; - (decided > 0) - .then(|| (f64::from(self.wins) + 0.5 * f64::from(self.draws)) / f64::from(decided)) - } -} - -/// Legacy book data kept so old reports still round-trip. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct BookExit { - pub ply: u32, - pub by_player: bool, - pub count: u32, -} - -/// One game of the player. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct GameInfo { - /// Record index in the database. - pub index: u32, - /// The player had White. - pub white: bool, - pub opponent: String, - /// 0: unknown. - pub opponent_elo: u16, - /// PGN form ("2026.10.18", "1997.05.??"), empty when unknown. - pub date: String, - pub outcome: Outcome, - /// The first moves of the main line (at most the report's plies), UCI and SAN. - pub ucis: Vec, - pub sans: Vec, - /// Keys of the positions before each move and after the last: `ucis.len() + 1`. - pub keys: Vec, - /// The deepest named position of the line ([`crate::PrepReport::openings`]). - pub opening: Option, - /// Plies of the line up to the named position (`keys[named]` is it). - pub named: Option, - /// Unused legacy book data, preserved when old reports are saved again. - #[serde(default)] - pub book: Option, -} - -impl GameInfo { - /// `yyyymmdd` for ordering (0: no date). - pub fn date_number(&self) -> u32 { - date_number(&self.date) - } - - /// Move `ply` (0-based) was the player's. - pub fn player_moves_at(&self, ply: usize) -> bool { - ply.is_multiple_of(2) == self.white - } - - /// "12. Nf3" / "12... Nf6" for move `ply` (0-based). - pub fn move_label(&self, ply: usize) -> String { - let san = self.sans.get(ply).map_or("", String::as_str); - move_label(ply, san) - } -} - -/// "12. Nf3" / "12... Nf6" for move `ply` (0-based from the usual start position). -pub fn move_label(ply: usize, san: &str) -> String { - let number = ply / 2 + 1; - if ply.is_multiple_of(2) { - format!("{number}. {san}") - } else { - format!("{number}... {san}") - } -} - -/// What a pass over the games produced. -pub struct Collected { - pub games: Vec, - pub openings: OpeningSet, - /// Games left out: from a set-up position, or unreadable. - pub skipped: u32, - /// Final positions of lines that end in checkmate or stalemate: (key, position). - pub terminal: Vec<(u64, Chess)>, -} - -/// Reads the first `plies` of each of `found` (record, the player had White); -/// `progress` counts the games done. `None` when cancelled. -pub fn collect( - db: &Database, - found: &[(u32, bool)], - plies: usize, - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Option { - let mut out = Collected { - games: Vec::with_capacity(found.len()), - openings: OpeningSet::default(), - skipped: 0, - terminal: Vec::new(), - }; - for &(index, white) in found { - if cancel.load(Ordering::Relaxed) { - return None; - } - progress.fetch_add(1, Ordering::Relaxed); - let Some(line) = db.main_line(index as usize, plies) else { - out.skipped += 1; - continue; - }; - if !line.standard_start { - out.skipped += 1; - continue; - } - let row = db.row(index as usize); - let mut pos = Chess::default(); - let mut keys = Vec::with_capacity(line.moves.len() + 1); - let mut ucis = Vec::with_capacity(line.moves.len()); - let mut sans = Vec::with_capacity(line.moves.len()); - keys.push(key(&pos)); - for m in &line.moves { - ucis.push(uci(m).to_string()); - sans.push(SanPlus::from_move_and_play_unchecked(&mut pos, *m).to_string()); - keys.push(key(&pos)); - } - if pos.is_checkmate() || pos.is_stalemate() { - out.terminal.push((key(&pos), pos)); - } - let (opening, named) = match openings::deepest(&keys) { - Some((at, id)) => (Some(out.openings.intern(id)), Some(at as u32)), - None => (None, None), - }; - out.games.push(GameInfo { - index, - white, - opponent: if white { row.black } else { row.white }, - opponent_elo: if white { row.black_elo } else { row.white_elo }, - date: row.date, - outcome: Outcome::of(row.result, white), - ucis, - sans, - keys, - opening, - named, - book: None, - }); - } - Some(out) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn outcomes_and_tallies() { - assert_eq!(Outcome::of("1-0", true), Outcome::Win); - assert_eq!(Outcome::of("1-0", false), Outcome::Loss); - assert_eq!(Outcome::of("0-1", false), Outcome::Win); - assert_eq!(Outcome::of("1/2-1/2", true), Outcome::Draw); - assert_eq!(Outcome::of("*", true), Outcome::Unknown); - let mut t = Tally::default(); - for o in [ - Outcome::Win, - Outcome::Win, - Outcome::Draw, - Outcome::Loss, - Outcome::Unknown, - ] { - t.add(o); - } - assert_eq!((t.games, t.wins, t.draws, t.losses), (5, 2, 1, 1)); - assert_eq!(t.score(), Some(0.625)); - assert_eq!(Tally::default().score(), None); - assert_eq!(move_label(0, "e4"), "1. e4"); - assert_eq!(move_label(1, "c5"), "1... c5"); - assert_eq!(move_label(22, "Nf3"), "12. Nf3"); - } -} diff --git a/crates/prep/src/lib.rs b/crates/prep/src/lib.rs deleted file mode 100644 index 9e746e6..0000000 --- a/crates/prep/src/lib.rs +++ /dev/null @@ -1,1254 +0,0 @@ -//! Preparing against an opponent on the desktop: what a player of a database plays -//! in the opening and where in the opening he goes wrong. -//! -//! The [`PrepReport`] is built in a moment from the player's games ([`build`]): his -//! main lines up to a number of plies, the repertoire tree of each colour with -//! transpositions marked, and the openings named from the Lichess `chess-openings` -//! table (family → variation → games). The engine step is apart and optional: every -//! distinct position of -//! the lines is evaluated once ([`PrepReport::targets`], run by -//! [`game_review::run`], results taken in by [`PrepReport::apply`]), the player's -//! moves are judged with the rules of the game analysis, and the errors are listed by -//! opening and, when the same error was made in several games, as repeated. The -//! report is cached by database, player and plies; evaluations by position, across -//! reports ([`PositionCache`]). -//! -//! Nothing here touches the database or the games; no user interface. - -use std::collections::HashMap; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::time::SystemTime; - -use chess_import::Database; -use game_review::{JobEvent, SEARCH_NODES, SEARCH_VERSION, Target}; -#[cfg(not(target_family = "wasm"))] -use game_review::{JobFailure, JobSettings}; -use serde::{Deserialize, Serialize}; -use uci::EnginePosition; - -mod errors; -mod games; -pub mod openings; -mod period; -mod players; -mod tree; - -pub use chess_import::chessbase::base::Side; -pub use errors::{EXACT, ErrorCounts, OpeningError, PositionCache, PositionEval, RepeatedError}; -pub use game_review::{Eval, Judgement}; -pub use games::{BookExit, GameInfo, Outcome, Tally, move_label}; -pub use openings::Opening; -pub use period::{Chosen, Period, PoolGame, newest as period_newest}; -pub use players::{Candidate, Player, candidates, games_of}; -pub use tree::{Node, Tree}; - -/// Plies of the opening a report looks at unless told otherwise. -pub const DEFAULT_PLIES: usize = 20; - -/// What a report covers. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub struct Options { - /// Plies of each game's main line. - pub plies: usize, - /// The player's colour(s). - pub side: Side, - /// Which of his games. - pub period: Period, -} - -impl Default for Options { - fn default() -> Self { - Options { - plies: DEFAULT_PLIES, - side: Side::Any, - period: Period::All, - } - } -} - -/// An opening as played by the player: the games with the same name. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Variation { - /// Index into [`PrepReport::openings`]; `None`: no named position in the line. - pub opening: Option, - pub tally: Tally, - /// Indices into [`PrepReport::games`], in order. - pub games: Vec, - pub errors: ErrorCounts, - /// Indices into [`ColorReport::errors`]. - pub error_list: Vec, -} - -/// The openings with the same family name ("Sicilian Defense"), most played first. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Family { - /// Empty for games without a named position. - pub name: String, - pub tally: Tally, - /// Most played first. - pub variations: Vec, - pub errors: ErrorCounts, -} - -/// The report for one colour of the player. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct ColorReport { - pub white: bool, - /// Indices into [`PrepReport::games`], in record order. - pub games: Vec, - pub tree: Tree, - pub families: Vec, - /// The player's opening errors, by game and ply (after the engine step). - pub errors: Vec, - /// The errors made in two or more games. - pub repeated: Vec, - pub counts: ErrorCounts, -} - -/// The engine the evaluations came from. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct EngineInfo { - pub name: String, - /// Nodes per position. - pub nodes: u64, -} - -/// Legacy book data kept so old reports still round-trip. -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct BookInfo { - pub fingerprint: u64, - pub threshold: u32, - pub left: u32, -} - -// 4: the period and the pool of the player's games. -const REPORT_VERSION: u32 = 4; - -/// Everything the preparation knows about the player. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct PrepReport { - pub version: u32, - /// Of the database ([`fingerprint`]). - pub fingerprint: u64, - pub player: Player, - /// The player's names in the database. - pub names: Vec, - pub plies: usize, - pub side_white: bool, - pub side_black: bool, - /// Which of the player's games the report took. - #[serde(default)] - pub period: Period, - /// All the player's games of the side(s), before the period's choice (for the - /// counts of the other periods). - #[serde(default)] - pub pool: Vec, - pub games: Vec, - /// Games left out: from a set-up position, or unreadable. - pub skipped: u32, - /// The openings the games and trees refer to. - pub openings: Vec, - pub white: ColorReport, - pub black: ColorReport, - /// Unused legacy book data, preserved when old reports are saved again. - #[serde(default)] - pub book: Option, - #[serde(default)] - pub book_counts: HashMap, - pub engine: Option, - /// Engine evaluations by position key. - pub evals: HashMap, - /// The version of the fixed search of the game analysis the evaluations come from - /// ([`SEARCH_VERSION`]; 0: from before it, made with the user's engine settings). - #[serde(default)] - pub search: u32, - /// A manual Stop forbids another automatic run of this report. - #[serde(default)] - pub engine_stopped: bool, -} - -/// Identity of a database for the report cache: the content of a PGN file, the -/// path, size and time of a ChessBase database. -pub fn fingerprint(db: &Database) -> u64 { - match db { - Database::Pgn(p) => { - let f = p.fingerprint(); - fnv(f - .content_hash - .to_le_bytes() - .iter() - .chain(f.len.to_le_bytes().iter())) - } - Database::ChessBase(b) => { - let meta = std::fs::metadata(b.path()).ok(); - let len = meta.as_ref().map_or(0, std::fs::Metadata::len); - let modified = meta - .and_then(|m| m.modified().ok()) - .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok()) - .map_or(0, |d| d.as_secs()); - fnv(b - .path() - .to_string_lossy() - .bytes() - .chain(len.to_le_bytes()) - .chain(modified.to_le_bytes()) - .collect::>() - .iter()) - } - } -} - -fn fnv<'a>(bytes: impl Iterator) -> u64 { - let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in bytes { - h ^= u64::from(*b); - h = h.wrapping_mul(0x0000_0100_0000_01b3); - } - h -} - -/// Builds the report of `player` in `db`: his games ([`games_of`]), their first -/// plies, the trees, the names and the opening tables. `progress` counts the games -/// read. `None` when cancelled. Milliseconds for hundreds of games. -pub fn build( - db: &Database, - player: &Player, - options: &Options, - progress: &AtomicUsize, - cancel: &AtomicBool, -) -> Option { - let found = games_of(db, player, options.side, cancel)?; - // Every game is read (its first plies: a moment), so that the pool and the counts of - // the periods are of the games a report can take: not those from a set-up position. - let collected = games::collect(db, &found, options.plies, progress, cancel)?; - let pool: Vec = collected - .games - .iter() - .map(|g| PoolGame { - index: g.index, - white: g.white, - date: g.date_number(), - }) - .collect(); - let chosen: std::collections::HashSet<(u32, bool)> = - period::choose(&pool, options.period).into_iter().collect(); - let mut openings = collected.openings; - let games: Vec = collected - .games - .into_iter() - .filter(|g| chosen.contains(&(g.index, g.white))) - .collect(); - let mut evals = HashMap::new(); - for (key, pos) in &collected.terminal { - if let Some(eval) = game_review::terminal_eval(pos) { - evals.insert( - *key, - PositionEval { - nodes: EXACT, - eval, - pv: Vec::new(), - depth: 0, - }, - ); - } - } - let color = |white: bool, openings: &mut openings::OpeningSet| -> ColorReport { - let which: Vec = games - .iter() - .enumerate() - .filter(|(_, g)| g.white == white) - .map(|(i, _)| i as u32) - .collect(); - let tree = Tree::build(&games, &which, options.plies, openings); - let families = families(&games, &which, &openings.list); - ColorReport { - white, - games: which, - tree, - families, - errors: Vec::new(), - repeated: Vec::new(), - counts: ErrorCounts::default(), - } - }; - let white = color(true, &mut openings); - let black = color(false, &mut openings); - let mut report = PrepReport { - version: REPORT_VERSION, - fingerprint: fingerprint(db), - player: player.clone(), - names: player.names(db), - plies: options.plies, - side_white: options.side != Side::Black, - side_black: options.side != Side::White, - period: options.period, - pool, - games, - skipped: collected.skipped, - openings: openings.list, - white, - black, - book: None, - book_counts: HashMap::new(), - engine: None, - evals, - search: SEARCH_VERSION, - engine_stopped: false, - }; - report.refresh(); - Some(report) -} - -/// Groups `games[g]` for `g` in `which` by opening name: families, most played -/// first, each with its variations, most played first. A name the table gives to -/// several positions ("Sicilian Defense: Closed" after 2.Nc3 and after 2...e6) is one -/// variation, shown with its shortest line. -fn families(games: &[GameInfo], which: &[u32], openings: &[Opening]) -> Vec { - let mut out: Vec = Vec::new(); - let mut family_of: HashMap = HashMap::new(); - let mut variation_of: HashMap<(usize, String), usize> = HashMap::new(); - for &g in which { - let game = &games[g as usize]; - let opening = game.opening.map(|o| &openings[o]); - let name = opening.map(|o| o.family().to_owned()).unwrap_or_default(); - let f = *family_of.entry(name.clone()).or_insert_with(|| { - out.push(Family { - name, - ..Family::default() - }); - out.len() - 1 - }); - let full = opening.map(|o| o.name.clone()).unwrap_or_default(); - let v = *variation_of.entry((f, full)).or_insert_with(|| { - out[f].variations.push(Variation { - opening: game.opening, - ..Variation::default() - }); - out[f].variations.len() - 1 - }); - out[f].tally.add(game.outcome); - let var = &mut out[f].variations[v]; - if let (Some(o), Some(shown)) = (game.opening, var.opening) - && openings[o].plies < openings[shown].plies - { - var.opening = Some(o); - } - var.tally.add(game.outcome); - var.games.push(g); - } - let variation_name = |v: &Variation| -> String { - v.opening - .map(|o| openings[o].name.clone()) - .unwrap_or_default() - }; - for f in &mut out { - f.variations.sort_by(|a, b| { - b.tally - .games - .cmp(&a.tally.games) - .then_with(|| variation_name(a).cmp(&variation_name(b))) - }); - } - out.sort_by(|a, b| { - b.tally - .games - .cmp(&a.tally.games) - .then_with(|| a.name.cmp(&b.name)) - }); - out -} - -impl PrepReport { - /// The colour(s) the report was built for. - pub fn side(&self) -> Side { - match (self.side_white, self.side_black) { - (true, false) => Side::White, - (false, true) => Side::Black, - _ => Side::Any, - } - } - - /// The options the report was built with. - pub fn options(&self) -> Options { - Options { - plies: self.plies, - side: self.side(), - period: self.period, - } - } - - /// How many games `period` would take of the colour(s) `side`. - pub fn count(&self, period: Period, side: Side) -> Chosen { - period::count(&self.pool, period, side) - } - - pub fn color(&self, white: bool) -> &ColorReport { - if white { &self.white } else { &self.black } - } - - // ----- the engine ----------------------------------------------------------- - - /// Every distinct position of the lines (the one after the last move included), - /// first met first; those without legal moves left out. - fn positions(&self) -> Vec<(u64, &GameInfo, usize)> { - self.positions_for(Side::Any) - } - - /// [`PrepReport::positions`] of the games the player had `side` in. - fn positions_for(&self, side: Side) -> Vec<(u64, &GameInfo, usize)> { - let mut seen = std::collections::HashSet::new(); - let mut out = Vec::new(); - for g in &self.games { - if (side == Side::White && !g.white) || (side == Side::Black && g.white) { - continue; - } - for (i, &k) in g.keys.iter().enumerate() { - if self.evals.get(&k).is_some_and(|e| e.nodes == EXACT) { - continue; - } - if seen.insert(k) { - out.push((k, g, i)); - } - } - } - out - } - - /// Some position has an engine evaluation (from a run or from the cache): the - /// errors are judged. - pub fn evaluated(&self) -> bool { - self.evals.values().any(|e| e.nodes != EXACT) - } - - /// Distinct positions an engine run looks at. - pub fn distinct_positions(&self) -> usize { - self.positions().len() - } - - /// Distinct positions of the games the player had `side` in. - pub fn distinct_positions_for(&self, side: Side) -> usize { - self.positions_for(side).len() - } - - /// Positions without an evaluation. - pub fn missing(&self) -> usize { - self.missing_for(Side::Any) - } - - /// [`PrepReport::missing`] among the games the player had `side` in. - pub fn missing_for(&self, side: Side) -> usize { - self.positions_for(side) - .iter() - .filter(|(k, _, _)| !self.evals.contains_key(k)) - .count() - } - - /// Takes from `cache` the evaluations the report lacks; returns how many. - pub fn take_cached(&mut self, cache: &PositionCache) -> usize { - let keys: Vec = self.positions().iter().map(|(k, _, _)| *k).collect(); - let mut taken = 0; - for k in keys { - if self.evals.contains_key(&k) { - continue; - } - if let Some(e) = cache.get(k) { - self.evals.insert(k, e.clone()); - taken += 1; - } - } - if taken > 0 { - self.refresh(); - } - taken - } - - /// The positions still to evaluate, for [`game_review::run`] (one search each, no - /// second search for !! and !). Their keys are the position keys in hexadecimal, as - /// [`PrepReport::apply`] reads them. - pub fn targets(&self) -> Vec { - self.targets_for(Side::Any) - } - - /// [`PrepReport::targets`] of the games the player had `side` in (the dialog's - /// «Black — 133 games» halves the work). - pub fn targets_for(&self, side: Side) -> Vec { - self.positions_for(side) - .into_iter() - .filter(|(k, _, _)| !self.evals.contains_key(k)) - .map(|(k, g, i)| Target { - key: format!("{k:016x}"), - pos: EnginePosition::startpos(g.ucis[..i].iter().cloned()), - turn: if i.is_multiple_of(2) { - uci::Side::White - } else { - uci::Side::Black - }, - played: None, - others: Vec::new(), - known: None, - shallow: None, - }) - .collect() - } - - /// Takes in what the engine job reported; the evaluation it carried (to cache), if - /// any. The errors are re-judged on the next [`PrepReport::refresh`]. - pub fn apply(&mut self, event: &JobEvent) -> Option<(u64, PositionEval)> { - let nodes = SEARCH_NODES; - match event { - JobEvent::Engine(name) => { - self.engine = Some(EngineInfo { - name: name.clone(), - nodes, - }); - None - } - JobEvent::Eval { key, eval, .. } => { - let k = u64::from_str_radix(key, 16).ok()?; - let e = PositionEval::from_engine(nodes, eval); - self.engine.get_or_insert_with(|| EngineInfo { - name: String::new(), - nodes, - }); - self.evals.insert(k, e.clone()); - Some((k, e)) - } - } - } - - /// Re-judges the player's moves from the evaluations: the errors by colour, - /// opening and repetition. Cheap (the lines of the games). - pub fn refresh(&mut self) { - let PrepReport { - games, - evals, - white, - black, - .. - } = self; - for cr in [white, black] { - let errors = errors::judge_games(games, &cr.games, evals); - cr.repeated = errors::repeated(&errors, games); - cr.counts = ErrorCounts::default(); - let mut at: HashMap = HashMap::new(); - for (f, fam) in cr.families.iter_mut().enumerate() { - fam.errors = ErrorCounts::default(); - for (v, var) in fam.variations.iter_mut().enumerate() { - var.errors = ErrorCounts::default(); - var.error_list.clear(); - for &g in &var.games { - at.insert(g, (f, v)); - } - } - } - for (i, e) in errors.iter().enumerate() { - cr.counts.add(e.judgement); - if let Some(&(f, v)) = at.get(&e.game) { - let fam = &mut cr.families[f]; - fam.errors.add(e.judgement); - fam.variations[v].errors.add(e.judgement); - fam.variations[v].error_list.push(i as u32); - } - } - cr.errors = errors; - } - } - - // ----- the report cache ----------------------------------------------------- - - /// The cache file of a report in `dir`. - pub fn cache_path(dir: &Path, fingerprint: u64, player: &Player, options: &Options) -> PathBuf { - let mut bytes = fingerprint.to_le_bytes().to_vec(); - for id in &player.ids { - bytes.extend(id.to_le_bytes()); - } - bytes.extend((options.plies as u64).to_le_bytes()); - bytes.push(match options.side { - Side::Any => 0, - Side::White => 1, - Side::Black => 2, - }); - // All the games: as before periods were chosen (the reports cached then). - match options.period { - Period::All => {} - Period::Months(m) => { - bytes.push(1); - bytes.extend(u32::from(m).to_le_bytes()); - } - Period::Last(n) => { - bytes.push(2); - bytes.extend(n.to_le_bytes()); - } - } - dir.join(format!("{:016x}.json", fnv(bytes.iter()))) - } - - /// The report cached in `dir` for this database, player and options, if any. - pub fn load( - dir: &Path, - db: &Database, - player: &Player, - options: &Options, - ) -> Option { - let fp = fingerprint(db); - let bytes = std::fs::read(Self::cache_path(dir, fp, player, options)).ok()?; - let mut report: PrepReport = serde_json::from_slice(&bytes).ok()?; - let same = report.version == REPORT_VERSION - && report.fingerprint == fp - && report.player == *player - && report.plies == options.plies - && report.side() == options.side - && report.period == options.period; - if !same { - return None; - } - // Evaluations of another search are not mixed with today's: the errors are - // found again. - if report.search != SEARCH_VERSION { - report.evals.retain(|_, e| e.nodes == EXACT); - report.engine = None; - report.search = SEARCH_VERSION; - } - // Errors and their aggregates are derived data. Reapply current eligibility - // rules even when cached evaluations came from the same engine search. - report.refresh(); - Some(report) - } - - /// Keeps the report in `dir` (atomically). - pub fn save(&self, dir: &Path) -> std::io::Result<()> { - let options = self.options(); - let path = Self::cache_path(dir, self.fingerprint, &self.player, &options); - let bytes = serde_json::to_vec(self).map_err(std::io::Error::other)?; - errors::write_atomic(&path, &bytes) - } -} - -/// Progress of [`analyse`]. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Progress { - /// Positions evaluated in this run. - pub done: usize, - /// Positions the run has to evaluate. - pub total: usize, - /// The engine's speed in the last search (0 if it did not say). - pub nps: u64, -} - -// The engines run as processes, each driven from a thread: not in a browser. -#[cfg(not(target_family = "wasm"))] -/// Runs the engine over the positions `report` lacks (the cache -/// is consulted first and fed as results come; `cache_dir` saves it every few -/// hundred positions and at the end), updating the report as results come in. -/// Returns when done, or soon after `cancel` is set (what was evaluated stays). -pub fn analyse( - report: &mut PrepReport, - cache: &mut PositionCache, - cache_dir: Option<&Path>, - config: uci::EngineConfig, - settings: &JobSettings, - cancel: &AtomicBool, - on_progress: &mut dyn FnMut(Progress), -) -> Result<(), JobFailure> { - report.take_cached(cache); - let targets = report.targets(); - let total = targets.len(); - let mut progress = Progress { - done: 0, - total, - nps: 0, - }; - on_progress(progress); - if total == 0 { - return Ok(()); - } - let mut since_save = 0; - let result = game_review::run(config, settings, targets, cancel, &mut |event| { - if let JobEvent::Eval { nps, .. } = &event { - progress.done += 1; - progress.nps = *nps; - } - if let Some((key, eval)) = report.apply(&event) { - cache.insert(key, eval); - since_save += 1; - if since_save >= 200 - && let Some(dir) = cache_dir - { - let _ = cache.save(dir); - since_save = 0; - } - } - if matches!(event, JobEvent::Eval { .. }) { - on_progress(progress); - } - }); - report.refresh(); - if let Some(dir) = cache_dir { - let _ = cache.save(dir); - } - result -} - -#[cfg(test)] -mod tests { - use super::*; - use chess_core::PgnDatabase; - use chess_import::PgnDb; - - fn database(pgn: &str) -> Database { - let db = PgnDatabase::from_bytes( - pgn.as_bytes().to_vec(), - None, - &mut |_| {}, - &AtomicBool::new(false), - ) - .expect("pgn"); - Database::Pgn(PgnDb::new(db)) - } - - const PGN: &str = "\ -[White \"Вафин Радель\"] -[Black \"Иванов Иван\"] -[Date \"2026.01.10\"] -[BlackElo \"1500\"] -[Result \"1-0\"] - -1. e4 c5 2. Nf3 Nc6 3. Bb5 g6 4. O-O Bg7 1-0 - -[White \"Петров Пётр\"] -[Black \"Вафин Радель\"] -[Date \"2026.02.11\"] -[WhiteElo \"1700\"] -[Result \"0-1\"] - -1. e4 c5 2. Nf3 d6 3. d4 cxd4 4. Nxd4 Nf6 5. Nc3 a6 0-1 - -[White \"Вафин Радель\"] -[Black \"Вафина Раяна\"] -[Date \"2026.03.12\"] -[Result \"1/2-1/2\"] - -1. e4 c5 2. Nf3 Nc6 3. Bb5 e6 1/2-1/2 - -[White \"Вафин Р.\"] -[Black \"Сидоров\"] -[Date \"2026.04.01\"] -[Result \"0-1\"] - -1. d4 d5 2. c4 0-1 - -[White \"Вафин Радель\"] -[Black \"Set Up\"] -[FEN \"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1\"] -[SetUp \"1\"] -[Result \"*\"] - -1... e5 * -"; - - #[test] - fn candidates_games_and_openings_of_a_player() { - let db = database(PGN); - // Every name with both words ("Вафина Раяна" has them too): the user picks. - let (list, total) = candidates(&db, "Вафин Р.", 10); - assert_eq!(total, 3, "{list:?}"); - assert_eq!(list[0].name, "Вафин Радель"); - assert_eq!(list[0].games, 4); - assert_eq!(list[1].name, "Вафин Р."); - assert_eq!(list[2].name, "Вафина Раяна"); - let (one, _) = candidates(&db, "Радель", 10); - assert_eq!(one.len(), 1); - // Two spellings merged. - let player = Player::new([list[0].id, list[1].id]); - let never = AtomicBool::new(false); - let found = games_of(&db, &player, Side::Any, &never).expect("games"); - assert_eq!( - found, - vec![(0, true), (1, false), (2, true), (3, true), (4, true)] - ); - assert_eq!( - games_of(&db, &player, Side::Black, &never).expect("games"), - vec![(1, false)] - ); - let report = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - assert_eq!(report.games.len(), 4, "the set-up game is left out"); - assert_eq!(report.skipped, 1); - assert_eq!(report.names, vec!["Вафин Радель", "Вафин Р."]); - let g = &report.games[0]; - assert_eq!( - (g.index, g.white, g.opponent.as_str(), g.opponent_elo), - (0, true, "Иванов Иван", 1500) - ); - assert_eq!(g.date, "2026.01.10"); - assert_eq!(g.outcome, Outcome::Win); - assert_eq!( - g.sans, - vec!["e4", "c5", "Nf3", "Nc6", "Bb5", "g6", "O-O", "Bg7"] - ); - assert_eq!(g.keys.len(), 9); - let o = &report.openings[g.opening.expect("named")]; - assert!( - o.name - .starts_with("Sicilian Defense: Nyezhmetdinov-Rossolimo Attack"), - "{}", - o.name - ); - assert_eq!(g.named, Some(6)); - assert_eq!(report.games[1].outcome, Outcome::Win); - assert_eq!(report.games[1].opponent_elo, 1700); - // White: two Rossolimo games and one Queen's Gambit; the family first. - let w = &report.white; - assert_eq!(w.games, vec![0, 2, 3]); - assert_eq!(w.families.len(), 2); - assert_eq!(w.families[0].name, "Sicilian Defense"); - assert_eq!(w.families[0].tally.games, 3 - 1); - assert_eq!( - w.families[0].variations.len(), - 2, - "3...g6 and 3...e6 are named apart" - ); - assert_eq!(w.families[1].name, "Queen's Gambit"); - assert_eq!(w.tree.nodes[0].tally.games, 3); - assert_eq!(w.tree.nodes[0].last_date, "2026.04.01"); - assert_eq!(w.tree.nodes[0].average_elo(), Some(1500)); - let b = &report.black; - assert_eq!(b.games, vec![1]); - assert_eq!(b.families[0].name, "Sicilian Defense"); - let name = &report.openings[b.families[0].variations[0].opening.unwrap()].name; - assert!(name.contains("Najdorf"), "{name}"); - assert!(report.evals.is_empty() && report.engine.is_none()); - assert_eq!(report.side(), Side::Any); - // Only White. - let white_only = build( - &db, - &player, - &Options { - plies: 4, - side: Side::White, - period: Period::All, - }, - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - assert_eq!(white_only.games.len(), 3); - assert!(white_only.black.games.is_empty()); - assert!(white_only.games.iter().all(|g| g.ucis.len() <= 4)); - assert_eq!(white_only.side(), Side::White); - // The last two months before his newest game (2026.04.01): from 2026.02.01. - let recent = build( - &db, - &player, - &Options { - period: Period::Months(2), - ..Options::default() - }, - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - let dates: Vec<&str> = recent.games.iter().map(|g| g.date.as_str()).collect(); - assert_eq!(dates, ["2026.02.11", "2026.03.12", "2026.04.01"]); - // The pool: the games a report can take (not the set-up one it skips). - let all = report.games.len(); - assert_eq!(report.skipped, 1); - assert_eq!(recent.pool.len(), all); - assert_eq!(recent.count(Period::All, Side::Any).games, all); - assert_eq!(recent.count(Period::Months(2), Side::Any).games, 3); - assert_eq!(recent.count(Period::Last(1), Side::White).games, 1); - // Cancelled. - let cancelled = AtomicBool::new(true); - assert!( - build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &cancelled - ) - .is_none() - ); - } - - #[test] - fn one_name_for_several_positions_is_one_variation() { - // "Sicilian Defense: Closed" is the table's name after 2.Nc3 and after 2...e6. - let db = database( - "[White \"A\"]\n[Black \"B\"]\n[Result \"1-0\"]\n\n1. e4 c5 2. Nc3 e6 1-0\n\n\ - [White \"A\"]\n[Black \"C\"]\n[Result \"0-1\"]\n\n1. e4 c5 2. Nc3 0-1\n\n", - ); - let player = Player::new([candidates(&db, "A", 1).0[0].id]); - let report = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &AtomicBool::new(false), - ) - .expect("report"); - let fam = &report.white.families[0]; - assert_eq!(fam.name, "Sicilian Defense"); - assert_eq!(fam.variations.len(), 1); - let v = &fam.variations[0]; - assert_eq!(v.games, vec![0, 1]); - let o = &report.openings[v.opening.unwrap()]; - assert_eq!( - (o.name.as_str(), o.line.as_str()), - ("Sicilian Defense: Closed", "1. e4 c5 2. Nc3") - ); - } - - #[test] - fn legacy_book_fields_survive_report_serde() { - let db = database(PGN); - let (list, _) = candidates(&db, "Вафин Р.", 2); - let player = Player::new([list[0].id, list[1].id]); - let mut report = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &AtomicBool::new(false), - ) - .expect("report"); - assert!(report.book.is_none() && report.book_counts.is_empty()); - let exit = BookExit { - ply: 6, - by_player: false, - count: 1, - }; - report.games[0].book = Some(exit); - report.book = Some(BookInfo { - fingerprint: 17, - threshold: 5, - left: 1, - }); - report.book_counts.insert(report.games[0].keys[0], 4); - let json = serde_json::to_string(&report).expect("serialize"); - let restored: PrepReport = serde_json::from_str(&json).expect("deserialize"); - assert_eq!(restored.games[0].book, Some(exit)); - assert_eq!(restored.book, report.book); - assert_eq!(restored.book_counts, report.book_counts); - } - - #[test] - fn evaluations_give_the_errors_by_opening_and_the_report_is_cached() { - let db = database(PGN); - let (list, _) = candidates(&db, "Вафин Радель", 1); - let player = Player::new([list[0].id]); - let never = AtomicBool::new(false); - let mut report = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - let total = report.distinct_positions(); - // 9 + 11 + 7 positions; the start and 1.e4 c5 2.Nf3 shared by three games, - // 2...Nc6 3.Bb5 by two. - assert_eq!(total, 27 - 10); - let targets = report.targets(); - assert_eq!(targets.len(), total); - // One colour: the positions of its games only (the start position is in both). - let black = report.targets_for(Side::Black); - assert_eq!(black.len(), report.games[1].keys.len()); - assert_eq!(report.distinct_positions_for(Side::Black), black.len()); - assert!(report.distinct_positions_for(Side::White) < total); - assert_eq!(report.missing_for(Side::Black), black.len()); - assert_eq!(targets[0].key, format!("{:016x}", report.games[0].keys[0])); - assert!(targets[0].pos.moves.is_empty()); - assert_eq!(targets[3].pos.moves, vec!["e2e4", "c7c5", "g1f3"]); - assert_eq!(targets[3].turn, uci::Side::Black); - assert!( - targets - .iter() - .all(|t| t.played.is_none() && t.known.is_none()) - ); - // The engine says: every move fine but 3.Bb5, a blunder (+0.3 → −1.5). - let mut cache = PositionCache::default(); - for t in &targets { - let key = u64::from_str_radix(&t.key, 16).unwrap(); - let after_bb5 = report.games[0].keys[5]; - let eval = if key == after_bb5 { - Eval::Cp(-150) - } else { - Eval::Cp(30) - }; - let before_bb5 = report.games[0].keys[4]; - let pv = if key == before_bb5 { - vec!["d2d4".to_owned()] - } else { - report - .games - .iter() - .find_map(|game| { - game.keys - .iter() - .position(|&k| k == key) - .and_then(|ply| game.ucis.get(ply)) - .map(|uci| vec![uci.clone()]) - }) - .unwrap_or_default() - }; - let event = JobEvent::Eval { - key: t.key.clone(), - eval: game_review::PosEval { - eval, - pv, - depth: 12, - second: None, - shallow: None, - }, - nps: 0, - }; - let (k, e) = report.apply(&event).expect("an evaluation"); - cache.insert(k, e); - } - assert_eq!(report.missing(), 0); - assert!(report.evaluated()); - report.refresh(); - assert_eq!(report.engine.as_ref().map(|e| e.nodes), Some(SEARCH_NODES)); - let w = &report.white; - assert_eq!(w.counts.blunders, 2); - assert_eq!(w.errors.len(), 2); - assert_eq!(w.errors[0].san, "Bb5"); - assert_eq!(w.errors[0].best_san, "d4"); - assert_eq!(w.errors[0].ply, 4); - assert_eq!( - report.games[w.errors[0].game as usize].move_label(4), - "3. Bb5" - ); - assert_eq!(w.families[0].errors.blunders, 2); - assert_eq!(w.families[0].variations[0].errors.blunders, 1); - assert_eq!(w.families[0].variations[0].error_list.len(), 1); - assert_eq!(w.families.len(), 1); - assert_eq!(w.repeated.len(), 1); - assert_eq!(w.repeated[0].games, vec![0, 2]); - assert_eq!(w.repeated[0].tally.draws, 1); - assert!(report.black.errors.is_empty()); - // Cached: the report by database, player and options; the evaluations by - // position, for anyone. - let dir = std::env::temp_dir().join(format!("prep-report-test-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - assert!(PrepReport::load(&dir, &db, &player, &Options::default()).is_none()); - report.save(&dir).expect("saved"); - let again = PrepReport::load(&dir, &db, &player, &Options::default()).expect("cached"); - assert_eq!(again.white.errors, report.white.errors); - assert_eq!(again.evals.len(), report.evals.len()); - assert!( - PrepReport::load( - &dir, - &db, - &player, - &Options { - plies: 10, - side: Side::Any, - period: Period::All, - } - ) - .is_none() - ); - let other = Player::new([list[0].id + 1]); - assert!(PrepReport::load(&dir, &db, &other, &Options::default()).is_none()); - let mut fresh = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - assert!(!fresh.evaluated()); - assert_eq!(fresh.take_cached(&cache), total); - assert!( - fresh.evaluated(), - "evaluations from the cache judge the errors too" - ); - assert_eq!(fresh.white.repeated, report.white.repeated); - assert_eq!(fresh.take_cached(&cache), 0); - // A report of another search (from before the fixed one) keeps its games but - // not its evaluations. - let path = PrepReport::cache_path(&dir, report.fingerprint, &player, &Options::default()); - let mut json: serde_json::Value = - serde_json::from_slice(&std::fs::read(&path).expect("report")).expect("json"); - json.as_object_mut().expect("report").remove("search"); - std::fs::write(&path, serde_json::to_vec(&json).expect("json")).expect("written"); - let old = PrepReport::load(&dir, &db, &player, &Options::default()).expect("still read"); - assert!(!old.evaluated() && old.white.errors.is_empty()); - assert_eq!(old.missing(), total); - assert_eq!(old.search, SEARCH_VERSION); - let _ = std::fs::remove_dir_all(&dir); - } - - #[test] - fn cached_errors_and_all_aggregates_are_rejudged_after_opponent_error() { - let db = database( - r#"[White "Target"] -[Black "A"] -[Result "1-0"] - -1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 1-0 - -[White "Target"] -[Black "B"] -[Result "0-1"] - -1. Nf3 Nc6 2. e4 e5 3. Bb5 a6 0-1 -"#, - ); - let (list, _) = candidates(&db, "Target", 1); - let player = Player::new([list[0].id]); - let options = Options::default(); - let mut report = build( - &db, - &player, - &options, - &AtomicUsize::new(0), - &AtomicBool::new(false), - ) - .unwrap(); - for game in &report.games { - for (ply, &key) in game.keys.iter().enumerate() { - report.evals.insert( - key, - PositionEval { - nodes: SEARCH_NODES, - eval: Eval::Cp(0), - pv: game.ucis.get(ply).cloned().into_iter().collect(), - depth: 12, - }, - ); - } - } - let first = &report.games[0]; - let before_bb5 = first.keys[4]; - report.evals.get_mut(&before_bb5).unwrap().pv = vec!["d2d4".to_owned()]; - report.evals.get_mut(&first.keys[5]).unwrap().eval = Eval::Cp(-150); - report.refresh(); - assert_eq!(report.white.errors.len(), 2); - assert_eq!(report.white.repeated.len(), 1); - assert_eq!(report.white.repeated[0].times(), 2); - let eval_count = report.evals.len(); - // Only the first move order contains this earlier error by Black. The - // second game transposes into the same Bb5 error through a clean prefix. - report.evals.get_mut(&report.games[0].keys[1]).unwrap().pv = vec!["c7c5".to_owned()]; - report.evals.get_mut(&report.games[0].keys[2]).unwrap().eval = Eval::Cp(150); - // Persist intentionally stale derived errors with current search metadata. - let dir = std::env::temp_dir().join(format!("prep-prefix-cache-{}", std::process::id())); - report.save(&dir).unwrap(); - let mut loaded = PrepReport::load(&dir, &db, &player, &options).unwrap(); - assert_eq!(loaded.search, SEARCH_VERSION); - assert_eq!(loaded.evals.len(), eval_count); - assert_eq!(loaded.take_cached(&PositionCache::default()), 0); - assert_eq!(loaded.white.errors.len(), 1); - assert_eq!(loaded.white.errors[0].game, 1); - assert!(loaded.white.repeated.is_empty()); - assert_eq!(loaded.white.counts.total(), 1); - assert_eq!( - loaded - .white - .families - .iter() - .map(|f| f.errors.total()) - .sum::(), - 1 - ); - let variants: Vec<_> = loaded - .white - .families - .iter() - .flat_map(|f| &f.variations) - .collect(); - assert_eq!(variants.iter().map(|v| v.errors.total()).sum::(), 1); - assert_eq!( - variants - .iter() - .flat_map(|v| &v.error_list) - .copied() - .collect::>(), - vec![0] - ); - assert_eq!( - loaded.games.len(), - 2, - "the repertoire itself is not filtered" - ); - std::fs::remove_dir_all(dir).unwrap(); - } - - /// The fake engine of the `uci` crate (`cargo build -p uci --bin fake_uci`). - #[test] - fn the_engine_run_fills_the_report_and_the_cache() { - let fake = concat!(env!("CARGO_MANIFEST_DIR"), "/../../target/debug/fake_uci"); - assert!( - std::path::Path::new(fake).exists(), - "build the fake engine first: cargo build -p uci --bin fake_uci" - ); - let db = database(PGN); - let (list, _) = candidates(&db, "Вафин Радель", 1); - let player = Player::new([list[0].id]); - let never = AtomicBool::new(false); - let mut report = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - let total = report.distinct_positions(); - let settings = JobSettings::new(2, None); - let mut cache = PositionCache::default(); - let mut last = Progress::default(); - analyse( - &mut report, - &mut cache, - None, - uci::EngineConfig::new(fake), - &settings, - &never, - &mut |p| last = p, - ) - .expect("the job runs"); - assert_eq!((last.done, last.total), (total, total)); - assert_eq!(report.missing(), 0); - assert_eq!(cache.len(), total); - assert_eq!( - report.engine.as_ref().map(|e| e.name.as_str()), - Some("Fake UCI") - ); - // A second run has nothing to do; a cancelled one ends at once. - let mut again = build( - &db, - &player, - &Options::default(), - &AtomicUsize::new(0), - &never, - ) - .expect("report"); - let cancelled = AtomicBool::new(true); - let mut calls = 0; - analyse( - &mut again, - &mut cache, - None, - uci::EngineConfig::new(fake), - &settings, - &cancelled, - &mut |_| calls += 1, - ) - .expect("nothing to do"); - assert_eq!(again.missing(), 0, "all from the cache"); - assert_eq!(calls, 1); - } -} diff --git a/crates/prep/src/openings.rs b/crates/prep/src/openings.rs deleted file mode 100644 index 7827354..0000000 --- a/crates/prep/src/openings.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Opening names: the table lives in the `chess-openings` crate (the game review uses it -//! too); here only what a report keeps of it. - -use std::collections::HashMap; - -pub use chess_openings::*; - -/// The openings a report refers to, each once, in the order they were first met. -#[derive(Default)] -pub struct OpeningSet { - pub list: Vec, - by_table: HashMap, -} - -impl OpeningSet { - /// The place of table entry `id` in [`OpeningSet::list`]. - pub fn intern(&mut self, id: usize) -> usize { - if let Some(&i) = self.by_table.get(&id) { - return i; - } - self.list.push(get(id).clone()); - self.by_table.insert(id, self.list.len() - 1); - self.list.len() - 1 - } -} - -#[cfg(test)] -mod tests { - use super::*; - use chess_core::shakmaty::Chess; - use chess_core::shakmaty::Position; - use chess_core::shakmaty::san::San; - - fn keys(moves: &[&str]) -> Vec { - let mut pos = Chess::default(); - let mut out = vec![key(&pos)]; - for s in moves { - let m = s.parse::().unwrap().to_move(&pos).unwrap(); - pos.play_unchecked(m); - out.push(key(&pos)); - } - out - } - - #[test] - fn a_set_keeps_each_opening_once() { - let mut set = OpeningSet::default(); - let id = deepest(&keys(&["e4", "c5"])).unwrap().1; - let other = deepest(&keys(&["d4"])).unwrap().1; - assert_eq!(set.intern(id), 0); - assert_eq!(set.intern(other), 1); - assert_eq!(set.intern(id), 0); - assert_eq!(set.list.len(), 2); - } -} diff --git a/crates/prep/src/period.rs b/crates/prep/src/period.rs deleted file mode 100644 index 4798015..0000000 --- a/crates/prep/src/period.rs +++ /dev/null @@ -1,250 +0,0 @@ -//! Which of the player's games a report takes: all, those of the last months (counted -//! back from his newest game, so an old database is not left empty), or his last games -//! of each colour. Games without a date are taken by «all» only; by number they count -//! as the oldest, in the order of the database (so a database without dates gives its -//! last records). When no game has a date, a period by months takes them all: it -//! cannot choose, and an empty report would explain nothing. - -use serde::{Deserialize, Serialize}; - -use chess_import::chessbase::base::Side; - -/// The games a report takes. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum Period { - #[default] - All, - /// Played within this many months before the player's newest game. - Months(u16), - /// The newest this many games of each colour. - Last(u32), -} - -/// One game of the player before the choice. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct PoolGame { - /// Record index in the database. - pub index: u32, - pub white: bool, - /// `yyyymmdd` (month or day 0 when unknown); 0: no date. - pub date: u32, -} - -/// What a period takes of the games of the colour(s) looked at. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct Chosen { - pub games: usize, - /// Of all the games: undated ones a period by months leaves out. - pub undated_out: usize, -} - -/// The latest day a PGN date can mean: «2026.??.??» → 2026.12.31, «2026.02.??» → -/// 2026.02.31 (only compared, never shown). -fn latest(date: u32) -> u32 { - match (date / 100 % 100, date % 100) { - (0, _) => date / 10000 * 10000 + 1231, - (_, 0) => date + 31, - _ => date, - } -} - -/// Today as `yyyymmdd` (UTC). -fn today() -> u32 { - let days = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_secs() / 86_400) as i64; - // Days since 1970 to the civil date (H. Hinnant's algorithm). - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let m = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = yoe + era * 400 + i64::from(m <= 2); - (y * 10000 + m * 100 + d) as u32 -} - -/// The date as the choice sees it: one after `today` is a typo («2206») and counts as -/// no date. -fn known(date: u32, today: u32) -> u32 { - if date > today { 0 } else { date } -} - -/// The date of the player's newest game as written (0: none dated): by its earliest -/// day, so that one game of «2026.??.??» does not move the period past the exactly -/// dated ones. -fn newest_at(pool: &[PoolGame], today: u32) -> u32 { - pool.iter().map(|g| known(g.date, today)).max().unwrap_or(0) -} - -/// The date of the player's newest game as written (0: none dated). -pub fn newest(pool: &[PoolGame]) -> u32 { - newest_at(pool, today()) -} - -/// The first day within `months` before the day `end` (`yyyymmdd`). -fn cutoff(end: u32, months: u16) -> u32 { - let (y, m, d) = (end / 10000, end / 100 % 100, end % 100); - let total = (y * 12 + m - 1).saturating_sub(u32::from(months)); - (total / 12) * 10000 + (total % 12 + 1) * 100 + d -} - -/// The games `period` takes: (record, the player had White), in record order. -pub fn choose(pool: &[PoolGame], period: Period) -> Vec<(u32, bool)> { - choose_at(pool, period, today()) -} - -/// [`choose`] on the day `today`. A partly known date is in a period when any day it -/// can mean is. -fn choose_at(pool: &[PoolGame], period: Period, today: u32) -> Vec<(u32, bool)> { - let mut out: Vec<(u32, bool)> = match period { - Period::All => pool.iter().map(|g| (g.index, g.white)).collect(), - Period::Months(months) => { - let newest = newest_at(pool, today); - if newest == 0 { - return choose_at(pool, Period::All, today); - } - let from = cutoff(latest(newest).min(today), months); - pool.iter() - .filter(|g| known(g.date, today) != 0 && latest(g.date) >= from) - .map(|g| (g.index, g.white)) - .collect() - } - Period::Last(n) => { - let mut out = Vec::new(); - for white in [true, false] { - let mut games: Vec<&PoolGame> = pool.iter().filter(|g| g.white == white).collect(); - // Newest first; the undated (0) last, later records counted newer. - games.sort_by(|a, b| { - known(b.date, today) - .cmp(&known(a.date, today)) - .then(b.index.cmp(&a.index)) - }); - out.extend(games.iter().take(n as usize).map(|g| (g.index, g.white))); - } - out - } - }; - out.sort_unstable(); - out -} - -/// How many games of `side` `period` takes, and the undated ones it leaves out. -pub fn count(pool: &[PoolGame], period: Period, side: Side) -> Chosen { - let of_side = |white: bool| match side { - Side::Any => true, - Side::White => white, - Side::Black => !white, - }; - let games = choose(pool, period) - .iter() - .filter(|(_, w)| of_side(*w)) - .count(); - let undated_out = match period { - Period::Months(_) if newest(pool) != 0 => pool - .iter() - .filter(|g| g.date == 0 && of_side(g.white)) - .count(), - _ => 0, - }; - Chosen { games, undated_out } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn g(index: u32, white: bool, date: u32) -> PoolGame { - PoolGame { index, white, date } - } - - #[test] - fn months_count_back_from_the_newest_game() { - let pool = [ - g(0, true, 20200105), - g(1, false, 20240301), - g(2, true, 20250228), - g(3, true, 20250301), - g(4, false, 0), - g(5, true, 20260301), - ]; - assert_eq!(cutoff(20260301, 12), 20250301); - assert_eq!(cutoff(20260115, 1), 20251215); - // Partly known dates. - assert_eq!(latest(20260000), 20261231); - assert_eq!(latest(20260200), 20260231); - let today = 20261031; - let year_only = [ - g(0, true, 20260000), - g(1, true, 20250301), - g(2, true, 20260700), - ]; - // From «2026.07.??», the newest: its last day 2026.07.31, three months back - // 2026.04.31; «2026» may be any day of the year, so it is in. - assert_eq!( - choose_at(&year_only, Period::Months(3), today), - vec![(0, true), (2, true)] - ); - // A typo from the future is not the newest game. - let typo = [ - g(0, true, 22060101), - g(1, true, 20260301), - g(2, true, 20250101), - ]; - assert_eq!(newest_at(&typo, today), 20260301); - assert_eq!(choose_at(&typo, Period::Months(6), today), vec![(1, true)]); - assert_eq!(choose_at(&typo, Period::Last(1), today), vec![(1, true)]); - // One game of «2026» does not push out the exactly dated newest ones. - let mixed = [ - g(0, true, 20260510), - g(1, true, 20260000), - g(2, true, 20260301), - ]; - assert_eq!(newest_at(&mixed, today), 20260510); - assert_eq!(choose_at(&mixed, Period::Months(3), today).len(), 3); - assert_eq!( - choose(&pool, Period::Months(12)), - vec![(3, true), (5, true)] - ); - assert_eq!( - choose(&pool, Period::Months(24)), - vec![(1, false), (2, true), (3, true), (5, true)] - ); - assert_eq!(choose(&pool, Period::All).len(), 6); - let c = count(&pool, Period::Months(24), Side::Black); - assert_eq!((c.games, c.undated_out), (1, 1)); - assert_eq!(count(&pool, Period::All, Side::Any).undated_out, 0); - // Nothing dated: a period by months takes all. - let undated = [g(0, true, 0), g(1, false, 0)]; - assert_eq!(choose(&undated, Period::Months(12)).len(), 2); - assert_eq!( - count(&undated, Period::Months(12), Side::Any).undated_out, - 0 - ); - } - - #[test] - fn the_last_games_of_each_colour() { - let pool = [ - g(0, true, 20200101), - g(1, true, 0), - g(2, true, 20230101), - g(3, false, 20240101), - g(4, true, 20220101), - g(5, false, 20190101), - ]; - assert_eq!( - choose(&pool, Period::Last(2)), - vec![(2, true), (3, false), (4, true), (5, false)] - ); - // Without dates: the last records. - let undated = [g(0, true, 0), g(1, true, 0), g(2, true, 0)]; - assert_eq!( - choose(&undated, Period::Last(2)), - vec![(1, true), (2, true)] - ); - assert_eq!(count(&pool, Period::Last(1), Side::Any).games, 2); - } -} diff --git a/crates/prep/src/players.rs b/crates/prep/src/players.rs deleted file mode 100644 index e9cb84b..0000000 --- a/crates/prep/src/players.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! The player: picked from the names of the database (never free text, so that -//! "Вафин" offers "Вафин Радель · 271" and "Вафина Раяна · 10" and the user chooses), -//! as one or several name ids when the database spells the same person in several -//! ways ("Kasparov, G." and "Kasparov, Garry"), and the player's games by colour. - -use std::sync::atomic::{AtomicBool, AtomicUsize}; - -use chess_import::Database; -use chess_import::chessbase::base::{Filter, NameFilter, Side, SortKey}; -use serde::{Deserialize, Serialize}; - -/// A name of the database that matches a query, with its number of games. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct Candidate { - pub id: u32, - pub name: String, - pub games: u32, -} - -/// Up to `limit` names containing every word of `query` (an initial with its full -/// stop finds the full name), names starting with the first word first, then by -/// number of games; and the number of all matches. -pub fn candidates(db: &Database, query: &str, limit: usize) -> (Vec, usize) { - let (list, total) = db.suggest_players(query, limit); - let list = list - .into_iter() - .map(|s| Candidate { - id: s.id, - name: s.name, - games: s.games, - }) - .collect(); - (list, total) -} - -/// The player of a report: one or more name ids of the database. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct Player { - pub ids: Vec, -} - -impl Player { - pub fn new(ids: impl IntoIterator) -> Player { - let mut ids: Vec = ids.into_iter().collect(); - ids.sort_unstable(); - ids.dedup(); - Player { ids } - } - - /// The names behind the ids, as the game list shows them. - pub fn names(&self, db: &Database) -> Vec { - self.ids - .iter() - .map(|&id| db.player_name(id).to_owned()) - .collect() - } -} - -/// The player's games for `side`: (record index, the player had White), in record -/// order. `None` when cancelled. -pub fn games_of( - db: &Database, - player: &Player, - side: Side, - cancel: &AtomicBool, -) -> Option> { - let mut out = Vec::new(); - for &id in &player.ids { - for (s, white) in [(Side::White, true), (Side::Black, false)] { - if side != Side::Any && side != s { - continue; - } - let filter = Filter { - player: NameFilter { - text: String::new(), - exact: Some(id), - }, - side: s, - games_only: true, - ..Filter::default() - }; - let found = db.query(&filter, SortKey::Number, true, &AtomicUsize::new(0), cancel)?; - out.extend(found.into_iter().map(|i| (i, white))); - } - } - // The same record with the same colour twice: two ids of the player on one side - // cannot happen, but two ids on both sides of one game can (a game against - // oneself in a spelling-merged list): it is kept once per colour. - out.sort_unstable(); - out.dedup(); - Some(out) -} diff --git a/crates/prep/src/tree.rs b/crates/prep/src/tree.rs deleted file mode 100644 index 50dc250..0000000 --- a/crates/prep/src/tree.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! The repertoire tree of one colour: the player's games laid over each other by -//! move order (it reads as a repertoire: 1.e4 c5 2.Nf3 …), every node carrying the -//! key of its position, so that two nodes reached by different move orders are seen -//! to be the same position (a transposition) and get the same opening name. - -use std::collections::HashMap; - -use serde::{Deserialize, Serialize}; - -use crate::games::{GameInfo, Tally}; -use crate::openings::{self, OpeningSet}; - -/// A position of the tree: the move that led to it from its parent, and the games -/// that went through it. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Node { - pub key: u64, - /// Half-moves from the start (0: the root). - pub ply: u8, - /// The move from the parent (empty for the root). - pub uci: String, - pub san: String, - pub parent: Option, - /// Most played first. - pub children: Vec, - pub tally: Tally, - /// The latest date among the games (PGN form; empty when none has one). - pub last_date: String, - /// Sum and number of the known opponent ratings, for the average. - pub elo_sum: u64, - pub elo_count: u32, - /// Games through the node: indices into [`crate::PrepReport::games`], in order. - pub games: Vec, - /// The same position is reached elsewhere in the tree by another move order. - pub transposition: bool, - /// The deepest named position on the path to the node - /// ([`crate::PrepReport::openings`]); `named` when it is this one. - pub opening: Option, - pub named: bool, -} - -impl Node { - pub fn average_elo(&self) -> Option { - (self.elo_count > 0).then(|| (self.elo_sum / u64::from(self.elo_count)) as u32) - } -} - -/// The tree of one colour; `nodes[0]` is the root (the start position). -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct Tree { - pub nodes: Vec, -} - -impl Tree { - /// Lays the lines of `games[g]` for `g` in `which` over each other, `plies` deep. - pub fn build( - games: &[GameInfo], - which: &[u32], - plies: usize, - openings: &mut OpeningSet, - ) -> Tree { - let mut tree = Tree { - nodes: vec![Node { - key: games - .first() - .and_then(|g| g.keys.first().copied()) - .unwrap_or_default(), - ply: 0, - uci: String::new(), - san: String::new(), - parent: None, - children: Vec::new(), - tally: Tally::default(), - last_date: String::new(), - elo_sum: 0, - elo_count: 0, - games: Vec::new(), - transposition: false, - opening: None, - named: false, - }], - }; - for &g in which { - let game = &games[g as usize]; - if let Some(&k) = game.keys.first() { - tree.nodes[0].key = k; - } - tree.count(0, g, game); - let mut at = 0usize; - for i in 0..game.ucis.len().min(plies) { - let next = match tree.nodes[at] - .children - .iter() - .find(|&&c| tree.nodes[c as usize].uci == game.ucis[i]) - { - Some(&c) => c as usize, - None => { - let key = game.keys[i + 1]; - // A more general name than the path's keeps the path's - // (see `openings::deepest`). - let parent = tree.nodes[at] - .opening - .map(|o| openings.list[o].name.clone()); - let named = openings::by_position(key).filter(|&id| { - parent.as_deref().is_none_or(|p| { - !openings::is_prefix_name(&openings::get(id).name, p) - }) - }); - let opening = named - .map(|id| openings.intern(id)) - .or(tree.nodes[at].opening); - tree.nodes.push(Node { - key, - ply: u8::try_from(i + 1).unwrap_or(u8::MAX), - uci: game.ucis[i].clone(), - san: game.sans[i].clone(), - parent: Some(at as u32), - children: Vec::new(), - tally: Tally::default(), - last_date: String::new(), - elo_sum: 0, - elo_count: 0, - games: Vec::new(), - transposition: false, - opening, - named: named.is_some(), - }); - let c = tree.nodes.len() - 1; - tree.nodes[at].children.push(c as u32); - c - } - }; - tree.count(next, g, game); - at = next; - } - } - // Most played first among the children. - let played: Vec = tree.nodes.iter().map(|n| n.tally.games).collect(); - for n in &mut tree.nodes { - n.children - .sort_by(|a, b| played[*b as usize].cmp(&played[*a as usize]).then(a.cmp(b))); - } - // Transpositions: one key in several nodes. - let mut seen: HashMap = HashMap::new(); - for n in &tree.nodes { - *seen.entry(n.key).or_default() += 1; - } - for n in &mut tree.nodes { - n.transposition = seen.get(&n.key).is_some_and(|c| *c > 1); - } - // One position, one name: the most precise of its move orders' names; a node - // is «named» where its name differs from its parent's. - let mut best: HashMap = HashMap::new(); - for n in tree.nodes.iter().filter(|n| n.transposition) { - if let Some(o) = n.opening { - let e = best.entry(n.key).or_insert(o); - if openings::is_prefix_name(&openings.list[*e].name, &openings.list[o].name) { - *e = o; - } - } - } - for i in 0..tree.nodes.len() { - if let Some(&o) = best.get(&tree.nodes[i].key) { - tree.nodes[i].opening = Some(o); - } - let parent = tree.nodes[i] - .parent - .and_then(|p| tree.nodes[p as usize].opening); - let name = |o: Option| o.map(|o| openings.list[o].name.as_str()); - tree.nodes[i].named = - tree.nodes[i].opening.is_some() && name(tree.nodes[i].opening) != name(parent); - } - tree - } - - /// The games through the position `key` by any move order (indices into - /// [`crate::PrepReport::games`], in order). - pub fn position_games(&self, key: u64) -> Vec { - let mut out: Vec = self - .nodes - .iter() - .filter(|n| n.key == key) - .flat_map(|n| n.games.iter().copied()) - .collect(); - out.sort_unstable(); - out.dedup(); - out - } - - /// The latest date among the games through the position `key`. - pub fn position_last_date(&self, key: u64) -> &str { - self.nodes - .iter() - .filter(|n| n.key == key) - .map(|n| n.last_date.as_str()) - .max_by_key(|d| chess_import::pgn_catalog::date_number(d)) - .unwrap_or("") - } - - fn count(&mut self, node: usize, g: u32, game: &GameInfo) { - let n = &mut self.nodes[node]; - n.tally.add(game.outcome); - n.games.push(g); - if game.opponent_elo > 0 { - n.elo_sum += u64::from(game.opponent_elo); - n.elo_count += 1; - } - if game.date_number() > chess_import::pgn_catalog::date_number(&n.last_date) { - n.last_date = game.date.clone(); - } - } - - /// The statistics of the position with `key` over all its move orders (the - /// sum of its nodes). - pub fn position_tally(&self, key: u64) -> Tally { - let mut t = Tally::default(); - for n in self.nodes.iter().filter(|n| n.key == key) { - t.games += n.tally.games; - t.wins += n.tally.wins; - t.draws += n.tally.draws; - t.losses += n.tally.losses; - } - t - } - - /// The path of moves to `node`, in SAN. - pub fn path(&self, node: usize) -> Vec<&str> { - let mut out = Vec::new(); - let mut at = Some(node); - while let Some(i) = at { - let n = &self.nodes[i]; - if n.parent.is_some() { - out.push(n.san.as_str()); - } - at = n.parent.map(|p| p as usize); - } - out.reverse(); - out - } -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use crate::games::Outcome; - use chess_core::shakmaty::Chess; - use chess_core::shakmaty::san::SanPlus; - use chess_import::position::{key, uci}; - - pub(crate) fn game( - index: u32, - white: bool, - moves: &[&str], - result: &str, - date: &str, - elo: u16, - ) -> GameInfo { - let mut pos = Chess::default(); - let (mut ucis, mut sans, mut keys) = (Vec::new(), Vec::new(), vec![key(&pos)]); - for s in moves { - let m = s.parse::().unwrap().san.to_move(&pos).unwrap(); - ucis.push(uci(&m).to_string()); - sans.push(SanPlus::from_move_and_play_unchecked(&mut pos, m).to_string()); - keys.push(key(&pos)); - } - GameInfo { - index, - white, - opponent: "Opp".into(), - opponent_elo: elo, - date: date.into(), - outcome: Outcome::of(result, white), - ucis, - sans, - keys, - opening: None, - named: None, - book: None, - } - } - - #[test] - fn the_tree_counts_games_and_marks_transpositions() { - let games = vec![ - game( - 0, - true, - &["d4", "d5", "Nf3", "Nf6"], - "1-0", - "2026.01.05", - 1500, - ), - game(1, true, &["Nf3", "d5", "d4", "Nf6"], "0-1", "2026.03.01", 0), - game(2, true, &["d4", "d5", "c4"], "1/2-1/2", "2025.12.31", 1700), - game(3, false, &["e4", "c5"], "0-1", "2026.02.02", 1600), - game( - 4, - true, - &["d4", "d5", "c4", "e6", "Nc3", "Nf6", "h3"], - "1-0", - "", - 0, - ), - ]; - let mut set = OpeningSet::default(); - let tree = Tree::build(&games, &[0, 1, 2], 20, &mut set); - let root = &tree.nodes[0]; - assert_eq!(root.tally.games, 3); - assert_eq!(root.last_date, "2026.03.01"); - assert_eq!(root.average_elo(), Some(1600)); - assert_eq!(root.games, vec![0, 1, 2]); - // 1.d4 (2 games) before 1.Nf3 (1 game). - let kids: Vec<&str> = root - .children - .iter() - .map(|&c| tree.nodes[c as usize].san.as_str()) - .collect(); - assert_eq!(kids, vec!["d4", "Nf3"]); - // The position after 1.d4 d5 2.Nf3 / 1.Nf3 d5 2.d4 is in two nodes. - let shared: Vec<&Node> = tree.nodes.iter().filter(|n| n.transposition).collect(); - let keys: Vec = shared.iter().map(|n| n.key).collect(); - assert_eq!(shared.len(), 4, "{keys:?}"); - let after_nf3 = tree - .nodes - .iter() - .find(|n| n.ply == 3 && n.san == "Nf3") - .unwrap(); - let after_d4 = tree - .nodes - .iter() - .find(|n| n.ply == 3 && n.san == "d4") - .unwrap(); - assert_eq!(after_nf3.key, after_d4.key); - assert_eq!(tree.position_tally(after_nf3.key).games, 2); - assert_eq!(tree.position_games(after_nf3.key), vec![0, 1]); - assert_eq!(tree.position_last_date(after_nf3.key), "2026.03.01"); - assert!( - !tree - .nodes - .iter() - .find(|n| n.san == "c4") - .unwrap() - .transposition - ); - assert_eq!( - tree.path(after_d4.parent.unwrap() as usize), - vec!["Nf3", "d5"] - ); - // Names: 1.d4 d5 2.Nf3 is named in the table, 2...Nf6 is too (Zukertort); - // both move orders get the same name. - assert!(after_nf3.named && after_d4.named); - assert_eq!(after_nf3.opening, after_d4.opening); - let name = &set.list[after_nf3.opening.unwrap()].name; - assert!(name.starts_with("Queen's Pawn Game"), "{name}"); - // A node that is not named (4.h3 in the Queen's Gambit Declined) inherits the - // name of its path. - let tree = Tree::build(&games, &[0, 1, 2, 4], 20, &mut set); - let h3 = tree.nodes.iter().find(|n| n.san == "h3").unwrap(); - assert!(!h3.named); - assert_eq!(h3.opening, tree.nodes[h3.parent.unwrap() as usize].opening); - assert!( - set.list[h3.opening.unwrap()] - .name - .starts_with("Queen's Gambit Declined") - ); - // Depth limit. - let short = Tree::build(&games, &[0, 1, 2], 1, &mut set); - assert_eq!(short.nodes.len(), 3); - } -} diff --git a/crates/trainer/Cargo.toml b/crates/trainer/Cargo.toml index 419cdce..132ca15 100644 --- a/crates/trainer/Cargo.toml +++ b/crates/trainer/Cargo.toml @@ -12,5 +12,4 @@ publish = false chess-core.workspace = true serde.workspace = true serde_json.workspace = true -web-time.workspace = true chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } diff --git a/crates/trainer/src/lib.rs b/crates/trainer/src/lib.rs index 8af37c7..0b4f12d 100644 --- a/crates/trainer/src/lib.rs +++ b/crates/trainer/src/lib.rs @@ -9,12 +9,9 @@ //! position and moves), so they survive edits of the game and are shared between games //! with the same line, in the file the app names ([`set_file`]). -pub mod repertoire; - use std::path::PathBuf; use std::sync::Mutex; -use std::time::Duration; -use web_time::Instant; +use std::time::{Duration, Instant}; use chess_core::shakmaty::fen::Fen; use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Move, Square}; diff --git a/crates/trainer/src/repertoire/acceptance_tests.rs b/crates/trainer/src/repertoire/acceptance_tests.rs deleted file mode 100644 index f317ebe..0000000 --- a/crates/trainer/src/repertoire/acceptance_tests.rs +++ /dev/null @@ -1,564 +0,0 @@ -use super::*; - -const DAY: i64 = 24 * 60 * 60; -const BASE: i64 = 1_800_000_000; - -fn item_key(index: usize) -> LearningItemKey { - LearningItemKey::local(format!("position-{index} w - -"), "e2e4") -} - -fn attempt( - key: &LearningItemKey, - id: impl Into, - event_type: TrainingEventType, - happened_at: i64, -) -> TrainingAttempt { - let actual_uci = match event_type { - TrainingEventType::IncorrectIndependent => "d2d4", - _ => "e2e4", - }; - TrainingAttempt { - user_id: key.user_id.clone(), - position_fen4: key.position_fen4.clone(), - client_attempt_id: id.into(), - session_id: "session-1".into(), - event_type, - expected_uci: key.expected_uci.clone(), - actual_uci: Some(actual_uci.into()), - response_time_ms: Some(750), - happened_at, - } -} - -fn record(item: &mut LearningItem, id: &str, event_type: TrainingEventType, happened_at: i64) { - apply_attempt( - item, - &attempt(&item.key, id, event_type, happened_at), - &SrsSettings::default(), - ) - .unwrap(); -} - -fn learnt_item(index: usize, reviewed_at: i64, next_review_at: i64) -> LearningItem { - let mut item = LearningItem::new(item_key(index)); - item.introduced = true; - item.correct_streak = 3; - item.correct_count = 3; - item.last_review_at = Some(reviewed_at); - item.last_correct_at = Some(reviewed_at); - item.next_review_at = Some(next_review_at); - item.previous_interval_seconds = Some(DAY); - item -} - -#[test] -fn at_02_first_independent_correct_introduces_learning_for_one_day() { - let mut item = LearningItem::new(item_key(0)); - record( - &mut item, - "at-02", - TrainingEventType::CorrectIndependent, - BASE, - ); - - assert!(item.introduced); - assert!(item.is_learning()); - assert!(!item.is_learnt()); - assert_eq!(item.correct_streak, 1); - assert_eq!(item.wrong_streak, 0); - assert_eq!(item.correct_count, 1); - assert_eq!(item.wrong_count, 0); - assert_eq!(item.last_review_at, Some(BASE)); - assert_eq!(item.last_correct_at, Some(BASE)); - assert_eq!(item.previous_interval_seconds, Some(DAY)); - assert_eq!(item.next_review_at, Some(BASE + DAY)); -} - -#[test] -fn at_03_third_independent_correct_is_learnt_and_still_scheduled() { - let mut item = LearningItem::new(item_key(0)); - for (id, at) in [("at-03-a", BASE), ("at-03-b", BASE + DAY)] { - record(&mut item, id, TrainingEventType::CorrectIndependent, at); - } - let third = BASE + 3 * DAY; - record( - &mut item, - "at-03-c", - TrainingEventType::CorrectIndependent, - third, - ); - - assert_eq!(item.correct_streak, 3); - assert!(item.is_learnt()); - assert!(!item.is_learning()); - assert_eq!(item.previous_interval_seconds, Some(4 * DAY)); - assert_eq!(item.next_review_at, Some(third + 4 * DAY)); -} - -#[test] -fn at_04_wrong_after_learnt_resets_streak_and_schedules_thirty_seconds() { - let mut item = LearningItem::new(item_key(0)); - for (id, at) in [ - ("at-04-a", BASE), - ("at-04-b", BASE + DAY), - ("at-04-c", BASE + 3 * DAY), - ] { - record(&mut item, id, TrainingEventType::CorrectIndependent, at); - } - let wrong_at = BASE + 7 * DAY; - record( - &mut item, - "at-04-wrong", - TrainingEventType::IncorrectIndependent, - wrong_at, - ); - - assert_eq!(item.correct_streak, 0); - assert_eq!(item.wrong_streak, 1); - assert!(item.is_learning()); - assert_eq!(item.last_correct_at, None); - assert_eq!(item.next_review_at, Some(wrong_at + 30)); - assert_eq!(item.last_wrong_move_uci.as_deref(), Some("d2d4")); - assert_eq!(item.last_wrong_at, Some(wrong_at)); - assert_eq!( - item.wrong_move_histogram.get("d2d4"), - Some(&WrongMoveStats { - count: 1, - last_at: wrong_at, - }) - ); -} - -#[test] -fn at_05_replay_after_error_does_not_change_knowledge_or_due() { - let mut item = LearningItem::new(item_key(0)); - record( - &mut item, - "at-05-wrong", - TrainingEventType::IncorrectIndependent, - BASE, - ); - let before = item.clone(); - record( - &mut item, - "at-05-replay", - TrainingEventType::ReplayAfterError, - BASE + 1, - ); - - assert_eq!(item, before); - assert_eq!(item.independent_attempt_count(), 1); - assert_eq!(item.correct_count, 0); - assert_eq!(item.next_review_at, Some(BASE + 30)); - assert_eq!(item.independent_response_times_ms, [750]); -} - -#[test] -fn at_06_preview_introduces_unseen_without_independent_success() { - let mut item = LearningItem::new(item_key(0)); - record(&mut item, "at-06", TrainingEventType::Previewed, BASE); - - assert!(item.introduced); - assert!(item.is_learning()); - assert_eq!(item.correct_streak, 0); - assert_eq!(item.wrong_streak, 0); - assert_eq!(item.independent_attempt_count(), 0); - assert_eq!(item.accuracy_percent(), None); - assert_eq!(item.last_correct_at, None); - assert_eq!(item.last_review_at, Some(BASE)); - assert_eq!(item.next_review_at, Some(BASE + 60)); - assert!(item.independent_response_times_ms.is_empty()); -} - -#[test] -fn at_08_learnt_item_is_also_due() { - let mut item = LearningItem::new(item_key(0)); - for (id, at) in [ - ("at-08-a", BASE), - ("at-08-b", BASE + DAY), - ("at-08-c", BASE + 3 * DAY), - ] { - record(&mut item, id, TrainingEventType::CorrectIndependent, at); - } - let now = item.next_review_at.unwrap(); - let summary = aggregate(std::slice::from_ref(&item), now, &SrsSettings::default()); - - assert_eq!(summary.total, 1); - assert_eq!(summary.learning, 0); - assert_eq!(summary.learnt, 1); - assert_eq!(summary.due, 1); - assert_eq!(summary.uncertain, 0); - assert_invariants(&summary); -} - -#[test] -fn at_12_accuracy_is_weighted_independent_accuracy_not_learning_status() { - let mut item = LearningItem::new(item_key(0)); - for index in 0..7 { - record( - &mut item, - &format!("at-12-correct-{index}"), - TrainingEventType::CorrectIndependent, - BASE + index, - ); - } - for index in 0..3 { - record( - &mut item, - &format!("at-12-wrong-{index}"), - TrainingEventType::IncorrectIndependent, - BASE + 7 + index, - ); - } - let summary = aggregate( - std::slice::from_ref(&item), - BASE + 10, - &SrsSettings::default(), - ); - - assert_eq!(item.correct_count, 7); - assert_eq!(item.wrong_count, 3); - assert_eq!(item.independent_attempt_count(), 10); - assert!((item.accuracy_percent().unwrap() - 70.0).abs() < f64::EPSILON); - assert!((summary.accuracy_percent.unwrap() - 70.0).abs() < f64::EPSILON); - assert_eq!(summary.accuracy_attempts, 10); - assert!(item.is_learning()); -} - -#[test] -fn at_13_accuracy_is_absent_without_independent_attempts() { - let item = LearningItem::new(item_key(0)); - let summary = aggregate(std::slice::from_ref(&item), BASE, &SrsSettings::default()); - - assert_eq!(item.accuracy_percent(), None); - assert_eq!(summary.accuracy_percent, None); - assert_eq!(summary.accuracy_attempts, 0); - assert_eq!(summary.repertoire_status, RepertoireStatus::NotStarted); -} - -#[test] -fn at_16_empty_scope_has_empty_status_and_no_percentages() { - let items: Vec = Vec::new(); - let summary = aggregate(items.iter(), BASE, &SrsSettings::default()); - - assert_eq!(summary.total, 0); - assert_eq!(summary.repertoire_status, RepertoireStatus::Empty); - assert_eq!(summary.next_due_at, None); - for percentage in [ - summary.coverage_percent, - summary.learnt_percent, - summary.confident_percent, - summary.learning_percent, - summary.unseen_percent, - summary.uncertain_of_learnt_percent, - summary.due_of_introduced_percent, - summary.accuracy_percent, - ] { - assert_eq!(percentage, None); - } - assert_invariants(&summary); -} - -#[test] -fn at_28_all_learnt_with_due_is_not_confirmed_current() { - let now = BASE + 20 * DAY; - let items: Vec<_> = (0..100) - .map(|index| { - let next = if index < 3 { now } else { now + DAY }; - learnt_item(index, now - DAY, next) - }) - .collect(); - let summary = aggregate(items.iter(), now, &SrsSettings::default()); - - assert_eq!(summary.total, 100); - assert_eq!(summary.learnt, 100); - assert_eq!(summary.due, 3); - assert_eq!(summary.next_due_at, None); - assert_eq!(summary.repertoire_status, RepertoireStatus::AllLearnt); - assert_invariants(&summary); -} - -#[test] -fn at_29_all_learnt_without_due_or_uncertain_is_confirmed_current() { - let now = BASE + 20 * DAY; - let items: Vec<_> = (0..100) - .map(|index| learnt_item(index, now - DAY, now + DAY)) - .collect(); - let summary = aggregate(items.iter(), now, &SrsSettings::default()); - - assert_eq!(summary.total, 100); - assert_eq!(summary.learnt, 100); - assert_eq!(summary.due, 0); - assert_eq!(summary.uncertain, 0); - assert_eq!(summary.next_due_at, Some(now + DAY)); - assert_eq!( - summary.repertoire_status, - RepertoireStatus::ConfirmedCurrent - ); - assert_invariants(&summary); -} - -#[test] -fn correct_after_four_days_schedules_eight_days() { - let settings = SrsSettings::default(); - let mut item = LearningItem::new(item_key(0)); - apply_independent_correct(&mut item, BASE, &settings); - apply_independent_correct(&mut item, BASE + 4 * DAY, &settings); - - assert_eq!(item.previous_interval_seconds, Some(8 * DAY)); - assert_eq!(item.next_review_at, Some(BASE + 12 * DAY)); -} - -#[test] -fn growth_interval_has_explicit_minimum_and_maximum() { - let settings = SrsSettings { - min_practical_interval_seconds: 3_600, - max_interval_seconds: 10 * DAY, - ..SrsSettings::default() - }; - let mut minimum = LearningItem::new(item_key(0)); - apply_independent_correct(&mut minimum, BASE, &settings); - apply_independent_correct(&mut minimum, BASE + 1, &settings); - assert_eq!(minimum.previous_interval_seconds, Some(3_600)); - assert_eq!(minimum.next_review_at, Some(BASE + 1 + 3_600)); - - let mut maximum = LearningItem::new(item_key(1)); - apply_independent_correct(&mut maximum, BASE, &settings); - apply_independent_correct(&mut maximum, BASE + 10 * DAY, &settings); - assert_eq!(maximum.previous_interval_seconds, Some(10 * DAY)); - assert_eq!(maximum.next_review_at, Some(BASE + 20 * DAY)); -} - -#[test] -fn preview_preserves_two_correct_streak_and_growth_base() { - let settings = SrsSettings::default(); - let mut item = LearningItem::new(item_key(0)); - apply_independent_correct(&mut item, BASE, &settings); - apply_independent_correct(&mut item, BASE + DAY, &settings); - let previous_interval = item.previous_interval_seconds; - let preview_at = BASE + 2 * DAY; - apply_preview(&mut item, preview_at, &settings); - - assert_eq!(item.correct_streak, 2); - assert_eq!(item.correct_count, 2); - assert_eq!(item.wrong_count, 0); - assert_eq!(item.wrong_streak, 0); - assert_eq!(item.last_correct_at, Some(BASE + DAY)); - assert_eq!(item.previous_interval_seconds, previous_interval); - assert_eq!(item.last_review_at, Some(preview_at)); - assert_eq!(item.next_review_at, Some(preview_at + 60)); -} - -#[test] -fn auto_context_and_illegal_move_create_no_independent_attempt() { - let settings = SrsSettings::default(); - let key = item_key(0); - let mut data = LearningData::default(); - assert_eq!( - data.apply_attempt( - attempt(&key, "illegal", TrainingEventType::IllegalMove, BASE), - &settings, - ), - Ok(AttemptApplication::Applied) - ); - assert_eq!( - data.apply_attempt( - attempt(&key, "auto", TrainingEventType::AutoContext, BASE + 1), - &settings, - ), - Ok(AttemptApplication::Applied) - ); - - let item = data.item(&key).unwrap(); - assert_eq!(item, &LearningItem::new(key)); - assert_eq!(item.independent_attempt_count(), 0); - assert_eq!(item.accuracy_percent(), None); - assert!(item.independent_response_times_ms.is_empty()); - assert_eq!(data.attempts.len(), 2); -} - -#[test] -fn duplicate_client_attempt_id_changes_state_only_once() { - let settings = SrsSettings::default(); - let key = item_key(0); - let first = attempt( - &key, - "duplicate-id", - TrainingEventType::CorrectIndependent, - BASE, - ); - let mut data = LearningData::default(); - assert_eq!( - data.apply_attempt(first.clone(), &settings), - Ok(AttemptApplication::Applied) - ); - let before = data.item(&key).unwrap().clone(); - assert_eq!( - data.apply_attempt(first, &settings), - Ok(AttemptApplication::Duplicate) - ); - - assert_eq!(data.item(&key), Some(&before)); - assert_eq!(data.item(&key).unwrap().correct_count, 1); - assert_eq!(data.item(&key).unwrap().correct_streak, 1); - assert_eq!(data.attempts.len(), 1); -} - -#[test] -fn uncertain_uses_strict_greater_of_grace_boundaries() { - let settings = SrsSettings::default(); - let mut item = learnt_item(0, BASE - 4 * DAY, BASE); - item.previous_interval_seconds = Some(4 * DAY); - assert!(!is_uncertain(&item, BASE + 7 * DAY, &settings)); - assert!(is_uncertain(&item, BASE + 7 * DAY + 1, &settings)); - - item.previous_interval_seconds = Some(40 * DAY); - assert!(!is_uncertain(&item, BASE + 7 * DAY + 1, &settings)); - assert!(!is_uncertain(&item, BASE + 10 * DAY, &settings)); - assert!(is_uncertain(&item, BASE + 10 * DAY + 1, &settings)); - - item.correct_streak = 2; - assert!(!is_uncertain(&item, BASE + 100 * DAY, &settings)); -} - -#[test] -fn aggregate_deduplicates_keys_and_weights_accuracy_once() { - let mut first = LearningItem::new(item_key(0)); - first.correct_count = 7; - first.wrong_count = 3; - let second = LearningItem::new(item_key(1)); - let items = [first.clone(), first, second]; - let summary = aggregate(items.iter(), BASE, &SrsSettings::default()); - - assert_eq!(summary.total, 2); - assert_eq!(summary.unseen, 2); - assert_eq!(summary.accuracy_correct, 7); - assert_eq!(summary.accuracy_wrong, 3); - assert_eq!(summary.accuracy_attempts, 10); - assert!((summary.accuracy_percent.unwrap() - 70.0).abs() < f64::EPSILON); - assert_invariants(&summary); -} - -#[test] -fn learning_data_json_round_trip_preserves_event_types_and_state() { - let settings = SrsSettings::default(); - let key = item_key(0); - let mut data = LearningData::default(); - data.apply_attempt( - attempt( - &key, - "serde-correct", - TrainingEventType::CorrectIndependent, - BASE, - ), - &settings, - ) - .unwrap(); - data.apply_attempt( - attempt( - &key, - "serde-replay", - TrainingEventType::ReplayAfterError, - BASE + 1, - ), - &settings, - ) - .unwrap(); - - let json = serde_json::to_string(&data).unwrap(); - assert!(json.contains("CORRECT_INDEPENDENT")); - assert!(json.contains("REPLAY_AFTER_ERROR")); - let restored: LearningData = serde_json::from_str(&json).unwrap(); - assert_eq!(restored, data); -} - -#[test] -fn mixed_event_sequence_preserves_aggregate_invariants() { - let events = [ - TrainingEventType::CorrectIndependent, - TrainingEventType::IncorrectIndependent, - TrainingEventType::Previewed, - TrainingEventType::ReplayAfterError, - TrainingEventType::AutoContext, - TrainingEventType::IllegalMove, - ]; - let keys: Vec<_> = (0..7).map(item_key).collect(); - let settings = SrsSettings::default(); - let mut data = LearningData::default(); - for key in &keys { - data.ensure_item(key.clone()); - } - - for step in 0..150_i64 { - let key = &keys[(step as usize * 3 + step as usize / 7) % keys.len()]; - let happened_at = BASE + step * 45; - let event = attempt( - key, - format!("property-{step}"), - events[step as usize % events.len()], - happened_at, - ); - assert_eq!( - data.apply_attempt(event.clone(), &settings), - Ok(AttemptApplication::Applied) - ); - if step % 9 == 0 { - assert_eq!( - data.apply_attempt(event, &settings), - Ok(AttemptApplication::Duplicate) - ); - } - - let as_of = happened_at + (step % 4) * 8 * DAY; - let global = aggregate(data.items.iter().chain(data.items.iter()), as_of, &settings); - assert_invariants(&global); - let left = aggregate(data.items.iter().take(4), as_of, &settings); - let right = aggregate(data.items.iter().skip(3), as_of, &settings); - assert!(global.total <= left.total + right.total); - } -} - -fn assert_invariants(summary: &LearningAggregate) { - assert_eq!( - summary.total, - summary.unseen + summary.learning + summary.learnt - ); - assert!(summary.uncertain <= summary.learnt); - assert!(summary.learnt_confident <= summary.learnt); - assert_eq!(summary.learnt_confident, summary.learnt - summary.uncertain); - assert!(summary.due <= summary.learning + summary.learnt); - assert_eq!( - summary.accuracy_attempts, - summary.accuracy_correct + summary.accuracy_wrong - ); - for percentage in [ - summary.coverage_percent, - summary.learnt_percent, - summary.confident_percent, - summary.learning_percent, - summary.unseen_percent, - summary.uncertain_of_learnt_percent, - summary.due_of_introduced_percent, - summary.accuracy_percent, - ] - .into_iter() - .flatten() - { - assert!(percentage.is_finite()); - assert!((0.0..=100.0).contains(&percentage)); - } - if let (Some(coverage), Some(learnt), Some(confident)) = ( - summary.coverage_percent, - summary.learnt_percent, - summary.confident_percent, - ) { - assert!(coverage >= learnt); - assert!(learnt >= confident); - } else { - assert_eq!(summary.total, 0); - } - if let Some(next) = summary.next_due_at { - assert!(summary.due < summary.total); - assert!(next > 0); - } -} diff --git a/crates/trainer/src/repertoire/advanced_tests.rs b/crates/trainer/src/repertoire/advanced_tests.rs deleted file mode 100644 index cdc0c40..0000000 --- a/crates/trainer/src/repertoire/advanced_tests.rs +++ /dev/null @@ -1,142 +0,0 @@ -use chess_core::{Game, NodeId}; - -use super::*; - -fn repertoire(pgn: &str) -> Repertoire { - let mut library = Library::default(); - let id = library - .create("Scope", &chess_core::parse_str(pgn).game) - .unwrap(); - library.repertoire(&id).unwrap().clone() -} - -#[test] -fn simultaneous_writers_cannot_overwrite_the_same_revision() { - let path = std::env::temp_dir().join(format!("cp-trainer-race-{}.json", std::process::id())); - let _ = std::fs::remove_file(&path); - let barrier = std::sync::Arc::new(std::sync::Barrier::new(8)); - let writers: Vec<_> = (0..8) - .map(|i| { - let path = path.clone(); - let barrier = barrier.clone(); - std::thread::spawn(move || { - let mut library = Library::default(); - library.create_empty(format!("Writer {i}")).unwrap(); - barrier.wait(); - LibraryStore::new(path).save(&mut library) - }) - }) - .collect(); - let results: Vec<_> = writers - .into_iter() - .map(|thread| thread.join().unwrap()) - .collect(); - assert_eq!(results.iter().filter(|r| r.is_ok()).count(), 1); - assert_eq!( - results - .iter() - .filter(|r| matches!(r, Err(StoreError::Conflict { .. }))) - .count(), - 7 - ); - assert_eq!( - LibraryStore::new(&path).load().unwrap().repertoires.len(), - 1 - ); - std::fs::remove_file(path).unwrap(); -} - -#[test] -fn previous_both_move_keys_migrate_to_position_statistics_without_data_loss() { - let path = - std::env::temp_dir().join(format!("cp-trainer-migration-{}.json", std::process::id())); - let rep = repertoire("1. e4 (1. d4) *"); - let position_fen4 = fen4(Game::new().start().position()); - let entries = ["e2e4", "d2d4"].map(|uci| { - let mut entry = MoveStats::new(MoveKey { - repertoire_id: rep.id.clone(), - mode: TrainingMode::Both, - position_fen4: position_fen4.clone(), - expected_uci: uci.into(), - }); - entry.attempts = 2; - entry.correct = 1; - entry.wrong = 1; - entry.hints = 1; - entry - }); - let mut data = StatsData::default(); - data.move_stats = entries.into(); - std::fs::write(&path, serde_json::to_vec(&data).unwrap()).unwrap(); - let store = StatsStore::new(&path); - let mut migrated = store.load().unwrap(); - assert_eq!(migrated.move_stats.len(), 1); - let entry = &migrated.move_stats[0]; - assert!(entry.key.expected_uci.is_empty()); - assert_eq!( - (entry.attempts, entry.correct, entry.wrong, entry.hints), - (4, 2, 2, 2) - ); - store.save(&mut migrated).unwrap(); - assert_eq!(store.load().unwrap().move_stats, migrated.move_stats); - std::fs::remove_file(path).unwrap(); -} - -#[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; - let source = chess_core::parse_str( - "1. Nf3 d5 2. d4 -- {teaching pass} 3. c4 $1 (3. e4 {side branch} $2) *", - ) - .game; - let original = source.canonical_tree(); - let mut library = Library::default(); - let id = library.create("Exact graft", &base).unwrap(); - let report = library.add_game(&id, &source).unwrap(); - assert_eq!(report.added_nodes, 3); - let merged = library.repertoire(&id).unwrap().game(); - let main_end = *merged.mainline().last().unwrap(); - assert!(merged.children(main_end).is_empty()); - let alternative = merged.children(NodeId::ROOT)[1]; - let d5 = merged.children(alternative)[0]; - let d4 = merged.children(d5)[0]; - let null = merged.children(d4)[0]; - assert!(merged.game_move(null).unwrap().is_null()); - assert_eq!( - merged.node(null).unwrap().comments_after(), - &["teaching pass"] - ); - let c4 = merged.children(null)[0]; - assert_eq!(merged.game_move(c4).unwrap().san, "c4"); - assert_eq!(merged.node(c4).unwrap().nags()[0].0, 1); - assert_eq!(merged.start().fen(), source.start().fen()); - // Match each complete source path, including every RAV under the null move. - // Compare position counters and annotations as well as moves: remapping the - // graft must not retain any IDs from the temporary planning document. - for source_id in source.attached_nodes() { - let mut target_id = NodeId::ROOT; - for step in source.path(source_id).into_iter().skip(1) { - let kind = source.game_move(step).unwrap().kind; - target_id = merged - .children(target_id) - .iter() - .copied() - .find(|id| merged.game_move(*id).is_some_and(|mv| mv.kind == kind)) - .expect("the complete source path survives the graft"); - } - let expected = source.node(source_id).unwrap(); - let actual = merged.node(target_id).unwrap(); - assert_eq!(actual.comments_before(), expected.comments_before()); - assert_eq!(actual.comments_after(), expected.comments_after()); - assert_eq!(actual.nags(), expected.nags()); - assert_eq!(actual.unparsed(), expected.unparsed()); - assert_eq!(merged.fen(target_id), source.fen(source_id)); - } - assert_eq!(source.canonical_tree(), original); - let canonical = merged.canonical_tree(); - assert_eq!(library.add_game(&id, &source).unwrap().added_nodes, 0); - assert_eq!( - library.repertoire(&id).unwrap().game().canonical_tree(), - canonical - ); -} diff --git a/crates/trainer/src/repertoire/aggregate.rs b/crates/trainer/src/repertoire/aggregate.rs deleted file mode 100644 index 1ef93fa..0000000 --- a/crates/trainer/src/repertoire/aggregate.rs +++ /dev/null @@ -1,455 +0,0 @@ -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use super::learning::LearningItem; -use super::srs::SrsSettings; - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum RepertoireStatus { - NotStarted, - InProgress, - AllLearnt, - ConfirmedCurrent, - #[default] - Empty, -} - -#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] -pub struct LearningAggregate { - pub total: usize, - pub unseen: usize, - pub learning: usize, - pub learnt: usize, - pub uncertain: usize, - pub learnt_confident: usize, - pub due: usize, - pub next_due_at: Option, - pub coverage_percent: Option, - pub learnt_percent: Option, - pub confident_percent: Option, - pub learning_percent: Option, - pub unseen_percent: Option, - pub uncertain_of_learnt_percent: Option, - pub due_of_introduced_percent: Option, - pub accuracy_correct: u64, - pub accuracy_wrong: u64, - pub accuracy_attempts: u64, - pub accuracy_percent: Option, - pub repertoire_status: RepertoireStatus, -} - -/// Uncertain starts strictly after the grace boundary, never at the boundary itself. -pub fn is_uncertain(item: &LearningItem, now: i64, settings: &SrsSettings) -> bool { - if !item.is_learnt() { - return false; - } - let Some(next_review_at) = item.next_review_at else { - return false; - }; - let interval_grace = item.previous_interval_seconds.unwrap_or(0).max(0) - / i64::from(settings.uncertain_interval_divisor.max(1)); - let grace = settings - .uncertain_min_grace_seconds - .max(0) - .max(interval_grace); - now > next_review_at.saturating_add(grace) -} - -/// Counts each full LearningItemKey once, even if several scopes supplied the same item. -pub fn aggregate<'a>( - items: impl IntoIterator, - now: i64, - settings: &SrsSettings, -) -> LearningAggregate { - let mut unique = BTreeMap::new(); - for item in items { - unique.entry(&item.key).or_insert(item); - } - - let mut summary = LearningAggregate::default(); - for item in unique.into_values() { - summary.total = summary.total.saturating_add(1); - if item.is_unseen() { - summary.unseen = summary.unseen.saturating_add(1); - } else if item.is_learnt() { - summary.learnt = summary.learnt.saturating_add(1); - } else { - summary.learning = summary.learning.saturating_add(1); - } - if is_uncertain(item, now, settings) { - summary.uncertain = summary.uncertain.saturating_add(1); - } - if item.is_due(now) { - summary.due = summary.due.saturating_add(1); - } - if item.introduced - && let Some(next) = item.next_review_at - && next > now - { - summary.next_due_at = Some(summary.next_due_at.map_or(next, |old| old.min(next))); - } - summary.accuracy_correct = summary.accuracy_correct.saturating_add(item.correct_count); - summary.accuracy_wrong = summary.accuracy_wrong.saturating_add(item.wrong_count); - } - - if summary.due > 0 { - summary.next_due_at = None; - } - summary.learnt_confident = summary.learnt.saturating_sub(summary.uncertain); - summary.accuracy_attempts = summary - .accuracy_correct - .saturating_add(summary.accuracy_wrong); - if summary.total > 0 { - summary.coverage_percent = Some(percent(summary.total - summary.unseen, summary.total)); - summary.learnt_percent = Some(percent(summary.learnt, summary.total)); - summary.confident_percent = Some(percent(summary.learnt_confident, summary.total)); - summary.learning_percent = Some(percent(summary.learning, summary.total)); - summary.unseen_percent = Some(percent(summary.unseen, summary.total)); - } - if summary.learnt > 0 { - summary.uncertain_of_learnt_percent = Some(percent(summary.uncertain, summary.learnt)); - } - let introduced = summary.total.saturating_sub(summary.unseen); - if introduced > 0 { - summary.due_of_introduced_percent = Some(percent(summary.due, introduced)); - } - if summary.accuracy_attempts > 0 { - summary.accuracy_percent = - Some(100.0 * summary.accuracy_correct as f64 / summary.accuracy_attempts as f64); - } - summary.repertoire_status = if summary.total == 0 { - RepertoireStatus::Empty - } else if summary.unseen == summary.total { - RepertoireStatus::NotStarted - } else if summary.learnt == summary.total && summary.uncertain == 0 && summary.due == 0 { - RepertoireStatus::ConfirmedCurrent - } else if summary.learnt == summary.total { - RepertoireStatus::AllLearnt - } else { - RepertoireStatus::InProgress - }; - for violation in learning_invariant_violations(&summary) { - eprintln!( - "training: learning aggregate invariant violation: {violation}; summary={summary:?}" - ); - } - summary -} - -pub fn learning_invariant_violations(summary: &LearningAggregate) -> Vec<&'static str> { - let mut violations = Vec::new(); - let classified_total = summary - .unseen - .checked_add(summary.learning) - .and_then(|total| total.checked_add(summary.learnt)); - if classified_total != Some(summary.total) { - violations.push("total != unseen + learning + learnt"); - } - if summary.uncertain > summary.learnt { - violations.push("uncertain > learnt"); - } - if summary.learnt.checked_sub(summary.uncertain) != Some(summary.learnt_confident) { - violations.push("learnt_confident != learnt - uncertain"); - } - if summary.due > summary.learning.saturating_add(summary.learnt) { - violations.push("due > learning + learnt"); - } - if let (Some(coverage), Some(learnt)) = (summary.coverage_percent, summary.learnt_percent) - && is_valid_percentage(coverage) - && is_valid_percentage(learnt) - && coverage < learnt - { - violations.push("coverage_percent < learnt_percent"); - } - if let (Some(learnt), Some(confident)) = (summary.learnt_percent, summary.confident_percent) - && is_valid_percentage(learnt) - && is_valid_percentage(confident) - && learnt < confident - { - violations.push("learnt_percent < confident_percent"); - } - for (percentage, violation) in [ - ( - summary.coverage_percent, - "coverage_percent is not finite or is outside 0..=100", - ), - ( - summary.learnt_percent, - "learnt_percent is not finite or is outside 0..=100", - ), - ( - summary.confident_percent, - "confident_percent is not finite or is outside 0..=100", - ), - ( - summary.learning_percent, - "learning_percent is not finite or is outside 0..=100", - ), - ( - summary.unseen_percent, - "unseen_percent is not finite or is outside 0..=100", - ), - ( - summary.uncertain_of_learnt_percent, - "uncertain_of_learnt_percent is not finite or is outside 0..=100", - ), - ( - summary.due_of_introduced_percent, - "due_of_introduced_percent is not finite or is outside 0..=100", - ), - ( - summary.accuracy_percent, - "accuracy_percent is not finite or is outside 0..=100", - ), - ] { - if percentage.is_some_and(|value| !is_valid_percentage(value)) { - violations.push(violation); - } - } - violations -} - -pub fn global_total_invariant_violation( - global_total: usize, - repertoire_totals: impl IntoIterator, -) -> Option<&'static str> { - let mut repertoire_total = 0usize; - for total in repertoire_totals { - let Some(next) = repertoire_total.checked_add(total) else { - return Some("repertoire_totals sum overflow"); - }; - repertoire_total = next; - } - (global_total > repertoire_total).then_some("global_total > sum(repertoire_totals)") -} - -pub fn log_global_total_invariant( - global_total: usize, - repertoire_totals: impl IntoIterator, -) { - if let Some(violation) = global_total_invariant_violation(global_total, repertoire_totals) { - eprintln!( - "training: global total invariant violation: {violation}; global_total={global_total}" - ); - } -} - -fn is_valid_percentage(value: f64) -> bool { - value.is_finite() && (0.0..=100.0).contains(&value) -} - -fn percent(numerator: usize, denominator: usize) -> f64 { - 100.0 * numerator as f64 / denominator as f64 -} - -#[cfg(test)] -mod tests { - use super::super::learning::LearningItemKey; - use super::*; - - fn valid_summary() -> LearningAggregate { - LearningAggregate { - total: 10, - unseen: 2, - learning: 3, - learnt: 5, - uncertain: 2, - learnt_confident: 3, - due: 4, - next_due_at: None, - coverage_percent: Some(80.0), - learnt_percent: Some(50.0), - confident_percent: Some(30.0), - learning_percent: Some(30.0), - unseen_percent: Some(20.0), - uncertain_of_learnt_percent: Some(40.0), - due_of_introduced_percent: Some(50.0), - accuracy_correct: 7, - accuracy_wrong: 3, - accuracy_attempts: 10, - accuracy_percent: Some(70.0), - repertoire_status: RepertoireStatus::InProgress, - } - } - - fn assert_has_violation(summary: &LearningAggregate, expected: &'static str) { - let violations = learning_invariant_violations(summary); - assert!( - violations.contains(&expected), - "missing {expected:?} in {violations:?}" - ); - } - - #[test] - fn valid_mixed_summary_has_no_invariant_violations() { - let mut summary = valid_summary(); - assert!(learning_invariant_violations(&summary).is_empty()); - - summary.accuracy_percent = None; - assert!(learning_invariant_violations(&summary).is_empty()); - } - - #[test] - fn detects_count_invariant_violations() { - let mut summary = valid_summary(); - summary.total = 11; - assert_has_violation(&summary, "total != unseen + learning + learnt"); - - let mut summary = valid_summary(); - summary.uncertain = 6; - assert_has_violation(&summary, "uncertain > learnt"); - - let mut summary = valid_summary(); - summary.learnt_confident = 4; - assert_has_violation(&summary, "learnt_confident != learnt - uncertain"); - - let mut summary = valid_summary(); - summary.due = 9; - assert_has_violation(&summary, "due > learning + learnt"); - } - - #[test] - fn detects_percentage_ordering_violations() { - let mut summary = valid_summary(); - summary.coverage_percent = Some(40.0); - assert_has_violation(&summary, "coverage_percent < learnt_percent"); - - let mut summary = valid_summary(); - summary.learnt_percent = Some(20.0); - assert_has_violation(&summary, "learnt_percent < confident_percent"); - } - - #[test] - fn detects_invalid_values_in_every_percentage() { - type PercentageSetter = fn(&mut LearningAggregate, f64); - - let fields: [(&str, PercentageSetter); 8] = [ - ( - "coverage_percent is not finite or is outside 0..=100", - |summary, value| summary.coverage_percent = Some(value), - ), - ( - "learnt_percent is not finite or is outside 0..=100", - |summary, value| summary.learnt_percent = Some(value), - ), - ( - "confident_percent is not finite or is outside 0..=100", - |summary, value| summary.confident_percent = Some(value), - ), - ( - "learning_percent is not finite or is outside 0..=100", - |summary, value| summary.learning_percent = Some(value), - ), - ( - "unseen_percent is not finite or is outside 0..=100", - |summary, value| summary.unseen_percent = Some(value), - ), - ( - "uncertain_of_learnt_percent is not finite or is outside 0..=100", - |summary, value| summary.uncertain_of_learnt_percent = Some(value), - ), - ( - "due_of_introduced_percent is not finite or is outside 0..=100", - |summary, value| summary.due_of_introduced_percent = Some(value), - ), - ( - "accuracy_percent is not finite or is outside 0..=100", - |summary, value| summary.accuracy_percent = Some(value), - ), - ]; - for (violation, set) in fields { - for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 100.01] { - let mut summary = valid_summary(); - set(&mut summary, value); - assert_has_violation(&summary, violation); - } - } - } - - #[test] - fn global_total_invariant_allows_deduplicated_union() { - assert_eq!(global_total_invariant_violation(3, [2, 2]), None); - } - - #[test] - fn global_total_invariant_detects_global_above_repertoire_sum() { - assert_eq!( - global_total_invariant_violation(5, [2, 2]), - Some("global_total > sum(repertoire_totals)") - ); - } - - #[test] - fn global_total_invariant_detects_repertoire_sum_overflow() { - assert_eq!( - global_total_invariant_violation(0, [usize::MAX, 1]), - Some("repertoire_totals sum overflow") - ); - } - - #[test] - fn global_total_invariant_handles_empty_repertoires() { - assert_eq!(global_total_invariant_violation(0, []), None); - assert_eq!( - global_total_invariant_violation(1, []), - Some("global_total > sum(repertoire_totals)") - ); - } - - #[test] - fn aggregate_output_is_unchanged() { - fn item( - index: usize, - introduced: bool, - correct_streak: u32, - next_review_at: Option, - ) -> LearningItem { - let mut item = - LearningItem::new(LearningItemKey::local(format!("fen-{index}"), "e2e4")); - item.introduced = introduced; - item.correct_streak = correct_streak; - item.next_review_at = next_review_at; - item.previous_interval_seconds = Some(0); - item - } - - let now = 1_000_000; - let grace = 7 * 24 * 60 * 60; - let mut items = [ - item(0, false, 0, None), - item(1, true, 1, Some(now + 100)), - item(2, true, 3, Some(now + 200)), - item(3, true, 3, Some(now - grace - 1)), - ]; - items[1].correct_count = 7; - items[1].wrong_count = 3; - - let summary = aggregate(items.iter(), now, &SrsSettings::default()); - let expected = LearningAggregate { - total: 4, - unseen: 1, - learning: 1, - learnt: 2, - uncertain: 1, - learnt_confident: 1, - due: 1, - next_due_at: None, - coverage_percent: Some(75.0), - learnt_percent: Some(50.0), - confident_percent: Some(25.0), - learning_percent: Some(25.0), - unseen_percent: Some(25.0), - uncertain_of_learnt_percent: Some(50.0), - due_of_introduced_percent: Some(100.0 / 3.0), - accuracy_correct: 7, - accuracy_wrong: 3, - accuracy_attempts: 10, - accuracy_percent: Some(70.0), - repertoire_status: RepertoireStatus::InProgress, - }; - assert_eq!(summary, expected); - assert!(learning_invariant_violations(&summary).is_empty()); - } -} diff --git a/crates/trainer/src/repertoire/analytics_tests.rs b/crates/trainer/src/repertoire/analytics_tests.rs deleted file mode 100644 index b38a0e2..0000000 --- a/crates/trainer/src/repertoire/analytics_tests.rs +++ /dev/null @@ -1,524 +0,0 @@ -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; - -use super::*; - -const DAY: i64 = 24 * 60 * 60; -const BASE: i64 = 1_800_000_000; - -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-analytics-{}-{}-{name}", - std::process::id(), - sequence - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -fn item_key(index: usize) -> LearningItemKey { - LearningItemKey::local(format!("position-{index} w - -"), "e2e4") -} - -fn attempt( - key: &LearningItemKey, - id: impl Into, - event_type: TrainingEventType, - happened_at: i64, - response_time_ms: u64, -) -> TrainingAttempt { - let actual_uci = match event_type { - TrainingEventType::IncorrectIndependent => "d2d4", - _ => "e2e4", - }; - TrainingAttempt { - user_id: key.user_id.clone(), - position_fen4: key.position_fen4.clone(), - client_attempt_id: id.into(), - session_id: "analytics".into(), - event_type, - expected_uci: key.expected_uci.clone(), - actual_uci: Some(actual_uci.into()), - response_time_ms: Some(response_time_ms), - happened_at, - } -} - -fn record(item: &mut LearningItem, id: &str, event_type: TrainingEventType, happened_at: i64) { - apply_attempt( - item, - &attempt(&item.key, id, event_type, happened_at, 250), - &SrsSettings::default(), - ) - .unwrap(); -} - -fn learnt_item(index: usize, reviewed_at: i64, next_review_at: i64) -> LearningItem { - let mut item = LearningItem::new(item_key(index)); - item.introduced = true; - item.correct_streak = 3; - item.correct_count = 3; - item.last_review_at = Some(reviewed_at); - item.last_correct_at = Some(reviewed_at); - item.last_independent_at = Some(reviewed_at); - item.last_independent_correct_at = Some(reviewed_at); - item.last_independent_result = Some(IndependentResult::Correct); - item.next_review_at = Some(next_review_at); - item.previous_interval_seconds = Some(DAY); - item -} - -fn introduced_item(index: usize, next_review_at: Option) -> LearningItem { - let mut item = LearningItem::new(item_key(index)); - item.introduced = true; - item.next_review_at = next_review_at; - item -} - -#[test] -fn resistant_enters_on_recent_results_and_exits_after_three_independent_correct() { - let mut item = LearningItem::new(item_key(0)); - for (index, event_type) in [ - TrainingEventType::IncorrectIndependent, - TrainingEventType::CorrectIndependent, - TrainingEventType::IncorrectIndependent, - TrainingEventType::CorrectIndependent, - TrainingEventType::IncorrectIndependent, - ] - .into_iter() - .enumerate() - { - record( - &mut item, - &format!("enter-{index}"), - event_type, - BASE + index as i64, - ); - } - - assert!(is_resistant(&item)); - assert!(item.is_learning()); - let summary = aggregate( - std::slice::from_ref(&item), - BASE + 5, - &SrsSettings::default(), - ); - assert_eq!((summary.total, summary.learning, summary.learnt), (1, 1, 0)); - - for index in 0..2 { - record( - &mut item, - &format!("exit-{index}"), - TrainingEventType::CorrectIndependent, - BASE + 5 + index, - ); - assert!(item.is_resistant()); - } - record( - &mut item, - "exit-2", - TrainingEventType::CorrectIndependent, - BASE + 7, - ); - assert!(!item.is_resistant()); - assert!(item.is_learnt()); - record( - &mut item, - "exit-3", - TrainingEventType::CorrectIndependent, - BASE + 8, - ); - assert!(!item.is_resistant()); - - for index in 0..6 { - record( - &mut item, - &format!("recent-{index}"), - TrainingEventType::CorrectIndependent, - BASE + 9 + index, - ); - } - assert_eq!(item.recent_independent_outcomes.len(), 10); - assert!( - item.recent_independent_outcomes - .iter() - .all(|outcome| outcome.result == IndependentResult::Correct) - ); - assert!(!item.is_resistant()); - assert_eq!(item.wrong_count, 3); -} - -#[test] -fn non_independent_events_preserve_independent_timestamps_history_and_median() { - let mut item = LearningItem::new(item_key(0)); - for (index, response_time_ms) in [400, 100, 300, 200].into_iter().enumerate() { - let event_type = if index == 0 { - TrainingEventType::IncorrectIndependent - } else { - TrainingEventType::CorrectIndependent - }; - let training_attempt = attempt( - &item.key, - format!("independent-{index}"), - event_type, - BASE + index as i64, - response_time_ms, - ); - apply_attempt(&mut item, &training_attempt, &SrsSettings::default()).unwrap(); - } - assert_eq!(item.response_time_median_ms(), Some(250.0)); - assert_eq!(item.last_independent_at, Some(BASE + 3)); - assert_eq!(item.last_independent_correct_at, Some(BASE + 3)); - assert_eq!(item.last_independent_wrong_at, Some(BASE)); - assert_eq!( - item.last_independent_result, - Some(IndependentResult::Correct) - ); - - for (index, event_type) in [ - TrainingEventType::Previewed, - TrainingEventType::ReplayAfterError, - TrainingEventType::AutoContext, - TrainingEventType::IllegalMove, - ] - .into_iter() - .enumerate() - { - let before_outcomes = item.recent_independent_outcomes.clone(); - let before_responses = item.independent_response_times_ms.clone(); - let training_attempt = attempt( - &item.key, - format!("context-{index}"), - event_type, - BASE + 10 + index as i64, - 99_999, - ); - apply_attempt(&mut item, &training_attempt, &SrsSettings::default()).unwrap(); - assert_eq!(item.last_independent_at, Some(BASE + 3)); - assert_eq!(item.last_independent_correct_at, Some(BASE + 3)); - assert_eq!(item.last_independent_wrong_at, Some(BASE)); - assert_eq!( - item.last_independent_result, - Some(IndependentResult::Correct) - ); - assert_eq!(item.recent_independent_outcomes, before_outcomes); - assert_eq!(item.independent_response_times_ms, before_responses); - assert_eq!(item.response_time_median_ms(), Some(250.0)); - } -} - -#[test] -fn at_09_uncertain_is_subset_of_learnt_not_an_extra_total() { - let item = learnt_item(0, BASE - DAY, BASE); - let now = BASE + 7 * DAY + 1; - assert!(is_uncertain(&item, now, &SrsSettings::default())); - let summary = aggregate(std::slice::from_ref(&item), now, &SrsSettings::default()); - assert_eq!(summary.total, 1); - assert_eq!(summary.learnt, 1); - assert_eq!(summary.uncertain, 1); - assert_eq!( - summary.total, - summary.unseen + summary.learning + summary.learnt - ); - let details = move_learning_analytics(&item, now, &SrsSettings::default()); - assert_eq!(details.status, MoveLearningStatus::Uncertain); - assert_eq!(details.uncertain_grace_seconds, Some(7 * DAY)); -} - -#[test] -fn at_10_independent_correct_clears_uncertain_and_stays_learnt() { - let mut item = learnt_item(0, BASE - DAY, BASE); - let now = BASE + 7 * DAY + 1; - apply_independent_correct(&mut item, now, &SrsSettings::default()); - assert!(item.is_learnt()); - assert!(!is_uncertain(&item, now, &SrsSettings::default())); - assert_eq!(item.last_correct_at, Some(now)); - assert_eq!(item.last_independent_correct_at, Some(now)); - assert!(item.next_review_at.is_some_and(|next| next > now)); -} - -#[test] -fn at_11_independent_wrong_clears_uncertain_by_returning_to_learning() { - let mut item = learnt_item(0, BASE - DAY, BASE); - let previous_independent_correct = item.last_independent_correct_at; - let now = BASE + 7 * DAY + 1; - apply_independent_wrong(&mut item, "d2d4", now, &SrsSettings::default()); - assert!(item.is_learning()); - assert!(!is_uncertain(&item, now, &SrsSettings::default())); - assert_eq!(item.correct_streak, 0); - assert_eq!(item.last_correct_at, None); - assert_eq!( - item.last_independent_correct_at, - previous_independent_correct - ); - assert_eq!(item.last_independent_wrong_at, Some(now)); - assert_eq!(item.last_independent_result, Some(IndependentResult::Wrong)); - assert_eq!(item.next_review_at, Some(now + MISTAKE_DELAY_SECONDS)); -} - -#[test] -fn at_26_scheduled_boundaries_are_disjoint_and_cover_every_introduced_item() { - let offset = LocalDatePolicy::fixed(2 * 60 * 60); - let end_today = offset.end_of_local_day_exclusive(BASE); - assert!(BASE + 1 < end_today); - let end_week = BASE + SCHEDULED_WEEK_SECONDS; - let end_month = BASE + SCHEDULED_MONTH_SECONDS; - let end_year = BASE + SCHEDULED_YEAR_SECONDS; - let mut items = vec![ - introduced_item(0, Some(BASE)), - introduced_item(1, Some(BASE + 1)), - introduced_item(2, Some(end_today)), - introduced_item(3, Some(end_week - 1)), - introduced_item(4, Some(end_week)), - introduced_item(5, Some(end_month)), - introduced_item(6, Some(end_year)), - introduced_item(7, None), - LearningItem::new(item_key(8)), - ]; - items[8].next_review_at = Some(BASE); - - let buckets = scheduled_buckets(items.iter(), BASE, offset); - assert_eq!(buckets.overdue, 2); - assert_eq!(buckets.today, 1); - assert_eq!(buckets.week, 2); - assert_eq!(buckets.month, 1); - assert_eq!(buckets.year, 1); - assert_eq!(buckets.later, 1); - assert_eq!(buckets.introduced(), 8); -} - -#[test] -fn local_date_policy_makes_offset_and_midnight_explicit() { - assert_eq!(LocalDatePolicy::UTC.date(0), "1970-01-01"); - let east = LocalDatePolicy::fixed(3_600); - assert_eq!(east.date(0), "1970-01-01"); - assert_eq!(east.end_of_local_day_exclusive(0), 23 * 3_600); - let west = LocalDatePolicy::fixed(-3_600); - assert_eq!(west.date(0), "1969-12-31"); - assert_eq!(west.end_of_local_day_exclusive(0), 3_600); -} - -#[test] -fn sequences_include_zero_and_attempt_histogram_sums_match_total() { - let unseen = LearningItem::new(item_key(0)); - let mut learning = introduced_item(1, Some(BASE)); - learning.correct_streak = 2; - learning.correct_count = 2; - let mut wrong = introduced_item(2, Some(BASE)); - wrong.wrong_streak = 3; - wrong.wrong_count = 3; - let mut learnt = learnt_item(3, BASE - DAY, BASE); - learnt.correct_streak = 5; - learnt.correct_count = 5; - learnt.wrong_count = 2; - let items = [unseen, learning, wrong, learnt]; - - let histograms = sequence_histograms(items.iter()); - assert_eq!(histograms.correct_streak.get(&0), Some(&2)); - assert_eq!(histograms.correct_streak.get(&2), Some(&1)); - assert_eq!(histograms.correct_streak.get(&5), Some(&1)); - assert_eq!(histograms.wrong_streak.get(&0), Some(&3)); - assert_eq!(histograms.wrong_streak.get(&3), Some(&1)); - assert_eq!(histograms.attempts.get(&0), Some(&1)); - assert_eq!(histograms.attempts.get(&2), Some(&1)); - assert_eq!(histograms.attempts.get(&3), Some(&1)); - assert_eq!(histograms.attempts.get(&7), Some(&1)); - assert_eq!( - histograms.correct_streak.values().sum::(), - items.len() - ); - assert_eq!(histograms.wrong_streak.values().sum::(), items.len()); - assert_eq!(histograms.attempts.values().sum::(), items.len()); -} - -#[test] -fn per_move_analytics_include_independent_details_and_scope_membership() { - let mut library = Library::default(); - let first = library - .create("First", &chess_core::parse_str("1. e4 e5 2. Nf3 *").game) - .unwrap(); - let second = library - .create("Second", &chess_core::parse_str("1. e4 c5 *").game) - .unwrap(); - let first_scope = StatsScope::for_repertoire(first.clone(), LearningSide::White, BASE); - let key = active_learning_memberships(&library, &first_scope) - .unwrap() - .into_iter() - .find(|membership| membership.key.expected_uci == "e2e4") - .unwrap() - .key; - let mut learning = LearningData::default(); - for (index, response_time_ms) in [400, 100, 300, 200].into_iter().enumerate() { - let event_type = if index == 0 { - TrainingEventType::IncorrectIndependent - } else { - TrainingEventType::CorrectIndependent - }; - learning - .apply_attempt( - attempt( - &key, - format!("details-{index}"), - event_type, - BASE - 3 + index as i64, - response_time_ms, - ), - &SrsSettings::default(), - ) - .unwrap(); - } - let scope = StatsScope::new([first, second], LearningSide::White, BASE + 1); - let details = - scoped_move_learning_analytics(&library, &learning, &scope, &SrsSettings::default()) - .unwrap(); - let e4 = details - .iter() - .find(|details| details.key.expected_uci == "e2e4") - .unwrap(); - assert_eq!(e4.status, MoveLearningStatus::LearntFresh); - assert_eq!(e4.memberships.len(), 2); - assert_eq!(e4.accuracy_percent, Some(75.0)); - assert_eq!(e4.independent_attempts, 4); - assert_eq!(e4.response_time_median_ms, Some(250.0)); - assert_eq!(e4.last_review_at, Some(BASE)); - assert_eq!(e4.last_independent_at, Some(BASE)); - assert_eq!(e4.last_independent_wrong_at, Some(BASE - 3)); - assert_eq!(e4.last_independent_result, Some(IndependentResult::Correct)); - assert_eq!(e4.wrong_move_histogram["d2d4"].count, 1); -} - -#[test] -fn at_27_daily_snapshots_capture_time_dependent_uncertain_without_rewriting_history() { - let dir = TestDir::new("snapshots"); - let path = dir.join("learning.json"); - let store = LearningStore::new(&path); - let mut library = Library::default(); - let repertoire = library - .create("Repertoire", &chess_core::parse_str("1. e4 *").game) - .unwrap(); - let first_scope = StatsScope::for_repertoire(repertoire, LearningSide::White, BASE); - let key = active_learning_keys(&library, &first_scope) - .unwrap() - .into_iter() - .next() - .unwrap(); - let mut learning = LearningData::default(); - let mut learnt = learnt_item(0, BASE - DAY, BASE); - learnt.key = key.clone(); - *learning.ensure_item(key) = learnt; - std::fs::write( - &path, - serde_json::to_vec_pretty(&LearningStoreData { - learning, - ..LearningStoreData::default() - }) - .unwrap(), - ) - .unwrap(); - - let first = store - .record_snapshot( - &library, - &first_scope, - &SrsSettings::default(), - LocalDatePolicy::UTC, - ) - .unwrap(); - assert!(first.recorded); - assert_eq!(first.revision, 1); - assert_eq!((first.snapshot.learnt, first.snapshot.uncertain), (1, 0)); - - let mut raw: serde_json::Value = - serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); - raw["snapshots"][0]["future_snapshot_extension"] = serde_json::json!({"keep": true}); - raw["snapshots"][0]["scope"]["future_scope_extension"] = serde_json::json!({"keep": true}); - std::fs::write(&path, serde_json::to_vec_pretty(&raw).unwrap()).unwrap(); - - let mut second_scope = first_scope.clone(); - second_scope.as_of = BASE + 7 * DAY + 1; - let second = store - .record_snapshot( - &library, - &second_scope, - &SrsSettings::default(), - LocalDatePolicy::UTC, - ) - .unwrap(); - assert!(second.recorded); - assert_eq!(second.revision, 2); - assert_eq!((second.snapshot.learnt, second.snapshot.uncertain), (1, 1)); - assert_ne!(first.snapshot.date, second.snapshot.date); - - let bytes_after_second = std::fs::read(&path).unwrap(); - second_scope.as_of += 60; - let repeated = store - .record_snapshot( - &library, - &second_scope, - &SrsSettings::default(), - LocalDatePolicy::UTC, - ) - .unwrap(); - assert!(!repeated.recorded); - assert_eq!(repeated.revision, 2); - assert_eq!(repeated.snapshot, second.snapshot); - assert_eq!(std::fs::read(&path).unwrap(), bytes_after_second); - - let loaded = store.load().unwrap(); - assert_eq!(loaded.snapshots.len(), 2); - assert_eq!(loaded.snapshots[0], first.snapshot); - assert_eq!(loaded.snapshots[1], second.snapshot); - let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); - assert_eq!( - saved["snapshots"][0]["future_snapshot_extension"], - serde_json::json!({"keep": true}) - ); - assert_eq!( - saved["snapshots"][0]["scope"]["future_scope_extension"], - serde_json::json!({"keep": true}) - ); -} - -#[test] -fn old_item_and_store_json_default_new_analytics_fields() { - let mut item_value = serde_json::to_value(LearningItem::new(item_key(0))).unwrap(); - let item_object = item_value.as_object_mut().unwrap(); - for field in [ - "last_independent_at", - "last_independent_correct_at", - "last_independent_wrong_at", - "last_independent_result", - "recent_independent_outcomes", - "resistant", - ] { - item_object.remove(field); - } - let item: LearningItem = serde_json::from_value(item_value).unwrap(); - assert_eq!(item.last_independent_at, None); - assert_eq!(item.last_independent_result, None); - assert!(item.recent_independent_outcomes.is_empty()); - assert!(!item.resistant); - - let mut store_value = serde_json::to_value(LearningStoreData::default()).unwrap(); - store_value.as_object_mut().unwrap().remove("snapshots"); - let store: LearningStoreData = serde_json::from_value(store_value).unwrap(); - assert!(store.snapshots.is_empty()); -} diff --git a/crates/trainer/src/repertoire/branch_analytics.rs b/crates/trainer/src/repertoire/branch_analytics.rs deleted file mode 100644 index 27e88c7..0000000 --- a/crates/trainer/src/repertoire/branch_analytics.rs +++ /dev/null @@ -1,71 +0,0 @@ -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use super::aggregate::{LearningAggregate, aggregate}; -use super::learning::{LearningData, LearningItem, LearningItemKey}; -use super::learning_graph::{ - LearningGraphError, StatsScope, aggregate_scope, all_path_learning_memberships, -}; -use super::model::{Library, RepertoireId}; -use super::srs::SrsSettings; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct BranchLearningAnalytics { - pub repertoire_id: RepertoireId, - pub branch_root: Vec, - pub summary: LearningAggregate, - pub last_independent_at: Option, -} - -pub fn branch_learning_analytics( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - settings: &SrsSettings, -) -> Result, LearningGraphError> { - let memberships = all_path_learning_memberships(library, scope)?; - let scoped = aggregate_scope(library, learning, scope, settings)?; - let items_by_key: BTreeMap<&LearningItemKey, &LearningItem> = - scoped.items.iter().map(|item| (&item.key, item)).collect(); - let first_prefix_len = scope - .branch_root - .as_ref() - .map_or(1, |root| root.len().max(1)); - let mut branches: BTreeMap< - (RepertoireId, Vec), - BTreeMap<&LearningItemKey, &LearningItem>, - > = BTreeMap::new(); - - for membership in memberships { - let Some((key, item)) = items_by_key.get_key_value(&membership.key) else { - continue; - }; - for prefix_len in first_prefix_len..=membership.path.len() { - branches - .entry(( - membership.repertoire_id.clone(), - membership.path[..prefix_len].to_vec(), - )) - .or_default() - .insert(*key, *item); - } - } - - Ok(branches - .into_iter() - .map(|((repertoire_id, branch_root), items)| { - let last_independent_at = items - .values() - .filter_map(|item| item.last_independent_at) - .max(); - let summary = aggregate(items.values().copied(), scope.as_of, settings); - BranchLearningAnalytics { - repertoire_id, - branch_root, - summary, - last_independent_at, - } - }) - .collect()) -} diff --git a/crates/trainer/src/repertoire/branch_tests.rs b/crates/trainer/src/repertoire/branch_tests.rs deleted file mode 100644 index 10885da..0000000 --- a/crates/trainer/src/repertoire/branch_tests.rs +++ /dev/null @@ -1,516 +0,0 @@ -use std::collections::BTreeSet; - -use super::*; - -const NOW: i64 = 1_800_000_000; -const DAY: i64 = 24 * 60 * 60; - -fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { - library - .create(name, &chess_core::parse_str(pgn).game) - .unwrap() -} - -fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { - let mut library = Library::default(); - let id = add_repertoire(&mut library, "One", pgn); - (library, id) -} - -fn scope(id: RepertoireId) -> StatsScope { - StatsScope::for_repertoire(id, LearningSide::White, NOW) -} - -fn strings(moves: &[&str]) -> Vec { - moves.iter().map(|mv| (*mv).to_owned()).collect() -} - -fn key_at_path(repertoire: &Repertoire, path: &[String], expected_uci: &str) -> LearningItemKey { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let parent = tree.node_at_path(path).unwrap(); - LearningItemKey::local(tree.position_key(parent).unwrap(), expected_uci) -} - -fn branch<'a>( - rows: &'a [BranchLearningAnalytics], - repertoire_id: &RepertoireId, - path: &[&str], -) -> Option<&'a BranchLearningAnalytics> { - rows.iter().find(|row| { - &row.repertoire_id == repertoire_id - && row - .branch_root - .iter() - .map(String::as_str) - .eq(path.iter().copied()) - }) -} - -fn learnt(item: &mut LearningItem, next_review_at: i64) { - item.introduced = true; - item.correct_streak = 3; - item.correct_count = 3; - item.last_review_at = Some(NOW - DAY); - item.last_correct_at = Some(NOW - DAY); - item.last_independent_at = Some(NOW - DAY); - item.next_review_at = Some(next_review_at); - item.previous_interval_seconds = Some(DAY); -} - -fn transposition_pgn() -> &'static str { - "1. e4 d5 (1... Nf6 2. d4 d5 3. c4) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 e6 6. g3 *" -} - -fn branching_pgn() -> &'static str { - "1. e4 e5 (1... c5 2. Nf3) 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O *" -} - -fn attempt( - key: &LearningItemKey, - id: &str, - event_type: TrainingEventType, - happened_at: i64, -) -> TrainingAttempt { - TrainingAttempt { - user_id: key.user_id.clone(), - position_fen4: key.position_fen4.clone(), - client_attempt_id: id.into(), - session_id: "branch-analytics".into(), - event_type, - expected_uci: key.expected_uci.clone(), - actual_uci: Some(if event_type == TrainingEventType::IncorrectIndependent { - "d2d4".into() - } else { - key.expected_uci.clone() - }), - response_time_ms: Some(250), - happened_at, - } -} - -#[test] -fn at_30_transposition_is_unique_per_branch_and_in_global_scope() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "First", transposition_pgn()); - let second = add_repertoire(&mut library, "Second", transposition_pgn()); - let shared = key_at_path( - library.repertoire(&first).unwrap(), - &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), - "c2c4", - ); - let mut learning = LearningData::default(); - learnt(learning.ensure_item(shared), NOW + DAY); - - let selected = scope(first.clone()); - let rows = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - let first_move = branch(&rows, &first, &["e2e4"]).unwrap(); - let main_branch = branch(&rows, &first, &["e2e4", "d7d5"]).unwrap(); - let transposing_branch = branch(&rows, &first, &["e2e4", "g8f6"]).unwrap(); - assert_eq!(first_move.summary.total, 7); - assert_eq!(first_move.summary.learnt, 1); - assert_eq!(first_move.summary.accuracy_correct, 3); - assert_eq!(first_move.summary.accuracy_attempts, 3); - assert_eq!(main_branch.summary.total, 5); - assert_eq!(main_branch.summary.learnt, 1); - assert_eq!(main_branch.summary.accuracy_correct, 3); - assert_eq!(transposing_branch.summary.total, 2); - assert_eq!(transposing_branch.summary.learnt, 1); - assert_eq!(transposing_branch.summary.accuracy_correct, 3); - assert_eq!(transposing_branch.summary.accuracy_attempts, 3); - assert_eq!( - first_move.summary.total + 1, - 1 + main_branch.summary.total + transposing_branch.summary.total - ); - assert!(rows.iter().all(|row| !row.branch_root.is_empty())); - - let global_scope = StatsScope::new([first.clone(), second.clone()], LearningSide::White, NOW); - let global_rows = - branch_learning_analytics(&library, &learning, &global_scope, &SrsSettings::default()) - .unwrap(); - let global_first_moves: Vec<_> = global_rows - .iter() - .filter(|row| row.branch_root == strings(&["e2e4"])) - .collect(); - assert_eq!(global_first_moves.len(), 2); - assert_eq!( - global_first_moves - .iter() - .map(|row| row.repertoire_id.clone()) - .collect::>(), - BTreeSet::from([first, second]) - ); - assert!( - global_first_moves - .iter() - .all(|row| row.summary.total == 7 && row.summary.accuracy_correct == 3) - ); - let global = - aggregate_scope(&library, &learning, &global_scope, &SrsSettings::default()).unwrap(); - assert_eq!(global.summary.total, 7); - assert_eq!(global.summary.learnt, 1); - assert_eq!(global.summary.accuracy_correct, 3); -} - -#[test] -fn branch_summary_uses_core_statuses_due_and_independent_accuracy() { - let (library, id) = single_repertoire(branching_pgn()); - let repertoire = library.repertoire(&id).unwrap(); - let nf3 = key_at_path(repertoire, &strings(&["e2e4", "e7e5"]), "g1f3"); - let bb5 = key_at_path( - repertoire, - &strings(&["e2e4", "e7e5", "g1f3", "b8c6"]), - "f1b5", - ); - let ba4 = key_at_path( - repertoire, - &strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6"]), - "b5a4", - ); - let castle = key_at_path( - repertoire, - &strings(&[ - "e2e4", "e7e5", "g1f3", "b8c6", "f1b5", "a7a6", "b5a4", "g8f6", - ]), - "e1g1", - ); - let mut learning = LearningData::default(); - - let item = learning.ensure_item(nf3); - item.introduced = true; - item.correct_streak = 1; - item.correct_count = 1; - item.next_review_at = Some(NOW + DAY); - item.last_independent_at = Some(NOW - 40); - - let item = learning.ensure_item(bb5); - learnt(item, NOW + DAY); - item.last_independent_at = Some(NOW - 20); - - let item = learning.ensure_item(ba4); - item.introduced = true; - item.correct_streak = 3; - item.correct_count = 2; - item.wrong_count = 1; - item.next_review_at = Some(NOW - 8 * DAY); - item.previous_interval_seconds = Some(DAY); - item.last_independent_at = Some(NOW - 10); - - let item = learning.ensure_item(castle); - item.introduced = true; - item.wrong_count = 2; - item.next_review_at = Some(NOW - 1); - item.last_independent_at = Some(NOW - 30); - - let rows = branch_learning_analytics( - &library, - &learning, - &scope(id.clone()), - &SrsSettings::default(), - ) - .unwrap(); - let summary = &branch(&rows, &id, &["e2e4"]).unwrap().summary; - assert_eq!(summary.total, 6); - assert_eq!(summary.unseen, 2); - assert_eq!(summary.learning, 2); - assert_eq!(summary.learnt, 2); - assert_eq!(summary.uncertain, 1); - assert_eq!(summary.learnt_confident, 1); - assert_eq!(summary.due, 2); - assert_eq!(summary.accuracy_correct, 6); - assert_eq!(summary.accuracy_wrong, 3); - assert_eq!(summary.accuracy_attempts, 9); - assert_eq!(summary.accuracy_percent, Some(100.0 * 6.0 / 9.0)); - assert_eq!( - branch(&rows, &id, &["e2e4"]).unwrap().last_independent_at, - Some(NOW - 10) - ); - - let unseen = branch(&rows, &id, &["e2e4", "c7c5"]).unwrap(); - assert_eq!(unseen.summary.total, 1); - assert_eq!(unseen.summary.unseen, 1); - assert_eq!(unseen.summary.accuracy_attempts, 0); - assert_eq!(unseen.summary.accuracy_percent, None); - assert_eq!(unseen.last_independent_at, None); -} - -#[test] -fn branch_last_independent_ignores_preview_and_auto_context() { - let (library, id) = single_repertoire(branching_pgn()); - let repertoire = library.repertoire(&id).unwrap(); - let main = key_at_path(repertoire, &strings(&["e2e4", "e7e5"]), "g1f3"); - let sideline = key_at_path(repertoire, &strings(&["e2e4", "c7c5"]), "g1f3"); - let mut learning = LearningData::default(); - for (key, event_id, event_type, happened_at) in [ - ( - &main, - "main-independent", - TrainingEventType::CorrectIndependent, - NOW - 20, - ), - ( - &sideline, - "sideline-independent", - TrainingEventType::IncorrectIndependent, - NOW - 10, - ), - (&main, "main-preview", TrainingEventType::Previewed, NOW - 1), - ( - &sideline, - "sideline-context", - TrainingEventType::AutoContext, - NOW, - ), - ] { - learning - .apply_attempt( - attempt(key, event_id, event_type, happened_at), - &SrsSettings::default(), - ) - .unwrap(); - } - assert_eq!(learning.item(&main).unwrap().last_review_at, Some(NOW - 1)); - assert_eq!( - learning.item(&main).unwrap().last_independent_at, - Some(NOW - 20) - ); - - let rows = branch_learning_analytics( - &library, - &learning, - &scope(id.clone()), - &SrsSettings::default(), - ) - .unwrap(); - let all = branch(&rows, &id, &["e2e4"]).unwrap(); - assert_eq!(all.last_independent_at, Some(NOW - 10)); - assert_eq!(all.summary.accuracy_correct, 1); - assert_eq!(all.summary.accuracy_wrong, 1); - assert_eq!(all.summary.accuracy_attempts, 2); - assert_eq!(all.summary.accuracy_percent, Some(50.0)); - assert_eq!( - branch(&rows, &id, &["e2e4", "e7e5"]) - .unwrap() - .last_independent_at, - Some(NOW - 20) - ); - assert_eq!( - branch(&rows, &id, &["e2e4", "c7c5"]) - .unwrap() - .last_independent_at, - Some(NOW - 10) - ); -} - -#[test] -fn disabled_branch_disappears_and_reenable_restores_history() { - let (mut library, id) = single_repertoire(branching_pgn()); - let selected = scope(id.clone()); - let sideline = key_at_path( - library.repertoire(&id).unwrap(), - &strings(&["e2e4", "c7c5"]), - "g1f3", - ); - let mut learning = LearningData::default(); - learnt(learning.ensure_item(sideline.clone()), NOW + DAY); - let before = learning.item(&sideline).unwrap().clone(); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "c7c5"]), true) - .unwrap(); - let disabled = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert!(branch(&disabled, &id, &["e2e4", "c7c5"]).is_none()); - assert_eq!(branch(&disabled, &id, &["e2e4"]).unwrap().summary.total, 5); - assert_eq!(learning.item(&sideline), Some(&before)); - - let mut include_inactive = selected.clone(); - include_inactive.only_active = false; - let inactive = branch_learning_analytics( - &library, - &learning, - &include_inactive, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!( - branch(&inactive, &id, &["e2e4", "c7c5"]) - .unwrap() - .summary - .learnt, - 1 - ); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "c7c5"]), false) - .unwrap(); - let enabled = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - let restored = branch(&enabled, &id, &["e2e4", "c7c5"]).unwrap(); - assert_eq!(restored.summary.total, 1); - assert_eq!(restored.summary.learnt, 1); - assert_eq!(restored.last_independent_at, Some(NOW - DAY)); - assert_eq!(learning.item(&sideline), Some(&before)); -} - -#[test] -fn max_depth_and_branch_root_limit_candidates_and_items() { - let (library, id) = - single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 *"); - let learning = LearningData::default(); - let depth_scope = scope(id.clone()).with_max_depth(Some(4)); - let depth_rows = - branch_learning_analytics(&library, &learning, &depth_scope, &SrsSettings::default()) - .unwrap(); - assert_eq!( - branch(&depth_rows, &id, &["e2e4"]).unwrap().summary.total, - 2 - ); - assert!(depth_rows.iter().all(|row| row.branch_root.len() <= 4)); - assert!( - depth_rows - .iter() - .all(|row| !row.branch_root.contains(&"f1b5".to_owned())) - ); - - let root = strings(&["e2e4", "e7e5"]); - let rooted_scope = scope(id.clone()).with_branch_root(root.clone()); - let rooted_rows = - branch_learning_analytics(&library, &learning, &rooted_scope, &SrsSettings::default()) - .unwrap(); - assert!(!rooted_rows.is_empty()); - assert!( - rooted_rows - .iter() - .all(|row| row.branch_root.starts_with(&root)) - ); - assert!(branch(&rooted_rows, &id, &["e2e4"]).is_none()); - assert_eq!( - branch(&rooted_rows, &id, &["e2e4", "e7e5"]) - .unwrap() - .summary - .total, - 5 - ); - - let limited_scope = rooted_scope.with_max_depth(Some(4)); - let limited_rows = - branch_learning_analytics(&library, &learning, &limited_scope, &SrsSettings::default()) - .unwrap(); - assert_eq!(limited_rows.len(), 2); - assert_eq!( - branch(&limited_rows, &id, &["e2e4", "e7e5"]) - .unwrap() - .summary - .total, - 1 - ); - assert!(limited_rows.iter().all(|row| row.branch_root.len() <= 4)); -} - -#[test] -fn empty_scope_has_no_rows_or_whole_repertoire_root() { - let (library, id) = single_repertoire("1. e4 *"); - let empty = StatsScope::new([], LearningSide::White, NOW); - assert!( - branch_learning_analytics( - &library, - &LearningData::default(), - &empty, - &SrsSettings::default(), - ) - .unwrap() - .is_empty() - ); - - let no_black_moves = StatsScope::for_repertoire(id, LearningSide::Black, NOW); - assert!( - branch_learning_analytics( - &library, - &LearningData::default(), - &no_black_moves, - &SrsSettings::default(), - ) - .unwrap() - .is_empty() - ); -} - -#[test] -fn branch_projection_is_deterministic_and_sorted() { - let (library, id) = single_repertoire(branching_pgn()); - let selected = scope(id.clone()); - let mut learning = LearningData::default(); - for key in active_learning_keys(&library, &selected).unwrap() { - learning.ensure_item(key); - } - let first = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - let mut sorted = first.clone(); - sorted.sort_by(|left, right| { - (&left.repertoire_id, &left.branch_root).cmp(&(&right.repertoire_id, &right.branch_root)) - }); - assert_eq!(first, sorted); - - learning.items.reverse(); - let second = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(first, second); -} - -#[test] -fn all_path_projection_keeps_all_answers_and_honours_disabled_branches() { - let (mut library, id) = single_repertoire("1. e4 (1. d4 d5) e5 *"); - let selected = scope(id.clone()); - let learning = LearningData::default(); - let default_rows = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!( - branch(&default_rows, &id, &["e2e4"]).unwrap().summary.total, - 1 - ); - assert_eq!( - branch(&default_rows, &id, &["d2d4"]).unwrap().summary.total, - 1 - ); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4"]), true) - .unwrap(); - let active = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert!(branch(&active, &id, &["e2e4"]).is_none()); - assert_eq!(branch(&active, &id, &["d2d4"]).unwrap().summary.total, 1); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4"]), false) - .unwrap(); - let root = { - let repertoire = library.repertoire(&id).unwrap(); - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - tree.position_key(tree.root()).unwrap().to_owned() - }; - library - .repertoire_mut(&id) - .unwrap() - .set_main_answer_override(&root, "d2d4", LearningSide::White) - .unwrap(); - let overridden = - branch_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!( - branch(&overridden, &id, &["e2e4"]).unwrap().summary.total, - 1 - ); - assert_eq!( - branch(&overridden, &id, &["d2d4"]).unwrap().summary.total, - 1 - ); -} diff --git a/crates/trainer/src/repertoire/context_tests.rs b/crates/trainer/src/repertoire/context_tests.rs deleted file mode 100644 index 2c9df61..0000000 --- a/crates/trainer/src/repertoire/context_tests.rs +++ /dev/null @@ -1,550 +0,0 @@ -use super::*; -use crate::repertoire::learning::AttemptApplication; - -const NOW: i64 = 1_800_000_000; -const DAY: i64 = 24 * 60 * 60; - -struct Fixture { - library: Library, - scope: StatsScope, - learning: LearningData, - session: LearningSessionSnapshot, -} - -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 seed( - learning: &mut LearningData, - key: LearningItemKey, - streak: u32, - next_review_at: Option, -) { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = streak; - item.correct_count = u64::from(streak); - item.last_review_at = (streak > 0).then_some(NOW - DAY); - item.last_correct_at = (streak > 0).then_some(NOW - DAY); - item.next_review_at = next_review_at; -} - -fn fixture( - pgn: &str, - side: LearningSide, - mode: QueueMode, - policy: LearningContextPolicy, - items: &[(&str, u32, Option)], -) -> Fixture { - 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, streak, next) in items { - let key = key_for(&library, &scope, expected); - seed(&mut learning, key, *streak, *next); - } - let mut session = LearningSessionSnapshot::new_with_mode( - "context", - &library, - &learning, - scope.clone(), - SrsSettings::default(), - mode, - ) - .unwrap(); - session.context_policy = policy; - Fixture { - library, - scope, - learning, - session, - } -} - -fn reinforcing_policy() -> LearningContextPolicy { - LearningContextPolicy { - consider_leadup_moves: true, - ..LearningContextPolicy::default() - } -} - -fn apply(learning: &mut LearningData, attempt: &TrainingAttempt) { - assert_eq!( - learning.apply_attempt(attempt.clone(), &SrsSettings::default()), - Ok(AttemptApplication::Applied) - ); -} - -fn play(fixture: &mut Fixture, uci: &str, id: &str) -> TrainingAttempt { - let attempt = fixture - .session - .play_uci_with_learning(&fixture.library, &fixture.learning, uci, id, NOW, Some(200)) - .unwrap(); - apply(&mut fixture.learning, &attempt); - attempt -} - -fn advance(fixture: &mut Fixture, id: &str) -> TrainingAttempt { - let attempt = fixture - .session - .advance_context_with_learning(&fixture.library, &fixture.learning, id, NOW) - .unwrap(); - apply(&mut fixture.learning, &attempt); - attempt -} - -fn automatic_uci(presentation: &LearningPresentation) -> Vec<&str> { - presentation - .automatic_context - .iter() - .map(|step| step.uci.as_str()) - .collect() -} - -#[test] -fn weak_context_is_reinforced_as_an_independent_answer() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - reinforcing_policy(), - &[("e2e4", 2, Some(NOW + 10 * DAY)), ("g1f3", 0, Some(NOW))], - ); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!( - presentation.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert!(presentation.automatic_context.is_empty()); - assert_eq!(f.session.current_expected_uci(), Some("e2e4")); - - let answer = play(&mut f, "e2e4", "weak-e4"); - assert_eq!(answer.event_type, TrainingEventType::CorrectIndependent); - assert!(f.session.completed_keys.contains(&e4)); - assert_eq!(f.session.phase, LearningSessionPhase::AdvancingContext); - assert_eq!( - advance(&mut f, "weak-e5").event_type, - TrainingEventType::AutoContext - ); - assert_eq!(f.session.phase, LearningSessionPhase::AwaitingIndependent); - play(&mut f, "g1f3", "weak-target"); - assert_eq!(f.session.phase, LearningSessionPhase::Finished); - assert_eq!( - f.learning - .attempts - .iter() - .filter(|attempt| attempt.item_key() == e4 && attempt.event_type.is_independent()) - .count(), - 1 - ); -} - -#[test] -fn due_soon_policy_reinforces_even_a_learnt_context_move() { - let mut policy = reinforcing_policy(); - policy.reinforce_minimum_days = Some(3); - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - policy, - &[("e2e4", 3, Some(NOW + 2 * DAY)), ("g1f3", 0, Some(NOW))], - ); - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!( - presentation.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert_eq!(f.session.current_expected_uci(), Some("e2e4")); -} - -#[test] -fn well_known_context_outside_due_window_is_not_reinforced() { - let mut policy = reinforcing_policy(); - policy.reinforce_minimum_days = Some(3); - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - policy, - &[("e2e4", 3, Some(NOW + 10 * DAY)), ("g1f3", 0, Some(NOW))], - ); - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!(presentation.phase, LearningSessionPhase::AdvancingContext); - assert_eq!(automatic_uci(&presentation), ["e2e4", "e7e5"]); -} - -#[test] -fn very_well_known_start_prefix_is_omitted_without_attempts() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - reinforcing_policy(), - &[ - ("e2e4", 100, Some(NOW + 10 * DAY)), - ("g1f3", 100, Some(NOW + 10 * DAY)), - ("f1b5", 0, Some(NOW)), - ], - ); - let before = f.learning.clone(); - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!( - presentation.phase, - LearningSessionPhase::AwaitingIndependent - ); - assert!(presentation.automatic_context.is_empty()); - assert_eq!(f.session.context_index, 4); - assert_eq!(f.session.current_expected_uci(), Some("f1b5")); - assert_eq!( - presentation.current_position.unwrap().fen4, - key_for(&f.library, &f.scope, "f1b5").position_fen4 - ); - assert_eq!(f.learning, before); -} - -#[test] -fn opponent_context_stays_automatic_even_with_weak_learning_data() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::Black, - QueueMode::SpacedRepetition, - reinforcing_policy(), - &[("e7e5", 2, Some(NOW + 10 * DAY)), ("b8c6", 0, Some(NOW))], - ); - let white_scope = StatsScope::for_repertoire( - f.scope.repertoire_ids.iter().next().unwrap().clone(), - LearningSide::White, - NOW, - ); - let opponent = key_for(&f.library, &white_scope, "e2e4"); - seed(&mut f.learning, opponent, 0, Some(NOW)); - - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!(presentation.phase, LearningSessionPhase::AdvancingContext); - assert_eq!(automatic_uci(&presentation), ["e2e4"]); - let automatic = advance(&mut f, "opponent-e4"); - assert_eq!(automatic.event_type, TrainingEventType::AutoContext); - assert_eq!( - f.session.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert_eq!(f.session.current_expected_uci(), Some("e7e5")); -} - -#[test] -fn reinforcement_is_not_repeated_in_the_same_review_cycle() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::ReviewInOrder, - reinforcing_policy(), - &[("e2e4", 0, Some(NOW + DAY)), ("g1f3", 0, Some(NOW))], - ); - f.session.queue.reverse(); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!( - presentation.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - play(&mut f, "e2e4", "cycle-context-e4"); - advance(&mut f, "cycle-e5"); - play(&mut f, "g1f3", "cycle-target-nf3"); - assert_eq!(f.session.cycle, 1); - assert!(f.session.completed_keys.is_empty()); - assert_eq!( - f.learning - .attempts - .iter() - .filter(|attempt| attempt.item_key() == e4 && attempt.event_type.is_independent()) - .count(), - 1 - ); - - let next_cycle = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!( - next_cycle.phase, - LearningSessionPhase::AwaitingContextIndependent - ); -} - -#[test] -fn wrong_context_replay_completes_context_without_success() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - reinforcing_policy(), - &[("e2e4", 2, Some(NOW + 10 * DAY)), ("g1f3", 0, Some(NOW))], - ); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - f.session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - let wrong = play(&mut f, "d2d4", "context-wrong"); - assert_eq!(wrong.event_type, TrainingEventType::IncorrectIndependent); - assert_eq!( - f.session.phase, - LearningSessionPhase::AwaitingReplayAfterError - ); - let revealed = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!(revealed.revealed_move.as_deref(), Some("e2e4")); - assert!(revealed.automatic_context.is_empty()); - - let replay = play(&mut f, "e2e4", "context-replay"); - assert_eq!(replay.event_type, TrainingEventType::ReplayAfterError); - assert!(f.session.completed_keys.contains(&e4)); - assert_eq!(f.session.phase, LearningSessionPhase::AdvancingContext); - let item = f.learning.item(&e4).unwrap(); - assert_eq!(item.correct_count, 2); - assert_eq!(item.wrong_count, 1); - assert_eq!(item.correct_streak, 0); - assert_eq!(item.last_correct_at, None); - assert_eq!( - f.learning - .attempts - .iter() - .filter(|attempt| attempt.item_key() == e4 && attempt.event_type.is_independent()) - .count(), - 1 - ); -} - -#[test] -fn leadup_off_and_legacy_methods_keep_context_automatic() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - LearningContextPolicy::default(), - &[("e2e4", 0, Some(NOW + DAY)), ("g1f3", 0, Some(NOW))], - ); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - let before = f.learning.item(&e4).unwrap().clone(); - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!(presentation.phase, LearningSessionPhase::AdvancingContext); - assert_eq!(automatic_uci(&presentation), ["e2e4", "e7e5"]); - assert!( - presentation - .automatic_context - .iter() - .all(|step| step.speed_factor == 1.0) - ); - - let first = f - .session - .advance_context(&f.library, "legacy-e4", NOW) - .unwrap(); - apply(&mut f.learning, &first); - let second = f - .session - .advance_context(&f.library, "legacy-e5", NOW) - .unwrap(); - apply(&mut f.learning, &second); - assert_eq!(f.session.phase, LearningSessionPhase::AwaitingIndependent); - assert_eq!(f.learning.item(&e4), Some(&before)); -} - -#[test] -fn fixed_and_adaptive_speed_factors_are_deterministic_and_clamped() { - let mut policy = LearningContextPolicy { - use_fixed_piece_speed: true, - move_speed_adjustment: 3.0, - ..LearningContextPolicy::default() - }; - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - policy, - &[("e2e4", 3, Some(NOW + DAY)), ("g1f3", 0, Some(NOW))], - ); - let fixed = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert!( - fixed - .automatic_context - .iter() - .all(|step| step.speed_factor == 1.0) - ); - - policy = f.session.context_policy; - policy.use_fixed_piece_speed = false; - policy.move_speed_adjustment = 1.5; - f.session.context_policy = policy; - let adaptive = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!(adaptive.automatic_context[0].speed_factor, 3.0); - assert_eq!(adaptive.automatic_context[1].speed_factor, 1.5); - - f.session.context_policy.move_speed_adjustment = 100.0; - let high = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert!( - high.automatic_context - .iter() - .all(|step| step.speed_factor == 4.0) - ); - f.session.context_policy.move_speed_adjustment = 0.0; - let low = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert!( - low.automatic_context - .iter() - .all(|step| step.speed_factor == 0.25) - ); -} - -#[test] -fn resume_keeps_partial_learning_context_position() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::White, - QueueMode::SpacedRepetition, - reinforcing_policy(), - &[ - ("e2e4", 2, Some(NOW + DAY)), - ("g1f3", 3, Some(NOW + 10 * DAY)), - ("f1b5", 0, Some(NOW)), - ], - ); - f.session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - play(&mut f, "e2e4", "resume-e4"); - advance(&mut f, "resume-e5"); - assert_eq!(f.session.context_index, 2); - - let json = serde_json::to_string(&f.session).unwrap(); - let restored = serde_json::from_str::(&json) - .unwrap() - .resume(&f.library) - .unwrap(); - f.session = restored; - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!(f.session.context_index, 2); - assert_eq!(automatic_uci(&presentation), ["g1f3", "b8c6"]); - advance(&mut f, "resume-nf3"); - advance(&mut f, "resume-nc6"); - assert_eq!(f.session.phase, LearningSessionPhase::AwaitingIndependent); - assert_eq!(f.session.current_expected_uci(), Some("f1b5")); -} - -#[test] -fn old_json_unknown_fields_and_duplicate_attempts_remain_compatible() { - let mut f = fixture( - "1. e4 *", - LearningSide::White, - QueueMode::SpacedRepetition, - LearningContextPolicy::default(), - &[("e2e4", 1, Some(NOW))], - ); - let mut raw = serde_json::to_value(&f.session).unwrap(); - raw.as_object_mut().unwrap().remove("context_policy"); - raw["future_snapshot"] = serde_json::json!({"preserved": true}); - let restored: LearningSessionSnapshot = serde_json::from_value(raw).unwrap(); - assert_eq!(restored.context_policy, LearningContextPolicy::default()); - restored.clone().resume(&f.library).unwrap(); - let policy: LearningContextPolicy = serde_json::from_value(serde_json::json!({ - "future_policy_field": true - })) - .unwrap(); - assert_eq!(policy, LearningContextPolicy::default()); - f.session = restored; - - let attempt = f - .session - .play_uci_with_learning(&f.library, &f.learning, "e2e4", "at-23", NOW, Some(100)) - .unwrap(); - apply(&mut f.learning, &attempt); - assert_eq!( - f.learning.apply_attempt(attempt, &SrsSettings::default()), - Ok(AttemptApplication::Duplicate) - ); - let e4 = key_for(&f.library, &f.scope, "e2e4"); - assert_eq!(f.learning.item(&e4).unwrap().correct_count, 2); - assert_eq!( - f.learning - .attempts - .iter() - .filter(|attempt| attempt.client_attempt_id == "at-23") - .count(), - 1 - ); -} - -#[test] -fn least_recent_keeps_legacy_context_checks_with_leadup_off() { - let mut f = fixture( - "1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *", - LearningSide::White, - QueueMode::LeastRecent, - LearningContextPolicy::default(), - &[ - ("e2e4", 0, Some(NOW + DAY)), - ("g1f3", 0, Some(NOW + DAY)), - ("f1b5", 0, Some(NOW + DAY)), - ], - ); - f.session.queue.reverse(); - f.session.phase = LearningSessionPhase::AdvancingContext; - let presentation = f - .session - .presentation_with_learning(&f.library, &f.learning) - .unwrap(); - assert_eq!( - presentation.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert_eq!(f.session.current_expected_uci(), Some("e2e4")); - assert!(presentation.automatic_context.is_empty()); -} diff --git a/crates/trainer/src/repertoire/daily_tests.rs b/crates/trainer/src/repertoire/daily_tests.rs deleted file mode 100644 index 8b72827..0000000 --- a/crates/trainer/src/repertoire/daily_tests.rs +++ /dev/null @@ -1,450 +0,0 @@ -//! 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/graph_tests.rs b/crates/trainer/src/repertoire/graph_tests.rs deleted file mode 100644 index 23f9102..0000000 --- a/crates/trainer/src/repertoire/graph_tests.rs +++ /dev/null @@ -1,703 +0,0 @@ -use std::collections::BTreeSet; - -use chess_core::shakmaty::{CastlingMode, Position}; -use chess_core::{Game, NodeId}; - -use super::*; - -const NOW: i64 = 1_800_000_000; -const DAY: i64 = 24 * 60 * 60; - -fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { - library - .create(name, &chess_core::parse_str(pgn).game) - .unwrap() -} - -fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { - let mut library = Library::default(); - let id = add_repertoire(&mut library, "One", pgn); - (library, id) -} - -fn scope(id: RepertoireId, side: LearningSide) -> StatsScope { - StatsScope::for_repertoire(id, side, NOW) -} - -fn strings(moves: &[&str]) -> Vec { - moves.iter().map(|mv| (*mv).to_owned()).collect() -} - -fn key_at_path(repertoire: &Repertoire, path: &[String], expected_uci: &str) -> LearningItemKey { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let parent = tree.node_at_path(path).unwrap(); - LearningItemKey::local(tree.position_key(parent).unwrap(), expected_uci) -} - -fn learnt(item: &mut LearningItem, next_review_at: i64) { - item.introduced = true; - item.correct_streak = 3; - item.correct_count = 3; - item.last_review_at = Some(NOW - DAY); - item.last_correct_at = Some(NOW - DAY); - item.next_review_at = Some(next_review_at); - item.previous_interval_seconds = Some(DAY); -} - -fn pgn_with_white_moves(count: usize) -> String { - let mut game = Game::new(); - let mut position = game.start().position().clone(); - let mut node = NodeId::ROOT; - let mut visited = BTreeSet::from([fen4(&position)]); - for _ in 0..count * 2 - 1 { - let mut moves = position.legal_moves(); - moves.sort_by_key(|mv| mv.to_uci(CastlingMode::Standard).to_string()); - let mv = moves - .into_iter() - .find(|mv| { - let mut next = position.clone(); - next.play_unchecked(*mv); - !visited.contains(&fen4(&next)) - }) - .expect("fixture must have a non-repeating legal continuation"); - node = game.add_line(node, &[mv]).unwrap(); - position.play_unchecked(mv); - visited.insert(fen4(&position)); - } - game.to_pgn() -} - -fn transposition_pgn() -> &'static str { - "1. e4 d5 (1... Nf6 2. d4 d5 3. c4) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 e6 6. g3 *" -} - -#[test] -fn at_01_one_hundred_real_pgn_moves_are_unique_unseen_and_not_due() { - let (library, id) = single_repertoire(&pgn_with_white_moves(100)); - let learning = LearningData::default(); - let scoped = aggregate_scope( - &library, - &learning, - &scope(id, LearningSide::White), - &SrsSettings::default(), - ) - .unwrap(); - - assert_eq!(scoped.summary.total, 100); - assert_eq!(scoped.summary.unseen, 100); - assert_eq!(scoped.summary.learning, 0); - assert_eq!(scoped.summary.learnt, 0); - assert_eq!(scoped.summary.due, 0); - assert_eq!(scoped.items.len(), 100); - assert_eq!(scoped.scope.as_of, NOW); - assert!(learning.items.is_empty()); -} - -#[test] -fn at_07_zero_due_with_unseen_is_not_confirmed_current() { - let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 *"); - let scope = scope(id, LearningSide::White); - let mut learning = LearningData::default(); - let first = active_learning_keys(&library, &scope) - .unwrap() - .into_iter() - .find(|key| key.expected_uci == "e2e4") - .unwrap(); - let item = learning.ensure_item(first); - item.introduced = true; - item.correct_streak = 1; - item.next_review_at = Some(NOW + DAY); - - let scoped = aggregate_scope(&library, &learning, &scope, &SrsSettings::default()).unwrap(); - assert_eq!(scoped.summary.due, 0); - assert_eq!(scoped.summary.unseen, 1); - assert_eq!(scoped.summary.learning, 1); - assert_ne!( - scoped.summary.repertoire_status, - RepertoireStatus::ConfirmedCurrent - ); - assert_eq!( - scoped.summary.repertoire_status, - RepertoireStatus::InProgress - ); -} - -#[test] -fn at_14_two_repertoires_use_one_global_learning_item() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "Open", "1. e4 e5 2. Nf3 Nc6 *"); - let second = add_repertoire(&mut library, "Petrov", "1. e4 e5 2. Nf3 Nf6 *"); - let root = fen4(Game::new().start().position()); - let shared_key = LearningItemKey::local(root, "e2e4"); - let mut learning = LearningData::default(); - let shared_item = learning.ensure_item(shared_key.clone()); - shared_item.introduced = true; - shared_item.correct_streak = 2; - - let first_scope = scope(first.clone(), LearningSide::White); - let second_scope = scope(second.clone(), LearningSide::White); - let both_scope = StatsScope::new([first, second], LearningSide::White, NOW); - for selected in [&first_scope, &second_scope, &both_scope] { - let scoped = - aggregate_scope(&library, &learning, selected, &SrsSettings::default()).unwrap(); - assert_eq!(scoped.summary.total, 2); - assert_eq!(scoped.summary.learning, 1); - assert_eq!(scoped.summary.unseen, 1); - assert_eq!( - scoped - .items - .iter() - .filter(|item| item.key == shared_key) - .count(), - 1 - ); - } - assert_eq!(learning.items.len(), 1); - assert_eq!(learning.items[0].correct_streak, 2); -} - -#[test] -fn at_15_global_aggregate_is_union_not_sum_of_repertoire_rows() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "Two knights", "1. e4 e5 2. Nf3 Nc6 *"); - let second = add_repertoire(&mut library, "Petrov", "1. e4 e5 2. Nf3 Nf6 *"); - let learning = LearningData::default(); - let first_total = aggregate_scope( - &library, - &learning, - &scope(first.clone(), LearningSide::Black), - &SrsSettings::default(), - ) - .unwrap() - .summary - .total; - let second_total = aggregate_scope( - &library, - &learning, - &scope(second.clone(), LearningSide::Black), - &SrsSettings::default(), - ) - .unwrap() - .summary - .total; - let global = aggregate_scope( - &library, - &learning, - &StatsScope::new([first, second], LearningSide::Black, NOW), - &SrsSettings::default(), - ) - .unwrap(); - - assert_eq!((first_total, second_total), (2, 2)); - assert_eq!(global.summary.total, 3); - assert!(global.summary.total < first_total + second_total); -} - -#[test] -fn at_16_no_active_own_moves_is_empty_without_percentages() { - let (library, id) = single_repertoire("1. e4 *"); - let scoped = aggregate_scope( - &library, - &LearningData::default(), - &scope(id, LearningSide::Black), - &SrsSettings::default(), - ) - .unwrap(); - - assert_eq!(scoped.summary.total, 0); - assert_eq!(scoped.summary.repertoire_status, RepertoireStatus::Empty); - for percentage in [ - scoped.summary.coverage_percent, - scoped.summary.learnt_percent, - scoped.summary.confident_percent, - scoped.summary.learning_percent, - scoped.summary.unseen_percent, - ] { - assert_eq!(percentage, None); - } -} - -#[test] -fn at_17_depth_limits_summary_but_not_full_scope() { - let (library, id) = - single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 *"); - let full_scope = scope(id.clone(), LearningSide::White); - let depth_scope = full_scope.clone().with_max_depth(Some(10)); - let learning = LearningData::default(); - let depth = - aggregate_scope(&library, &learning, &depth_scope, &SrsSettings::default()).unwrap(); - let full = aggregate_scope(&library, &learning, &full_scope, &SrsSettings::default()).unwrap(); - - assert_eq!(depth.summary.total, 5); - assert_eq!(full.summary.total, 6); - assert!( - full.items - .iter() - .any(|item| item.key.expected_uci == "f1e1") - ); - assert!( - !depth - .items - .iter() - .any(|item| item.key.expected_uci == "f1e1") - ); -} - -#[test] -fn at_18_19_disable_and_reenable_preserve_global_history() { - let (mut library, id) = single_repertoire("1. e4 e5 (1... c5) 2. Nf3 *"); - let mut learning = LearningData::default(); - let nf3 = key_at_path( - library.repertoire(&id).unwrap(), - &strings(&["e2e4", "e7e5"]), - "g1f3", - ); - learnt(learning.ensure_item(nf3.clone()), NOW + DAY); - let before = learning.item(&nf3).unwrap().clone(); - let selected = scope(id.clone(), LearningSide::White); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "e7e5"]), true) - .unwrap(); - let disabled = - aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(disabled.summary.total, 1); - assert!(!disabled.items.iter().any(|item| item.key == nf3)); - assert_eq!(learning.item(&nf3), Some(&before)); - - let mut include_inactive = selected.clone(); - include_inactive.only_active = false; - assert_eq!( - aggregate_scope( - &library, - &learning, - &include_inactive, - &SrsSettings::default(), - ) - .unwrap() - .summary - .learnt, - 1 - ); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "e7e5"]), false) - .unwrap(); - let enabled = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(enabled.summary.total, 2); - assert_eq!(enabled.summary.learnt, 1); - assert_eq!(learning.item(&nf3), Some(&before)); -} - -#[test] -fn disabled_transposition_keeps_shared_key_through_another_active_branch() { - let (mut library, id) = single_repertoire(transposition_pgn()); - let selected = scope(id.clone(), LearningSide::White); - let shared = key_at_path( - library.repertoire(&id).unwrap(), - &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), - "c2c4", - ); - let mut learning = LearningData::default(); - learnt(learning.ensure_item(shared.clone()), NOW + DAY); - let before = learning.item(&shared).unwrap().clone(); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "d7d5"]), true) - .unwrap(); - let disabled_keys = active_learning_keys(&library, &selected).unwrap(); - assert!(disabled_keys.contains(&shared)); - assert_eq!(disabled_keys.len(), 3); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "d7d5"]), false) - .unwrap(); - let enabled_keys = active_learning_keys(&library, &selected).unwrap(); - assert!(enabled_keys.contains(&shared)); - assert_eq!(enabled_keys.len(), 7); - assert_eq!(learning.item(&shared), Some(&before)); -} - -#[test] -fn at_24_transposition_paths_share_one_key_and_progress() { - let (library, id) = single_repertoire(transposition_pgn()); - let repertoire = library.repertoire(&id).unwrap(); - let first_scope = - scope(id.clone(), LearningSide::White).with_branch_root(strings(&["e2e4", "d7d5"])); - let second_scope = scope(id, LearningSide::White).with_branch_root(strings(&["e2e4", "g8f6"])); - let first_keys = active_learning_keys(&library, &first_scope).unwrap(); - let second_keys = active_learning_keys(&library, &second_scope).unwrap(); - let shared: Vec<_> = first_keys.intersection(&second_keys).cloned().collect(); - let expected = key_at_path( - repertoire, - &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), - "c2c4", - ); - assert_eq!(shared.as_slice(), std::slice::from_ref(&expected)); - - let mut learning = LearningData::default(); - learnt(learning.ensure_item(expected), NOW + DAY); - for selected in [first_scope, second_scope] { - let scoped = - aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(scoped.summary.learnt, 1); - } - assert_eq!(learning.items.len(), 1); -} - -#[test] -fn at_25_adding_twenty_moves_recalculates_scope_and_preserves_successes() { - let (mut library, id) = single_repertoire(&pgn_with_white_moves(80)); - let selected = scope(id.clone(), LearningSide::White); - let old_keys = active_learning_keys(&library, &selected).unwrap(); - assert_eq!(old_keys.len(), 80); - let mut learning = LearningData::default(); - for key in old_keys { - learnt(learning.ensure_item(key), NOW + DAY); - } - let before = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(before.summary.learnt_percent, Some(100.0)); - - library.repertoire_mut(&id).unwrap().pgn = pgn_with_white_moves(100); - let after = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(after.summary.total, 100); - assert_eq!(after.summary.learnt, 80); - assert_eq!(after.summary.unseen, 20); - assert_eq!(after.summary.learnt_percent, Some(80.0)); - assert!(learning.items.iter().all(|item| item.correct_streak == 3)); -} - -#[test] -fn at_28_one_hundred_learnt_with_three_due_is_all_learnt_not_confirmed() { - let (library, id) = single_repertoire(&pgn_with_white_moves(100)); - let selected = scope(id, LearningSide::White); - let mut learning = LearningData::default(); - for (index, key) in active_learning_keys(&library, &selected) - .unwrap() - .into_iter() - .enumerate() - { - learnt( - learning.ensure_item(key), - if index < 3 { NOW } else { NOW + DAY }, - ); - } - let scoped = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(scoped.summary.total, 100); - assert_eq!(scoped.summary.learnt, 100); - assert_eq!(scoped.summary.due, 3); - assert_eq!( - scoped.summary.repertoire_status, - RepertoireStatus::AllLearnt - ); -} - -#[test] -fn at_29_one_hundred_fresh_learnt_without_due_is_confirmed_current() { - let (library, id) = single_repertoire(&pgn_with_white_moves(100)); - let selected = scope(id, LearningSide::White); - let mut learning = LearningData::default(); - for key in active_learning_keys(&library, &selected).unwrap() { - learnt(learning.ensure_item(key), NOW + DAY); - } - let scoped = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(scoped.summary.total, 100); - assert_eq!(scoped.summary.learnt, 100); - assert_eq!(scoped.summary.due, 0); - assert_eq!(scoped.summary.uncertain, 0); - assert_eq!( - scoped.summary.repertoire_status, - RepertoireStatus::ConfirmedCurrent - ); -} - -#[test] -fn at_30_lines_overlap_but_repertoire_is_not_an_arithmetic_mean() { - let (library, id) = single_repertoire(transposition_pgn()); - let repertoire = library.repertoire(&id).unwrap(); - let first_scope = - scope(id.clone(), LearningSide::White).with_branch_root(strings(&["e2e4", "d7d5"])); - let second_scope = - scope(id.clone(), LearningSide::White).with_branch_root(strings(&["e2e4", "g8f6"])); - let shared = key_at_path( - repertoire, - &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), - "c2c4", - ); - let mut learning = LearningData::default(); - learnt(learning.ensure_item(shared), NOW + DAY); - let first = - aggregate_scope(&library, &learning, &first_scope, &SrsSettings::default()).unwrap(); - let second = - aggregate_scope(&library, &learning, &second_scope, &SrsSettings::default()).unwrap(); - let full = aggregate_scope( - &library, - &learning, - &scope(id, LearningSide::White), - &SrsSettings::default(), - ) - .unwrap(); - - assert_eq!((first.summary.total, second.summary.total), (5, 2)); - assert_eq!(first.summary.learnt, 1); - assert_eq!(second.summary.learnt, 1); - assert_eq!(full.summary.total, 7); - assert_eq!(full.summary.learnt, 1); - let mean = - (first.summary.learnt_percent.unwrap() + second.summary.learnt_percent.unwrap()) / 2.0; - assert!((full.summary.learnt_percent.unwrap() - mean).abs() > f64::EPSILON); - let first_keys = active_learning_keys(&library, &first_scope).unwrap(); - let second_keys = active_learning_keys(&library, &second_scope).unwrap(); - assert_eq!(first_keys.union(&second_keys).count(), 6); - assert!(first_keys.union(&second_keys).count() < first_keys.len() + second_keys.len()); -} - -#[test] -fn all_answers_keep_real_pgn_context_and_shortest_graph_depth() { - let (library, id) = single_repertoire( - "1. e4 d5 (1... Nf6 2. d4 d5 3. g3) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 *", - ); - let full_scope = scope(id.clone(), LearningSide::White); - let full = active_learning_memberships(&library, &full_scope).unwrap(); - let c4 = full - .iter() - .find(|membership| membership.key.expected_uci == "c2c4") - .unwrap(); - assert_eq!(c4.min_depth, 5); - assert_eq!(c4.path.len(), 9); - let tree = RepertoireTree::from_game( - library.repertoire(&id).unwrap().game(), - u32::MAX, - Vec::new(), - ); - assert!( - tree.node_at_path(&c4.path).is_some(), - "context must be an actual annotated PGN path" - ); - assert_eq!(c4.path.last().map(String::as_str), Some("c2c4")); - assert!( - full.iter() - .any(|membership| membership.key.expected_uci == "g2g3") - ); - - let depth = - active_learning_memberships(&library, &full_scope.clone().with_max_depth(Some(5))).unwrap(); - assert!(depth.iter().any(|membership| membership.key == c4.key)); - assert!( - !active_learning_keys(&library, &full_scope.with_max_depth(Some(4))) - .unwrap() - .contains(&c4.key) - ); - - let short_branch = scope(id, LearningSide::White).with_branch_root(strings(&["e2e4", "g8f6"])); - let short_keys = active_learning_keys(&library, &short_branch).unwrap(); - assert_eq!(short_keys.len(), 2); - assert!(short_keys.iter().any(|key| key.expected_uci == "g2g3")); - assert!(!short_keys.iter().any(|key| key.expected_uci == "c2c4")); -} - -#[test] -fn main_answer_override_validates_side_and_pgn_move_and_roundtrips() { - let (library, id) = single_repertoire("1. e4 (1. d4) e5 *"); - let start = fen4(Game::new().start().position()); - let repertoire = library.repertoire(&id).unwrap(); - let original_pgn = repertoire.pgn.clone(); - let e4 = LearningItemKey::local(start.clone(), "e2e4"); - let d4 = LearningItemKey::local(start.clone(), "d2d4"); - let selected = scope(id.clone(), LearningSide::White); - let default_keys = active_learning_keys(&library, &selected).unwrap(); - assert!(default_keys.contains(&e4)); - assert!(default_keys.contains(&d4)); - - let mut changed = repertoire.clone(); - changed - .set_main_answer_override(&start, "d2d4", LearningSide::White) - .unwrap(); - assert_eq!(changed.main_answer_override(&start), Some("d2d4")); - assert!(matches!( - changed.set_main_answer_override(&start, "e7e5", LearningSide::Black), - Err(RepertoireError::MainAnswerWrongSide { .. }) - )); - assert!(matches!( - changed.set_main_answer_override(&start, "c2c4", LearningSide::White), - Err(RepertoireError::MainAnswerMoveNotFound { .. }) - )); - assert!(matches!( - changed.set_main_answer_override("missing", "d2d4", LearningSide::White), - Err(RepertoireError::MainAnswerPositionNotFound(_)) - )); - assert_eq!(changed.main_answer_override(&start), Some("d2d4")); - assert_eq!(changed.pgn, original_pgn); - - let encoded = serde_json::to_string(&changed).unwrap(); - let restored: Repertoire = serde_json::from_str(&encoded).unwrap(); - assert_eq!(restored.main_answer_override(&start), Some("d2d4")); - let mut old_json = serde_json::to_value(&changed).unwrap(); - old_json - .as_object_mut() - .unwrap() - .remove("main_answer_overrides"); - let old: Repertoire = serde_json::from_value(old_json).unwrap(); - assert!(old.main_answer_overrides.is_empty()); - - let mut overridden_library = Library::default(); - overridden_library.repertoires.push(changed.clone()); - let overridden = active_learning_keys(&overridden_library, &selected).unwrap(); - assert!(overridden.contains(&d4)); - assert!(overridden.contains(&e4)); - assert_eq!(overridden, default_keys); - let ordered = active_learning_memberships(&overridden_library, &selected).unwrap(); - let preferred = ordered.iter().find(|item| item.key == d4).unwrap(); - let other = ordered.iter().find(|item| item.key == e4).unwrap(); - assert!(preferred.pgn_order < other.pgn_order); - assert_eq!( - changed.clear_main_answer_override(&start).as_deref(), - Some("d2d4") - ); - assert_eq!(changed.clear_main_answer_override(&start), None); - - overridden_library.repertoires[0].clear_main_answer_override(&start); - let second = add_repertoire(&mut overridden_library, "Queen pawn", "1. e4 (1. d4) e5 *"); - overridden_library - .repertoire_mut(&second) - .unwrap() - .set_main_answer_override(&start, "d2d4", LearningSide::White) - .unwrap(); - let global = active_learning_keys( - &overridden_library, - &StatsScope::new([id, second], LearningSide::White, NOW), - ) - .unwrap(); - assert!(global.contains(&e4)); - assert!(global.contains(&d4)); - assert_eq!(global.len(), 2); -} - -#[test] -fn both_training_mode_is_rejected_for_learning_statistics() { - assert_eq!( - LearningSide::try_from(TrainingMode::White), - Ok(LearningSide::White) - ); - assert_eq!( - LearningSide::try_from(TrainingMode::Black), - Ok(LearningSide::Black) - ); - assert_eq!( - LearningSide::try_from(TrainingMode::Both), - Err(LearningGraphError::BothSidesNotSupported) - ); -} - -#[test] -fn repeated_fen4_cycle_terminates_and_deduplicates_items() { - let (library, id) = single_repertoire("1. Nf3 Nf6 2. Ng1 Ng8 3. Nf3 Nf6 4. Ng1 Ng8 *"); - let memberships = - active_learning_memberships(&library, &scope(id, LearningSide::White)).unwrap(); - assert_eq!(memberships.len(), 2); - let mut depths: Vec<_> = memberships - .iter() - .map(|membership| membership.min_depth) - .collect(); - depths.sort_unstable(); - assert_eq!(depths, [1, 3]); -} - -#[test] -fn aggregate_scope_uses_one_explicit_as_of() { - let (library, id) = single_repertoire("1. e4 *"); - let mut selected = scope(id, LearningSide::White); - let key = active_learning_keys(&library, &selected) - .unwrap() - .into_iter() - .next() - .unwrap(); - let mut learning = LearningData::default(); - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 1; - item.next_review_at = Some(NOW); - - selected.as_of = NOW - 1; - let before = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(before.summary.due, 0); - assert_eq!(before.summary.next_due_at, Some(NOW)); - assert_eq!(before.scope.as_of, NOW - 1); - - selected.as_of = NOW; - let due = aggregate_scope(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(due.summary.due, 1); - assert_eq!(due.summary.next_due_at, None); - assert_eq!(due.scope.as_of, NOW); -} - -#[test] -fn reset_impact_projects_n_m_and_names_without_resetting() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "First", "1. e4 e5 2. Nf3 *"); - let second = add_repertoire(&mut library, "Second", "1. e4 c5 2. c4 *"); - let selected = scope(first, LearningSide::White); - let mut learning = LearningData::default(); - for key in active_learning_keys(&library, &selected).unwrap() { - learnt(learning.ensure_item(key), NOW + DAY); - } - let before = learning.clone(); - - let impact = reset_impact(&library, &selected).unwrap(); - assert_eq!(impact.reset_count, 2); - assert_eq!(impact.shared_count, 1); - assert_eq!(impact.affected_repertoires.len(), 2); - let first_impact = impact - .affected_repertoires - .iter() - .find(|repertoire| repertoire.name == "First") - .unwrap(); - let second_impact = impact - .affected_repertoires - .iter() - .find(|repertoire| repertoire.name == "Second") - .unwrap(); - assert_eq!(first_impact.item_count, 2); - assert_eq!(second_impact.item_count, 1); - assert!( - impact - .affected_repertoires - .iter() - .any(|repertoire| repertoire.id == second) - ); - assert_eq!(learning, before); -} - -#[test] -fn disabling_one_answer_keeps_other_active_variations() { - let (mut library, id) = single_repertoire("1. e4 (1. d4) e5 *"); - let selected = scope(id.clone(), LearningSide::White); - let root = fen4(Game::new().start().position()); - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4"]), true) - .unwrap(); - assert_eq!( - active_learning_keys(&library, &selected).unwrap(), - BTreeSet::from([LearningItemKey::local(root.clone(), "d2d4")]) - ); - - library - .repertoire_mut(&id) - .unwrap() - .set_main_answer_override(&root, "d2d4", LearningSide::White) - .unwrap(); - assert_eq!( - active_learning_keys(&library, &selected).unwrap(), - BTreeSet::from([LearningItemKey::local(root, "d2d4")]) - ); -} diff --git a/crates/trainer/src/repertoire/learning.rs b/crates/trainer/src/repertoire/learning.rs deleted file mode 100644 index 1e63e6c..0000000 --- a/crates/trainer/src/repertoire/learning.rs +++ /dev/null @@ -1,298 +0,0 @@ -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -pub const LOCAL_PROFILE_ID: &str = "local"; - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct LearningItemKey { - pub user_id: String, - pub position_fen4: String, - pub expected_uci: String, -} - -impl LearningItemKey { - pub fn new( - user_id: impl Into, - position_fen4: impl Into, - expected_uci: impl Into, - ) -> Self { - Self { - user_id: user_id.into(), - position_fen4: position_fen4.into(), - expected_uci: expected_uci.into(), - } - } - - pub fn local(position_fen4: impl Into, expected_uci: impl Into) -> Self { - Self::new(LOCAL_PROFILE_ID, position_fen4, expected_uci) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct WrongMoveStats { - pub count: u64, - pub last_at: i64, -} - -pub const RECENT_INDEPENDENT_OUTCOMES_LIMIT: usize = 10; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum IndependentResult { - Correct, - Wrong, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct IndependentOutcome { - pub result: IndependentResult, - pub happened_at: i64, -} - -/// Learning state for one user/FEN4/UCI key. Timestamps are UTC Unix seconds. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct LearningItem { - pub key: LearningItemKey, - pub introduced: bool, - pub correct_streak: u32, - pub wrong_streak: u32, - /// Only CORRECT_INDEPENDENT events increment this counter. - pub correct_count: u64, - /// Only INCORRECT_INDEPENDENT events increment this counter. - pub wrong_count: u64, - pub last_review_at: Option, - /// SRS growth base; an independent wrong answer clears it as before. - pub last_correct_at: Option, - pub next_review_at: Option, - pub previous_interval_seconds: Option, - pub last_wrong_move_uci: Option, - pub last_wrong_at: Option, - pub wrong_move_histogram: BTreeMap, - /// Response times of independent attempts only; contextual events are excluded. - pub independent_response_times_ms: Vec, - #[serde(default)] - pub last_independent_at: Option, - #[serde(default)] - pub last_independent_correct_at: Option, - #[serde(default)] - pub last_independent_wrong_at: Option, - #[serde(default)] - pub last_independent_result: Option, - #[serde(default)] - pub recent_independent_outcomes: Vec, - #[serde(default)] - pub resistant: bool, -} - -impl LearningItem { - pub fn new(key: LearningItemKey) -> Self { - Self { - key, - introduced: false, - correct_streak: 0, - wrong_streak: 0, - correct_count: 0, - wrong_count: 0, - last_review_at: None, - last_correct_at: None, - next_review_at: None, - previous_interval_seconds: None, - last_wrong_move_uci: None, - last_wrong_at: None, - wrong_move_histogram: BTreeMap::new(), - independent_response_times_ms: Vec::new(), - last_independent_at: None, - last_independent_correct_at: None, - last_independent_wrong_at: None, - last_independent_result: None, - recent_independent_outcomes: Vec::new(), - resistant: false, - } - } - - pub fn is_unseen(&self) -> bool { - !self.introduced - } - - pub fn is_learning(&self) -> bool { - self.introduced && self.correct_streak < 3 - } - - pub fn is_learnt(&self) -> bool { - self.introduced && self.correct_streak >= 3 - } - - pub fn is_due(&self, now: i64) -> bool { - self.introduced && self.next_review_at.is_some_and(|next| next <= now) - } - - pub fn is_resistant(&self) -> bool { - self.resistant - } - - pub fn independent_attempt_count(&self) -> u64 { - self.correct_count.saturating_add(self.wrong_count) - } - - pub fn accuracy_percent(&self) -> Option { - let attempts = self.independent_attempt_count(); - (attempts > 0).then(|| 100.0 * self.correct_count as f64 / attempts as f64) - } - - pub fn response_time_median_ms(&self) -> Option { - median(&self.independent_response_times_ms) - } - - pub(crate) fn record_independent_outcome(&mut self, result: IndependentResult, now: i64) { - self.last_independent_at = Some(now); - self.last_independent_result = Some(result); - match result { - IndependentResult::Correct => self.last_independent_correct_at = Some(now), - IndependentResult::Wrong => self.last_independent_wrong_at = Some(now), - } - self.recent_independent_outcomes.push(IndependentOutcome { - result, - happened_at: now, - }); - if self.recent_independent_outcomes.len() > RECENT_INDEPENDENT_OUTCOMES_LIMIT { - let excess = self - .recent_independent_outcomes - .len() - .saturating_sub(RECENT_INDEPENDENT_OUTCOMES_LIMIT); - self.recent_independent_outcomes.drain(..excess); - } - - let wrong_count = self - .recent_independent_outcomes - .iter() - .filter(|outcome| outcome.result == IndependentResult::Wrong) - .count(); - let correct_since_error = self - .recent_independent_outcomes - .iter() - .rev() - .take_while(|outcome| outcome.result == IndependentResult::Correct) - .count(); - if correct_since_error >= 3 { - self.resistant = false; - } else if self.recent_independent_outcomes.len() >= 5 && wrong_count >= 3 { - self.resistant = true; - } - } -} - -pub fn is_resistant(item: &LearningItem) -> bool { - item.is_resistant() -} - -fn median(values: &[u64]) -> Option { - if values.is_empty() { - return None; - } - let mut sorted = values.to_vec(); - sorted.sort_unstable(); - let middle = sorted.len() / 2; - if sorted.len().is_multiple_of(2) { - Some((sorted[middle - 1] as f64 + sorted[middle] as f64) / 2.0) - } else { - Some(sorted[middle] as f64) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum TrainingEventType { - CorrectIndependent, - IncorrectIndependent, - Previewed, - ReplayAfterError, - AutoContext, - IllegalMove, -} - -impl TrainingEventType { - pub fn is_independent(self) -> bool { - matches!(self, Self::CorrectIndependent | Self::IncorrectIndependent) - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct TrainingAttempt { - pub user_id: String, - pub position_fen4: String, - pub client_attempt_id: String, - pub session_id: String, - pub event_type: TrainingEventType, - pub expected_uci: String, - pub actual_uci: Option, - pub response_time_ms: Option, - /// UTC Unix seconds assigned by the event-recording boundary. - pub happened_at: i64, -} - -impl TrainingAttempt { - pub fn item_key(&self) -> LearningItemKey { - LearningItemKey::new( - self.user_id.clone(), - self.position_fen4.clone(), - self.expected_uci.clone(), - ) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum AttemptApplication { - Applied, - Duplicate, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LearningError { - EmptyClientAttemptId, - WrongLearningItem, - MissingActualMove, -} - -impl std::fmt::Display for LearningError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::EmptyClientAttemptId => f.write_str("client attempt id must not be empty"), - Self::WrongLearningItem => { - f.write_str("training attempt belongs to a different learning item") - } - Self::MissingActualMove => { - f.write_str("an independent wrong attempt must contain the actual UCI move") - } - } - } -} - -impl std::error::Error for LearningError {} - -/// In-memory learning state and its idempotency journal; persistence is a separate layer. -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct LearningData { - pub items: Vec, - pub attempts: Vec, - #[serde(flatten)] - pub extensions: BTreeMap, -} - -impl LearningData { - pub fn item(&self, key: &LearningItemKey) -> Option<&LearningItem> { - self.items.iter().find(|item| &item.key == key) - } - - pub fn ensure_item(&mut self, key: LearningItemKey) -> &mut LearningItem { - let index = match self.items.iter().position(|item| item.key == key) { - Some(index) => index, - None => { - self.items.push(LearningItem::new(key)); - self.items.len() - 1 - } - }; - &mut self.items[index] - } -} diff --git a/crates/trainer/src/repertoire/learning_analytics.rs b/crates/trainer/src/repertoire/learning_analytics.rs deleted file mode 100644 index b919792..0000000 --- a/crates/trainer/src/repertoire/learning_analytics.rs +++ /dev/null @@ -1,348 +0,0 @@ -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use super::aggregate::is_uncertain; -use super::learning::{ - IndependentResult, LearningData, LearningItem, LearningItemKey, WrongMoveStats, -}; -use super::learning_graph::{ - LearningGraphError, LearningItemMembership, StatsScope, active_learning_memberships, - aggregate_scope, -}; -use super::model::Library; -use super::srs::SrsSettings; - -pub const SECONDS_PER_DAY: i64 = 24 * 60 * 60; -pub const SCHEDULED_WEEK_SECONDS: i64 = 7 * SECONDS_PER_DAY; -pub const SCHEDULED_MONTH_SECONDS: i64 = 30 * SECONDS_PER_DAY; -pub const SCHEDULED_YEAR_SECONDS: i64 = 365 * SECONDS_PER_DAY; - -/// Fixed UTC offset used for local calendar dates. The caller resolves named zones and DST. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct LocalDatePolicy { - pub utc_offset_seconds: i32, -} - -impl LocalDatePolicy { - pub const UTC: Self = Self { - utc_offset_seconds: 0, - }; - - pub const fn fixed(utc_offset_seconds: i32) -> Self { - Self { utc_offset_seconds } - } - - pub fn date(self, as_of: i64) -> String { - let local = i128::from(as_of) + i128::from(self.utc_offset_seconds); - civil_date(local.div_euclid(i128::from(SECONDS_PER_DAY))) - } - - /// Exclusive UTC boundary of the current local day: the next local midnight. - pub fn end_of_local_day_exclusive(self, as_of: i64) -> i64 { - let offset = i128::from(self.utc_offset_seconds); - let local = i128::from(as_of) + offset; - let next_midnight = - (local.div_euclid(i128::from(SECONDS_PER_DAY)) + 1) * i128::from(SECONDS_PER_DAY); - clamp_i64(next_midnight - offset) - } -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ScheduledBuckets { - pub overdue: usize, - pub today: usize, - pub week: usize, - pub month: usize, - pub year: usize, - pub later: usize, -} - -impl ScheduledBuckets { - pub fn introduced(self) -> usize { - self.overdue - .saturating_add(self.today) - .saturating_add(self.week) - .saturating_add(self.month) - .saturating_add(self.year) - .saturating_add(self.later) - } -} - -/// Today ends at the explicit local midnight; all other ranges use fixed durations. -/// An introduced item without a schedule is overdue so the buckets remain a partition. -pub fn scheduled_buckets<'a>( - items: impl IntoIterator, - now: i64, - local_date: LocalDatePolicy, -) -> ScheduledBuckets { - let end_today = local_date.end_of_local_day_exclusive(now); - let end_week = now.saturating_add(SCHEDULED_WEEK_SECONDS); - let end_month = now.saturating_add(SCHEDULED_MONTH_SECONDS); - let end_year = now.saturating_add(SCHEDULED_YEAR_SECONDS); - let mut buckets = ScheduledBuckets::default(); - for item in unique_items(items).into_values() { - if item.is_unseen() { - continue; - } - let bucket = match item.next_review_at { - None => &mut buckets.overdue, - Some(next) if next <= now => &mut buckets.overdue, - Some(next) if next < end_today => &mut buckets.today, - Some(next) if next < end_week => &mut buckets.week, - Some(next) if next < end_month => &mut buckets.month, - Some(next) if next < end_year => &mut buckets.year, - Some(_) => &mut buckets.later, - }; - *bucket = bucket.saturating_add(1); - } - buckets -} - -pub type CorrectStreakHistogram = BTreeMap; -pub type WrongStreakHistogram = BTreeMap; -pub type AttemptsHistogram = BTreeMap; - -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct SequenceHistograms { - pub correct_streak: CorrectStreakHistogram, - pub wrong_streak: WrongStreakHistogram, - pub attempts: AttemptsHistogram, -} - -pub fn sequence_histograms<'a>( - items: impl IntoIterator, -) -> SequenceHistograms { - let mut histograms = SequenceHistograms::default(); - for item in unique_items(items).into_values() { - increment(&mut histograms.correct_streak, item.correct_streak); - increment(&mut histograms.wrong_streak, item.wrong_streak); - increment(&mut histograms.attempts, item.independent_attempt_count()); - } - histograms -} - -pub fn correct_streak_histogram<'a>( - items: impl IntoIterator, -) -> CorrectStreakHistogram { - sequence_histograms(items).correct_streak -} - -pub fn wrong_streak_histogram<'a>( - items: impl IntoIterator, -) -> WrongStreakHistogram { - sequence_histograms(items).wrong_streak -} - -pub fn attempts_histogram<'a>( - items: impl IntoIterator, -) -> AttemptsHistogram { - sequence_histograms(items).attempts -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum MoveLearningStatus { - Unseen, - Learning, - LearntFresh, - Uncertain, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct MoveLearningAnalytics { - pub key: LearningItemKey, - pub status: MoveLearningStatus, - pub resistant: bool, - pub accuracy_percent: Option, - pub correct_count: u64, - pub wrong_count: u64, - pub independent_attempts: u64, - pub correct_streak: u32, - pub wrong_streak: u32, - pub last_review_at: Option, - pub last_independent_at: Option, - pub last_independent_result: Option, - pub last_independent_correct_at: Option, - pub last_independent_wrong_at: Option, - pub next_review_at: Option, - pub review_in_seconds: Option, - pub overdue_seconds: Option, - pub uncertain_grace_seconds: Option, - pub wrong_move_histogram: BTreeMap, - pub response_time_median_ms: Option, - pub memberships: Vec, -} - -pub fn move_learning_analytics( - item: &LearningItem, - now: i64, - settings: &SrsSettings, -) -> MoveLearningAnalytics { - let uncertain = is_uncertain(item, now, settings); - let status = if item.is_unseen() { - MoveLearningStatus::Unseen - } else if !item.is_learnt() { - MoveLearningStatus::Learning - } else if uncertain { - MoveLearningStatus::Uncertain - } else { - MoveLearningStatus::LearntFresh - }; - let uncertain_grace_seconds = (item.is_learnt() && item.next_review_at.is_some()) - .then(|| { - item.previous_interval_seconds.unwrap_or(0).max(0) - / i64::from(settings.uncertain_interval_divisor.max(1)) - }) - .map(|interval_grace| { - settings - .uncertain_min_grace_seconds - .max(0) - .max(interval_grace) - }); - MoveLearningAnalytics { - key: item.key.clone(), - status, - resistant: item.is_resistant(), - accuracy_percent: item.accuracy_percent(), - correct_count: item.correct_count, - wrong_count: item.wrong_count, - independent_attempts: item.independent_attempt_count(), - correct_streak: item.correct_streak, - wrong_streak: item.wrong_streak, - last_review_at: item.last_review_at, - last_independent_at: item.last_independent_at, - last_independent_result: item.last_independent_result, - last_independent_correct_at: item.last_independent_correct_at, - last_independent_wrong_at: item.last_independent_wrong_at, - next_review_at: item.next_review_at, - review_in_seconds: item - .next_review_at - .filter(|next| *next > now) - .map(|next| next.saturating_sub(now)), - overdue_seconds: item - .next_review_at - .map(|next| now.saturating_sub(next).max(0)), - uncertain_grace_seconds, - wrong_move_histogram: item.wrong_move_histogram.clone(), - response_time_median_ms: item.response_time_median_ms(), - memberships: Vec::new(), - } -} - -pub fn scoped_move_learning_analytics( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - settings: &SrsSettings, -) -> Result, LearningGraphError> { - let scoped = aggregate_scope(library, learning, scope, settings)?; - let mut memberships_by_key: BTreeMap> = - BTreeMap::new(); - for membership in active_learning_memberships(library, scope)? { - memberships_by_key - .entry(membership.key.clone()) - .or_default() - .push(membership); - } - Ok(scoped - .items - .iter() - .map(|item| { - let mut analytics = move_learning_analytics(item, scope.as_of, settings); - analytics.memberships = memberships_by_key.remove(&item.key).unwrap_or_default(); - analytics - }) - .collect()) -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct LearningSnapshot { - pub date: String, - pub scope: StatsScope, - pub as_of: i64, - pub timezone: LocalDatePolicy, - pub total: usize, - pub unseen: usize, - pub learning: usize, - pub learnt: usize, - pub uncertain: usize, - pub due: usize, -} - -impl LearningSnapshot { - pub fn capture( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - settings: &SrsSettings, - timezone: LocalDatePolicy, - ) -> Result { - let scoped = aggregate_scope(library, learning, scope, settings)?; - Ok(Self { - date: timezone.date(scope.as_of), - scope: scope.clone(), - as_of: scope.as_of, - timezone, - total: scoped.summary.total, - unseen: scoped.summary.unseen, - learning: scoped.summary.learning, - learnt: scoped.summary.learnt, - uncertain: scoped.summary.uncertain, - due: scoped.summary.due, - }) - } -} - -pub(crate) fn same_snapshot_slot(left: &LearningSnapshot, right: &LearningSnapshot) -> bool { - if left.date != right.date { - return false; - } - let mut left_scope = left.scope.clone(); - let mut right_scope = right.scope.clone(); - left_scope.as_of = 0; - right_scope.as_of = 0; - left_scope == right_scope -} - -fn unique_items<'a>( - items: impl IntoIterator, -) -> BTreeMap<&'a LearningItemKey, &'a LearningItem> { - let mut unique = BTreeMap::new(); - for item in items { - unique.entry(&item.key).or_insert(item); - } - unique -} - -fn increment(histogram: &mut BTreeMap, key: K) { - let count = histogram.entry(key).or_default(); - *count = count.saturating_add(1); -} - -fn clamp_i64(value: i128) -> i64 { - if value < i128::from(i64::MIN) { - i64::MIN - } else if value > i128::from(i64::MAX) { - i64::MAX - } else { - value as i64 - } -} - -fn civil_date(days_since_unix_epoch: i128) -> String { - let shifted = days_since_unix_epoch + 719_468; - let era = shifted.div_euclid(146_097); - let day_of_era = shifted - era * 146_097; - let year_of_era = - (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; - let mut year = year_of_era + era * 400; - let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); - let month_prime = (5 * day_of_year + 2) / 153; - let day = day_of_year - (153 * month_prime + 2) / 5 + 1; - let month = month_prime + if month_prime < 10 { 3 } else { -9 }; - if month <= 2 { - year += 1; - } - format!("{year:04}-{month:02}-{day:02}") -} diff --git a/crates/trainer/src/repertoire/learning_context.rs b/crates/trainer/src/repertoire/learning_context.rs deleted file mode 100644 index a82fc9d..0000000 --- a/crates/trainer/src/repertoire/learning_context.rs +++ /dev/null @@ -1,131 +0,0 @@ -use std::collections::BTreeSet; - -use serde::{Deserialize, Serialize}; - -use crate::repertoire::learning::{LearningData, LearningItem, LearningItemKey}; - -const SECONDS_PER_DAY: i64 = 24 * 60 * 60; -const MIN_SPEED_FACTOR: f64 = 0.25; -const MAX_SPEED_FACTOR: f64 = 4.0; - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct LearningContextPolicy { - pub reinforce_minimum_correct: u32, - pub reinforce_minimum_days: Option, - pub dont_show_start_moves_threshold: u32, - pub use_fixed_piece_speed: bool, - pub move_speed_adjustment: f64, - pub consider_leadup_moves: bool, -} - -impl Default for LearningContextPolicy { - fn default() -> Self { - Self { - reinforce_minimum_correct: 3, - reinforce_minimum_days: None, - dont_show_start_moves_threshold: 100, - use_fixed_piece_speed: true, - move_speed_adjustment: 1.0, - consider_leadup_moves: false, - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum LearningContextAction { - Automatic, - Independent, -} - -pub(crate) struct LearningContextMove { - pub key: LearningItemKey, - pub own_move: bool, - pub least_recent_target: bool, -} - -pub(crate) struct LearningContextPlan { - pub actions: Vec, - pub skip_prefix: usize, -} - -pub(crate) fn plan_context( - moves: &[LearningContextMove], - learning: &LearningData, - policy: &LearningContextPolicy, - completed_keys: &BTreeSet, - least_recent: bool, - now: i64, -) -> LearningContextPlan { - let actions = moves - .iter() - .map(|context| { - if !context.own_move || completed_keys.contains(&context.key) { - return LearningContextAction::Automatic; - } - let item = learning.item(&context.key); - let reinforce = - policy.consider_leadup_moves && requires_reinforcement(item, policy, now); - if (least_recent && context.least_recent_target) || reinforce { - LearningContextAction::Independent - } else { - LearningContextAction::Automatic - } - }) - .collect::>(); - let mut skip_prefix = 0; - let mut known_own_move = false; - let mut stopped = false; - for (index, (context, action)) in moves.iter().zip(&actions).enumerate() { - if *action == LearningContextAction::Independent - || (context.own_move && !very_well_known(learning.item(&context.key), policy)) - { - skip_prefix = if known_own_move { index } else { 0 }; - stopped = true; - break; - } - known_own_move |= context.own_move; - } - if known_own_move && !stopped { - skip_prefix = moves.len(); - } - LearningContextPlan { - actions, - skip_prefix, - } -} - -pub(crate) fn speed_factor(policy: &LearningContextPolicy, item: Option<&LearningItem>) -> f64 { - if policy.use_fixed_piece_speed { - return 1.0; - } - let adjustment = if policy.move_speed_adjustment.is_finite() { - policy.move_speed_adjustment - } else { - 1.0 - }; - let scale = u32::max(policy.reinforce_minimum_correct, 1); - let knowledge = - f64::from(item.map_or(0, |item| item.correct_streak).min(scale)) / f64::from(scale); - (adjustment * (1.0 + knowledge)).clamp(MIN_SPEED_FACTOR, MAX_SPEED_FACTOR) -} - -fn requires_reinforcement( - item: Option<&LearningItem>, - policy: &LearningContextPolicy, - now: i64, -) -> bool { - let weak = item.map_or(0, |item| item.correct_streak) < policy.reinforce_minimum_correct; - let due_soon = policy.reinforce_minimum_days.is_some_and(|days| { - let horizon = now.saturating_add(i64::from(days).saturating_mul(SECONDS_PER_DAY)); - item.is_some_and(|item| { - item.introduced && item.next_review_at.is_some_and(|next| next <= horizon) - }) - }); - weak || due_soon -} - -fn very_well_known(item: Option<&LearningItem>, policy: &LearningContextPolicy) -> bool { - policy.dont_show_start_moves_threshold > 0 - && item.is_some_and(|item| item.correct_streak >= policy.dont_show_start_moves_threshold) -} diff --git a/crates/trainer/src/repertoire/learning_graph.rs b/crates/trainer/src/repertoire/learning_graph.rs deleted file mode 100644 index ed22ad2..0000000 --- a/crates/trainer/src/repertoire/learning_graph.rs +++ /dev/null @@ -1,629 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use std::fmt; - -use chess_core::MoveKind; -use chess_core::shakmaty::{CastlingMode, Position}; -use serde::{Deserialize, Serialize}; - -use super::aggregate::{LearningAggregate, aggregate}; -use super::learning::{LearningData, LearningItem, LearningItemKey}; -use super::learning_modes::LearningPriority; -use super::model::{LearningSide, Library, Repertoire, RepertoireId}; -use super::srs::SrsSettings; -use super::stats::TrainingMode; -use super::tree::RepertoireTree; - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct StatsScope { - pub repertoire_ids: BTreeSet, - pub side: LearningSide, - pub max_depth: Option, - #[serde(default = "default_only_active")] - pub only_active: bool, - pub branch_root: Option>, - pub as_of: i64, - #[serde(default)] - pub learning_priority: LearningPriority, -} - -impl StatsScope { - pub fn new( - repertoire_ids: impl IntoIterator, - side: LearningSide, - as_of: i64, - ) -> Self { - Self { - repertoire_ids: repertoire_ids.into_iter().collect(), - side, - max_depth: None, - only_active: true, - branch_root: None, - as_of, - learning_priority: LearningPriority::default(), - } - } - - pub fn for_repertoire(id: RepertoireId, side: LearningSide, as_of: i64) -> Self { - Self::new([id], side, as_of) - } - - pub fn with_max_depth(mut self, max_depth: Option) -> Self { - self.max_depth = max_depth; - self - } - - pub fn with_branch_root(mut self, branch_root: Vec) -> Self { - self.branch_root = Some(branch_root); - self - } - - pub fn with_learning_priority(mut self, learning_priority: LearningPriority) -> Self { - self.learning_priority = learning_priority; - self - } -} - -fn default_only_active() -> bool { - true -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct LearningItemMembership { - pub repertoire_id: RepertoireId, - pub key: LearningItemKey, - pub min_depth: u32, - pub path: Vec, - #[serde(default)] - pub pgn_order: usize, - #[serde(default)] - pub variation_depth: u32, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct ScopedLearningAggregate { - pub scope: StatsScope, - pub items: Vec, - pub summary: LearningAggregate, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct ResetRepertoireImpact { - pub id: RepertoireId, - pub name: String, - pub item_count: usize, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] -pub struct ResetImpactProjection { - pub reset_count: usize, - pub shared_count: usize, - pub affected_repertoires: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LearningGraphError { - BothSidesNotSupported, - RepertoireNotFound(RepertoireId), - BranchRootNotFound { - repertoire_id: RepertoireId, - branch_root: Vec, - }, - DepthOverflow(RepertoireId), - TrainingPathGeneration { - repertoire_id: RepertoireId, - message: String, - }, -} - -impl fmt::Display for LearningGraphError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::BothSidesNotSupported => { - f.write_str("learning statistics require exactly one side, not Both") - } - Self::RepertoireNotFound(id) => write!(f, "repertoire not found: {id}"), - Self::BranchRootNotFound { - repertoire_id, - branch_root, - } => write!( - f, - "branch root {} is not present in repertoire {repertoire_id}", - branch_root.join(" ") - ), - Self::DepthOverflow(id) => { - write!( - f, - "learning depth exceeds the supported limit in repertoire {id}" - ) - } - Self::TrainingPathGeneration { - repertoire_id, - message, - } => write!( - f, - "could not generate training paths in repertoire {repertoire_id}: {message}" - ), - } - } -} - -impl std::error::Error for LearningGraphError {} - -impl TryFrom for LearningSide { - type Error = LearningGraphError; - - fn try_from(mode: TrainingMode) -> Result { - match mode { - TrainingMode::White => Ok(Self::White), - TrainingMode::Black => Ok(Self::Black), - TrainingMode::Both => Err(LearningGraphError::BothSidesNotSupported), - } - } -} - -#[derive(Clone, Debug)] -struct GraphEdge { - /// Actual PGN occurrence; graph shortcuts must not invent a context path. - source_path: Vec, - uci: String, - to: String, - parent_order: usize, - child_order: usize, - pgn_order: usize, -} - -#[derive(Clone, Debug)] -struct PositionEntry { - side: LearningSide, - edges: Vec, -} - -pub fn active_learning_memberships( - library: &Library, - scope: &StatsScope, -) -> Result, LearningGraphError> { - let mut memberships = Vec::new(); - for id in &scope.repertoire_ids { - let repertoire = library - .repertoire(id) - .ok_or_else(|| LearningGraphError::RepertoireNotFound(id.clone()))?; - memberships.extend(repertoire_memberships(repertoire, scope)?); - } - memberships.sort_by(|left, right| { - (&left.repertoire_id, &left.key).cmp(&(&right.repertoire_id, &right.key)) - }); - Ok(memberships) -} - -pub fn active_learning_keys( - library: &Library, - scope: &StatsScope, -) -> Result, LearningGraphError> { - Ok(active_learning_memberships(library, scope)? - .into_iter() - .map(|membership| membership.key) - .collect()) -} - -pub fn aggregate_scope( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - settings: &SrsSettings, -) -> Result { - let keys = active_learning_keys(library, scope)?; - let items: Vec<_> = keys - .into_iter() - .map(|key| { - learning - .item(&key) - .cloned() - .unwrap_or_else(|| LearningItem::new(key)) - }) - .collect(); - let summary = aggregate(items.iter(), scope.as_of, settings); - Ok(ScopedLearningAggregate { - scope: scope.clone(), - items, - summary, - }) -} - -pub fn reset_impact( - library: &Library, - scope: &StatsScope, -) -> Result { - let selected_memberships = active_learning_memberships(library, scope)?; - let selected_keys: BTreeSet<_> = selected_memberships - .iter() - .map(|membership| membership.key.clone()) - .collect(); - let mut selected_by_repertoire: BTreeMap> = - BTreeMap::new(); - for membership in selected_memberships { - selected_by_repertoire - .entry(membership.repertoire_id) - .or_default() - .insert(membership.key); - } - - let mut shared_keys = BTreeSet::new(); - let mut affected_repertoires = Vec::new(); - for repertoire in &library.repertoires { - let selected = scope.repertoire_ids.contains(&repertoire.id); - let impacted_keys = if selected { - selected_by_repertoire - .remove(&repertoire.id) - .unwrap_or_default() - } else { - let other_scope = - StatsScope::for_repertoire(repertoire.id.clone(), scope.side, scope.as_of); - let other_keys = active_learning_keys(library, &other_scope)?; - shared_keys.extend( - other_keys - .intersection(&selected_keys) - .cloned() - .collect::>(), - ); - other_keys - .intersection(&selected_keys) - .cloned() - .collect::>() - }; - if !impacted_keys.is_empty() { - affected_repertoires.push(ResetRepertoireImpact { - id: repertoire.id.clone(), - name: repertoire.name.clone(), - item_count: impacted_keys.len(), - }); - } - } - - Ok(ResetImpactProjection { - reset_count: selected_keys.len(), - shared_count: shared_keys.len(), - affected_repertoires, - }) -} - -// Preferred answers order the traversal, but never remove another PGN answer. -fn preferred_children( - repertoire: &Repertoire, - tree: &RepertoireTree, - node: chess_core::NodeId, -) -> Vec { - let mut children = tree.game().children(node).to_vec(); - if let Some(preferred) = tree - .position_key(node) - .and_then(|position| repertoire.main_answer_override(position)) - { - children.sort_by_key(|child| { - tree.game() - .game_move(*child) - .and_then(|mv| mv.uci()) - .as_deref() - != Some(preferred) - }); - } - children -} - -fn preferred_node_order(repertoire: &Repertoire, tree: &RepertoireTree) -> Vec { - let mut nodes = Vec::new(); - let mut stack = vec![tree.root()]; - while let Some(node) = stack.pop() { - nodes.push(node); - stack.extend(preferred_children(repertoire, tree, node).into_iter().rev()); - } - nodes -} - -fn repertoire_memberships( - repertoire: &Repertoire, - scope: &StatsScope, -) -> Result, LearningGraphError> { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let game = tree.game(); - let branch_root = scope.branch_root.as_deref(); - let path_allowed = |path: &[String]| { - branch_root.is_none_or(|root| path.starts_with(root)) - && (!scope.only_active || !repertoire.is_prefix_disabled(path)) - }; - - let attached_nodes = preferred_node_order(repertoire, &tree); - let pgn_orders: BTreeMap<_, _> = attached_nodes - .iter() - .enumerate() - .map(|(order, node)| (*node, order)) - .collect(); - let mut positions: BTreeMap = BTreeMap::new(); - let mut branch_root_found = branch_root.is_none(); - let mut start = None; - for (parent_order, node) in attached_nodes.into_iter().enumerate() { - let Some(path) = tree.path(node) else { - continue; - }; - if branch_root.is_some_and(|root| path == root) { - branch_root_found = true; - if path_allowed(path) { - start = tree.position_key(node).map(str::to_owned); - } - } - if !path_allowed(path) { - continue; - } - let Some(position_fen4) = tree.position_key(node).map(str::to_owned) else { - continue; - }; - let Some(position) = tree.position(node) else { - continue; - }; - let entry = positions - .entry(position_fen4.clone()) - .or_insert_with(|| PositionEntry { - side: LearningSide::from(position.turn()), - edges: Vec::new(), - }); - for (child_order, child) in preferred_children(repertoire, &tree, node) - .iter() - .enumerate() - { - if !tree.path(*child).is_some_and(path_allowed) { - continue; - } - let Some(game_move) = game.game_move(*child) else { - continue; - }; - let MoveKind::Normal(mv) = game_move.kind else { - continue; - }; - let Some(to) = tree.position_key(*child).map(str::to_owned) else { - continue; - }; - entry.edges.push(GraphEdge { - source_path: tree.path(*child).expect("checked PGN path").to_vec(), - uci: mv.to_uci(CastlingMode::Standard).to_string(), - to, - parent_order, - child_order, - pgn_order: pgn_orders.get(child).copied().unwrap_or(usize::MAX), - }); - } - } - - if !branch_root_found { - return Err(LearningGraphError::BranchRootNotFound { - repertoire_id: repertoire.id.clone(), - branch_root: branch_root.unwrap_or_default().to_vec(), - }); - } - if branch_root.is_none() { - start = tree.position_key(tree.root()).map(str::to_owned); - } - let Some(start) = start else { - return Ok(Vec::new()); - }; - - for entry in positions.values_mut() { - entry.edges.sort_by(|left, right| { - (left.source_path.len(), left.parent_order, left.child_order) - .cmp(&( - right.source_path.len(), - right.parent_order, - right.child_order, - )) - .then_with(|| left.uci.cmp(&right.uci)) - .then_with(|| left.to.cmp(&right.to)) - }); - let mut seen = BTreeSet::new(); - entry.edges.retain(|edge| seen.insert(edge.uci.clone())); - } - - let base_depth = u32::try_from(branch_root.unwrap_or_default().len()) - .map_err(|_| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; - let mut queue = VecDeque::from([( - start.clone(), - base_depth, - branch_root.unwrap_or_default().to_vec(), - 0_u32, - )]); - let mut visited = BTreeSet::from([start]); - let mut result: BTreeMap = BTreeMap::new(); - - while let Some((position_fen4, depth, path, variation_depth)) = queue.pop_front() { - if scope.max_depth.is_some_and(|maximum| depth >= maximum) { - continue; - } - let Some(entry) = positions.get(&position_fen4) else { - continue; - }; - let own_position = entry.side == scope.side; - let edges = &entry.edges; - - for edge in edges { - let next_depth = depth - .checked_add(1) - .ok_or_else(|| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; - let next_variation_depth = variation_depth - .checked_add(u32::from(edge.child_order > 0)) - .ok_or_else(|| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; - let mut next_path = path.clone(); - next_path.push(edge.uci.clone()); - if own_position { - let key = LearningItemKey::local(position_fen4.clone(), edge.uci.clone()); - result - .entry(key.clone()) - .or_insert_with(|| LearningItemMembership { - repertoire_id: repertoire.id.clone(), - key, - min_depth: next_depth, - path: edge.source_path.clone(), - pgn_order: edge.pgn_order, - variation_depth: next_variation_depth, - }); - } - if visited.insert(edge.to.clone()) { - queue.push_back((edge.to.clone(), next_depth, next_path, next_variation_depth)); - } - } - } - - Ok(result.into_values().collect()) -} - -pub(crate) fn all_path_learning_memberships( - library: &Library, - scope: &StatsScope, -) -> Result, LearningGraphError> { - let mut memberships = Vec::new(); - for id in &scope.repertoire_ids { - let repertoire = library - .repertoire(id) - .ok_or_else(|| LearningGraphError::RepertoireNotFound(id.clone()))?; - memberships.extend(all_path_repertoire_memberships(repertoire, scope)?); - } - memberships.sort_by(|left, right| { - (&left.repertoire_id, &left.path, &left.key).cmp(&( - &right.repertoire_id, - &right.path, - &right.key, - )) - }); - Ok(memberships) -} - -struct AllPathContext<'a> { - repertoire: &'a Repertoire, - scope: &'a StatsScope, - tree: &'a RepertoireTree, - pgn_orders: &'a BTreeMap, -} - -fn all_path_repertoire_memberships( - repertoire: &Repertoire, - scope: &StatsScope, -) -> Result, LearningGraphError> { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let game = tree.game(); - let branch_root = scope.branch_root.as_deref(); - let path_allowed = |path: &[String]| { - branch_root.is_none_or(|root| path.starts_with(root)) - && (!scope.only_active || !repertoire.is_prefix_disabled(path)) - }; - let start = if let Some(root) = branch_root { - let Some(node) = game - .attached_nodes() - .into_iter() - .find(|node| tree.path(*node).is_some_and(|path| path == root)) - else { - return Err(LearningGraphError::BranchRootNotFound { - repertoire_id: repertoire.id.clone(), - branch_root: root.to_vec(), - }); - }; - if !tree.path(node).is_some_and(path_allowed) { - return Ok(Vec::new()); - } - node - } else { - tree.root() - }; - let base_depth = u32::try_from(branch_root.unwrap_or_default().len()) - .map_err(|_| LearningGraphError::DepthOverflow(repertoire.id.clone()))?; - let attached_nodes = preferred_node_order(repertoire, &tree); - let pgn_orders: BTreeMap<_, _> = attached_nodes - .iter() - .enumerate() - .map(|(order, node)| (*node, order)) - .collect(); - let context = AllPathContext { - repertoire, - scope, - tree: &tree, - pgn_orders: &pgn_orders, - }; - let mut memberships = Vec::new(); - let mut path = branch_root.unwrap_or_default().to_vec(); - visit_all_path_memberships(&context, start, base_depth, 0, &mut path, &mut memberships)?; - Ok(memberships) -} - -fn visit_all_path_memberships( - context: &AllPathContext<'_>, - node: chess_core::NodeId, - depth: u32, - variation_depth: u32, - path: &mut Vec, - memberships: &mut Vec, -) -> Result<(), LearningGraphError> { - if context - .scope - .max_depth - .is_some_and(|maximum| depth >= maximum) - { - return Ok(()); - } - let Some(position_fen4) = context.tree.position_key(node) else { - return Ok(()); - }; - let Some(position) = context.tree.position(node) else { - return Ok(()); - }; - let own_position = LearningSide::from(position.turn()) == context.scope.side; - let game = context.tree.game(); - let mut seen_uci = BTreeSet::new(); - for (child_order, child) in preferred_children(context.repertoire, context.tree, node) - .iter() - .enumerate() - { - if !context.tree.path(*child).is_some_and(|child_path| { - context - .scope - .branch_root - .as_deref() - .is_none_or(|root| child_path.starts_with(root)) - && (!context.scope.only_active - || !context.repertoire.is_prefix_disabled(child_path)) - }) { - continue; - } - let Some(game_move) = game.game_move(*child) else { - continue; - }; - let MoveKind::Normal(mv) = game_move.kind else { - continue; - }; - let uci = mv.to_uci(CastlingMode::Standard).to_string(); - if !seen_uci.insert(uci.clone()) { - continue; - } - let next_depth = depth - .checked_add(1) - .ok_or_else(|| LearningGraphError::DepthOverflow(context.repertoire.id.clone()))?; - let next_variation_depth = variation_depth - .checked_add(u32::from(child_order > 0)) - .ok_or_else(|| LearningGraphError::DepthOverflow(context.repertoire.id.clone()))?; - path.push(uci.clone()); - if own_position { - memberships.push(LearningItemMembership { - repertoire_id: context.repertoire.id.clone(), - key: LearningItemKey::local(position_fen4, uci), - min_depth: next_depth, - path: path.clone(), - pgn_order: context.pgn_orders.get(child).copied().unwrap_or(usize::MAX), - variation_depth: next_variation_depth, - }); - } - let result = visit_all_path_memberships( - context, - *child, - next_depth, - next_variation_depth, - path, - memberships, - ); - path.pop(); - result?; - } - Ok(()) -} diff --git a/crates/trainer/src/repertoire/learning_modes.rs b/crates/trainer/src/repertoire/learning_modes.rs deleted file mode 100644 index a0c5d83..0000000 --- a/crates/trainer/src/repertoire/learning_modes.rs +++ /dev/null @@ -1,87 +0,0 @@ -use std::cmp::Ordering; -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use super::learning::{LearningData, LearningItemKey}; -use super::learning_graph::LearningItemMembership; - -#[derive( - Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, -)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum LearningPriority { - #[default] - DepthFirst, - BreadthOverDepth, - MainLinesFirst, - CommonPositionsFirst, -} - -pub(crate) fn sort_by_priority( - memberships: &mut [LearningItemMembership], - priority: LearningPriority, -) { - memberships.sort_by(|left, right| compare_priority(left, right, priority)); -} - -pub(crate) fn sort_least_recent( - memberships: &mut [LearningItemMembership], - learning: &LearningData, - priority: LearningPriority, -) { - let states: BTreeMap)> = memberships - .iter() - .map(|membership| { - let key = membership.key.clone(); - let item = learning.item(&key); - let introduced = item.is_some_and(|item| item.introduced); - let last_attempt = learning - .attempts - .iter() - .filter(|attempt| attempt.item_key() == key) - .map(|attempt| attempt.happened_at) - .max(); - let last_seen = item - .and_then(|item| item.last_review_at) - .max(last_attempt) - .or(last_attempt); - (key, (introduced, last_seen)) - }) - .collect(); - - memberships.sort_by(|left, right| { - let (left_introduced, left_last_seen) = - states.get(&left.key).copied().unwrap_or((false, None)); - let (right_introduced, right_last_seen) = - states.get(&right.key).copied().unwrap_or((false, None)); - left_introduced - .cmp(&right_introduced) - .then_with(|| left_last_seen.cmp(&right_last_seen)) - .then_with(|| compare_priority(left, right, priority)) - }); -} - -fn compare_priority( - left: &LearningItemMembership, - right: &LearningItemMembership, - priority: LearningPriority, -) -> Ordering { - left.repertoire_id - .cmp(&right.repertoire_id) - .then_with(|| match priority { - LearningPriority::DepthFirst => left.pgn_order.cmp(&right.pgn_order), - // No popularity or engine data is stored: common-position priority is - // explicitly the deterministic breadth-first fallback. - LearningPriority::BreadthOverDepth | LearningPriority::CommonPositionsFirst => left - .min_depth - .cmp(&right.min_depth) - .then_with(|| left.pgn_order.cmp(&right.pgn_order)), - LearningPriority::MainLinesFirst => left - .variation_depth - .cmp(&right.variation_depth) - .then_with(|| left.pgn_order.cmp(&right.pgn_order)), - }) - .then_with(|| left.path.cmp(&right.path)) - .then_with(|| left.key.cmp(&right.key)) -} diff --git a/crates/trainer/src/repertoire/learning_session.rs b/crates/trainer/src/repertoire/learning_session.rs deleted file mode 100644 index c93ac8a..0000000 --- a/crates/trainer/src/repertoire/learning_session.rs +++ /dev/null @@ -1,1533 +0,0 @@ -use std::{ - collections::{BTreeMap, BTreeSet}, - sync::{Arc, Mutex}, -}; - -use chess_core::shakmaty::fen::Fen; -use chess_core::shakmaty::uci::UciMove; -use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; -use serde::{Deserialize, Serialize}; - -use super::learning::{LearningData, LearningItemKey, TrainingAttempt, TrainingEventType}; -use super::learning_graph::{ - LearningGraphError, LearningItemMembership, StatsScope, active_learning_memberships, -}; -use super::learning_modes::{LearningPriority, sort_by_priority, sort_least_recent}; -use super::model::{LearningSide, Library, RepertoireId}; -use super::scope::TrainingScopeKey; -use super::srs::SrsSettings; -use super::stats::{QueueMode, TrainingMode}; -use super::store::LearningSession; -use super::tree::fen4; - -#[path = "learning_context.rs"] -mod learning_context; -pub use learning_context::LearningContextPolicy; -use learning_context::{ - LearningContextAction, LearningContextMove, LearningContextPlan, plan_context, speed_factor, -}; - -#[cfg(test)] -#[path = "context_tests.rs"] -mod context_tests; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum LearningSessionPhase { - AwaitingIndependent, - AwaitingContextIndependent, - AwaitingReplayAfterError, - PreviewedReplay, - AdvancingContext, - Finished, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct LearningSessionTarget { - pub key: LearningItemKey, - pub repertoire_id: RepertoireId, - pub min_depth: u32, - /// Includes the expected target move as its last element. - pub path: Vec, - #[serde(default)] - pub pgn_order: usize, - #[serde(default)] - pub variation_depth: u32, -} - -impl From for LearningSessionTarget { - fn from(membership: LearningItemMembership) -> Self { - Self { - key: membership.key, - repertoire_id: membership.repertoire_id, - min_depth: membership.min_depth, - path: membership.path, - pgn_order: membership.pgn_order, - variation_depth: membership.variation_depth, - } - } -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct LearningSessionSnapshot { - pub session: LearningSession, - #[serde(default)] - pub context_policy: LearningContextPolicy, - pub stats_scope: StatsScope, - pub queue: Vec, - pub current_index: usize, - pub phase: LearningSessionPhase, - /// Number of already presented or deliberately omitted moves in the current target path. - pub context_index: usize, - pub completed_keys: BTreeSet, - #[serde(default)] - pub cycle: u64, - /// 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>); - -impl PartialEq for SessionRuntime { - fn eq(&self, _other: &Self) -> bool { - true - } -} - -#[derive(Default, Debug)] -struct RuntimeData { - source: Option, - #[cfg(test)] - parses: usize, - #[cfg(test)] - replays: usize, - #[cfg(test)] - plans: usize, -} - -#[derive(Debug)] -struct ReplaySource { - repertoire_id: RepertoireId, - pgn: String, - start: Chess, - target: Option, -} - -#[derive(Debug)] -struct ReplayedTarget { - target: LearningSessionTarget, - side: LearningSide, - positions: Arc>, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct LearningPosition { - pub fen: String, - pub fen4: String, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct LearningContextStep { - pub uci: String, - pub from: LearningPosition, - pub to: LearningPosition, - pub speed_factor: f64, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct LearningPresentation { - pub phase: LearningSessionPhase, - pub target: Option, - pub target_path: Vec, - pub current_position: Option, - /// Automatic steps that still need presentation before the independent answer. - pub automatic_context: Vec, - pub revealed_move: Option, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum LearningSessionError { - EmptySessionId, - EmptyClientAttemptId, - UnsupportedMode(QueueMode), - SessionSideMismatch, - InvalidPhase { - operation: &'static str, - phase: LearningSessionPhase, - }, - IntroductionRequiresFinished, - InvalidSnapshot(&'static str), - RepertoireNotFound(RepertoireId), - InvalidTargetPath { - repertoire_id: RepertoireId, - path: Vec, - }, - TargetPositionMismatch, - TargetSideMismatch, - /// A known repertoire answer that is not the pending question. This is neutral - /// input: callers must not record an attempt, play an error sound or reset SRS. - RepertoireAlternative { - already_completed: bool, - }, - Graph(LearningGraphError), -} - -impl std::fmt::Display for LearningSessionError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::EmptySessionId => f.write_str("learning session id must not be empty"), - Self::EmptyClientAttemptId => f.write_str("client attempt id must not be empty"), - Self::UnsupportedMode(mode) => { - write!(f, "learning session operation does not support {mode:?}") - } - Self::SessionSideMismatch => { - f.write_str("learning session side does not match its statistics scope") - } - Self::InvalidPhase { operation, phase } => { - write!( - f, - "cannot {operation} while learning session is in {phase:?}" - ) - } - Self::IntroductionRequiresFinished => { - f.write_str("new learning items can be introduced only after the due queue") - } - Self::InvalidSnapshot(message) => { - write!(f, "invalid learning session snapshot: {message}") - } - Self::RepertoireNotFound(id) => write!(f, "repertoire not found: {id}"), - Self::InvalidTargetPath { - repertoire_id, - path, - } => write!( - f, - "learning target path is no longer legal in repertoire {repertoire_id}: {}", - path.join(" ") - ), - Self::TargetPositionMismatch => { - f.write_str("learning target path does not reach its saved position") - } - Self::TargetSideMismatch => { - f.write_str("learning target position belongs to the other side") - } - Self::RepertoireAlternative { already_completed } => { - if *already_completed { - f.write_str("this repertoire answer has already been reviewed in this pass") - } else { - f.write_str("this repertoire answer is not the current scheduled question") - } - } - Self::Graph(error) => error.fmt(f), - } - } -} - -impl std::error::Error for LearningSessionError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Graph(error) => Some(error), - _ => None, - } - } -} - -impl From for LearningSessionError { - fn from(error: LearningGraphError) -> Self { - Self::Graph(error) - } -} - -impl LearningSessionSnapshot { - pub fn new( - id: impl Into, - library: &Library, - learning: &LearningData, - stats_scope: StatsScope, - settings: SrsSettings, - ) -> Result { - Self::new_with_mode( - id, - library, - learning, - stats_scope, - settings, - QueueMode::SpacedRepetition, - ) - } - - pub fn new_with_mode( - id: impl Into, - library: &Library, - learning: &LearningData, - stats_scope: StatsScope, - settings: SrsSettings, - mode: QueueMode, - ) -> Result { - let id = id.into(); - if id.is_empty() { - return Err(LearningSessionError::EmptySessionId); - } - let queue = select_queue(library, learning, &stats_scope, mode)?; - let side = training_mode(stats_scope.side); - let session = LearningSession { - id, - mode, - side, - scope: TrainingScopeKey { - prefix: stats_scope.branch_root.clone().unwrap_or_default(), - end_prefix: None, - }, - settings, - }; - let mut snapshot = Self { - session, - context_policy: LearningContextPolicy::default(), - stats_scope, - queue, - current_index: 0, - phase: LearningSessionPhase::Finished, - context_index: 0, - 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( - &mut self, - library: &Library, - learning: &LearningData, - ) -> 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 = select_targets( - library, - learning, - &self.stats_scope, - |item| item.is_none_or(|item| !item.introduced), - self.stats_scope.learning_priority, - )?; - self.current_index = 0; - self.completed_keys.clear(); - self.reset_current_target_with_library(library)?; - Ok(self.queue.len()) - } - - pub fn start_next_pass( - &mut self, - library: &Library, - learning: &LearningData, - ) -> Result { - self.validate_configuration()?; - if self.phase != LearningSessionPhase::Finished { - return Err(LearningSessionError::InvalidPhase { - operation: "start the next pass", - phase: self.phase, - }); - } - self.queue = select_queue(library, learning, &self.stats_scope, self.session.mode)?; - self.current_index = 0; - self.completed_keys.clear(); - if !self.queue.is_empty() { - self.cycle = self.cycle.saturating_add(1); - } - self.reset_current_target_with_library(library)?; - Ok(self.queue.len()) - } - - pub fn reset_review_order(&mut self) -> Result<(), LearningSessionError> { - self.validate_configuration()?; - if self.session.mode != QueueMode::ReviewInOrder { - return Err(LearningSessionError::UnsupportedMode(self.session.mode)); - } - self.current_index = 0; - self.context_index = 0; - self.completed_keys.clear(); - self.cycle = 0; - self.reset_current_target(); - Ok(()) - } - - pub fn resume(self, library: &Library) -> Result { - self.validate(library)?; - Ok(self) - } - - pub fn id(&self) -> &str { - &self.session.id - } - - pub fn current_target(&self) -> Option<&LearningSessionTarget> { - self.queue.get(self.current_index) - } - - pub fn current_expected_uci(&self) -> Option<&str> { - let target = self.current_target()?; - if self.is_context_challenge(target) { - target.path.get(self.context_index).map(String::as_str) - } else { - Some(&target.key.expected_uci) - } - } - - pub fn remaining(&self) -> usize { - self.queue - .iter() - .skip(self.current_index) - .filter(|target| !self.completed_keys.contains(&target.key)) - .count() - } - - /// Choices still due in this fixed pass; statistics stay separate for each UCI. - pub fn pending_answers_for_position(&self, position_fen4: &str) -> Vec { - self.queue - .iter() - .skip(self.current_index) - .filter(|target| { - target.key.position_fen4 == position_fen4 - && !self.completed_keys.contains(&target.key) - }) - .map(|target| target.key.expected_uci.clone()) - .collect() - } - - /// Only active answers in this session's scope qualify, never arbitrary legal - /// moves or a disabled/out-of-scope PGN branch. - pub fn is_active_repertoire_answer( - &self, - library: &Library, - position_fen4: &str, - uci: &str, - ) -> Result { - Ok(active_learning_memberships(library, &self.stats_scope)? - .iter() - .any(|item| item.key.position_fen4 == position_fen4 && item.key.expected_uci == uci)) - } - - pub fn presentation( - &self, - library: &Library, - ) -> Result { - self.presentation_impl(library, None) - } - - pub fn presentation_with_learning( - &mut self, - library: &Library, - learning: &LearningData, - ) -> Result { - self.sync_context_phase(library, Some(learning))?; - self.presentation_impl(library, Some(learning)) - } - - fn presentation_impl( - &self, - library: &Library, - learning: Option<&LearningData>, - ) -> Result { - self.validate_configuration()?; - let Some(target) = self.current_target() else { - return Ok(LearningPresentation { - phase: self.phase, - target: None, - target_path: Vec::new(), - current_position: None, - automatic_context: Vec::new(), - revealed_move: None, - }); - }; - let positions = self.replay_target(library, target)?; - if self.context_index >= positions.len() { - return Err(LearningSessionError::InvalidSnapshot( - "context index is outside the target path", - )); - } - let prefix_len = target.path.len().saturating_sub(1); - let plan = learning.map(|learning| self.context_plan(target, &positions, learning)); - let automatic_context = (self.context_index..prefix_len) - .take_while(|index| { - if *index == self.context_index && self.is_context_challenge(target) { - false - } else { - !self.context_needs_check(target, &positions, *index, plan.as_ref()) - } - }) - .map(|index| { - let factor = learning.map_or(1.0, |learning| { - let own_move = - LearningSide::from(positions[index].turn()) == self.stats_scope.side; - let key = LearningItemKey::new( - target.key.user_id.clone(), - fen4(&positions[index]), - target.path[index].clone(), - ); - let item = own_move.then(|| learning.item(&key)).flatten(); - speed_factor(&self.context_policy, item) - }); - LearningContextStep { - uci: target.path[index].clone(), - from: learning_position(&positions[index]), - to: learning_position(&positions[index + 1]), - speed_factor: factor, - } - }) - .collect(); - let revealed_move = match self.phase { - LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay => { - self.current_expected_uci().map(str::to_owned) - } - _ => None, - }; - Ok(LearningPresentation { - phase: self.phase, - target: Some(target.key.clone()), - target_path: target.path.clone(), - current_position: Some(learning_position(&positions[self.context_index])), - automatic_context, - revealed_move, - }) - } - - pub fn advance_context( - &mut self, - library: &Library, - client_attempt_id: impl Into, - happened_at: i64, - ) -> Result { - self.advance_context_impl(library, client_attempt_id, happened_at, None) - } - - pub fn advance_context_with_learning( - &mut self, - library: &Library, - learning: &LearningData, - client_attempt_id: impl Into, - happened_at: i64, - ) -> Result { - self.sync_context_phase(library, Some(learning))?; - self.advance_context_impl(library, client_attempt_id, happened_at, Some(learning)) - } - - fn advance_context_impl( - &mut self, - library: &Library, - client_attempt_id: impl Into, - happened_at: i64, - learning: Option<&LearningData>, - ) -> Result { - let client_attempt_id = checked_attempt_id(client_attempt_id.into())?; - self.require_phase( - "advance automatic context", - LearningSessionPhase::AdvancingContext, - )?; - let target = - self.current_target() - .cloned() - .ok_or(LearningSessionError::InvalidSnapshot( - "context has no current target", - ))?; - let positions = self.replay_target(library, &target)?; - let prefix_len = target.path.len() - 1; - if self.context_index >= prefix_len { - return Err(LearningSessionError::InvalidSnapshot( - "automatic context is already complete", - )); - } - let index = self.context_index; - let plan = learning.map(|learning| self.context_plan(&target, &positions, learning)); - if self.context_needs_check(&target, &positions, index, plan.as_ref()) { - return Err(LearningSessionError::InvalidSnapshot( - "automatic context requires an independent answer", - )); - } - let uci = target.path[index].clone(); - let attempt = TrainingAttempt { - user_id: target.key.user_id, - position_fen4: fen4(&positions[index]), - client_attempt_id, - session_id: self.session.id.clone(), - event_type: TrainingEventType::AutoContext, - expected_uci: uci.clone(), - actual_uci: Some(uci), - response_time_ms: None, - happened_at, - }; - self.context_index += 1; - self.sync_context_phase(library, learning)?; - Ok(attempt) - } - - pub fn preview( - &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()?; - match self.phase { - LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay => return Ok(None), - LearningSessionPhase::AwaitingIndependent => {} - phase => { - return Err(LearningSessionError::InvalidPhase { - operation: "preview the expected move", - phase, - }); - } - } - let target = - self.current_target() - .cloned() - .ok_or(LearningSessionError::InvalidSnapshot( - "preview has no current target", - ))?; - self.phase = LearningSessionPhase::PreviewedReplay; - self.showing_new = new; - Ok(Some(self.attempt( - &target.key, - TrainingEventType::Previewed, - Some(target.key.expected_uci.clone()), - None, - client_attempt_id, - happened_at, - ))) - } - - pub fn play_uci( - &mut self, - library: &Library, - uci: &str, - client_attempt_id: impl Into, - happened_at: i64, - response_time_ms: Option, - ) -> Result { - self.play_uci_impl( - library, - uci, - client_attempt_id, - happened_at, - response_time_ms, - None, - None, - ) - } - - pub fn play_uci_with_learning( - &mut self, - library: &Library, - learning: &LearningData, - uci: &str, - client_attempt_id: impl Into, - happened_at: i64, - response_time_ms: Option, - ) -> Result { - self.sync_context_phase(library, Some(learning))?; - self.play_uci_impl( - library, - uci, - client_attempt_id, - happened_at, - response_time_ms, - Some(learning), - None, - ) - } - - /// The UI prepares this scope's answers with the immutable library in its - /// startup worker, so a wrong move never rebuilds all repertoire graphs. - #[allow(clippy::too_many_arguments)] - pub fn play_uci_with_learning_answers( - &mut self, - library: &Library, - learning: &LearningData, - answers: &BTreeSet, - uci: &str, - client_attempt_id: impl Into, - happened_at: i64, - response_time_ms: Option, - ) -> Result { - self.sync_context_phase(library, Some(learning))?; - self.play_uci_impl( - library, - uci, - client_attempt_id, - happened_at, - response_time_ms, - Some(learning), - Some(answers), - ) - } - - #[allow(clippy::too_many_arguments)] - fn play_uci_impl( - &mut self, - library: &Library, - uci: &str, - client_attempt_id: impl Into, - happened_at: i64, - response_time_ms: Option, - learning: Option<&LearningData>, - answers: Option<&BTreeSet>, - ) -> Result { - let client_attempt_id = checked_attempt_id(client_attempt_id.into())?; - self.validate_configuration()?; - if !matches!( - self.phase, - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent - | LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay - ) { - return Err(LearningSessionError::InvalidPhase { - operation: "play a move", - phase: self.phase, - }); - } - let target = - self.current_target() - .cloned() - .ok_or(LearningSessionError::InvalidSnapshot( - "move input has no current target", - ))?; - let positions = self.replay_target(library, &target)?; - let context = self.is_context_challenge(&target); - let challenge_index = if context { - self.context_index - } else { - target.path.len() - 1 - }; - let position = &positions[challenge_index]; - let challenge_key = if context { - LearningItemKey::new( - target.key.user_id.clone(), - fen4(position), - target.path[challenge_index].clone(), - ) - } else { - target.key.clone() - }; - let legal = uci - .parse::() - .ok() - .and_then(|parsed| parsed.to_move(position).ok()); - let Some(mv) = legal else { - return Ok(self.attempt( - &challenge_key, - TrainingEventType::IllegalMove, - Some(uci.to_owned()), - None, - client_attempt_id, - happened_at, - )); - }; - let actual_uci = mv.to_uci(CastlingMode::Standard).to_string(); - let correct = actual_uci == challenge_key.expected_uci; - if !correct { - let actual_key = LearningItemKey::new( - challenge_key.user_id.clone(), - challenge_key.position_fen4.clone(), - actual_uci.clone(), - ); - if matches!( - self.phase, - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent - ) && let Some(index) = self - .queue - .iter() - .enumerate() - .skip(self.current_index) - .find_map(|(index, candidate)| { - (candidate.key == actual_key && !self.completed_keys.contains(&actual_key)) - .then_some(index) - }) - { - // Consume exactly the answer played. The original target remains - // pending, even when this question was part of its context. Never - // advance the old path after taking a different branch. - let attempt = self.attempt( - &actual_key, - TrainingEventType::CorrectIndependent, - Some(actual_uci), - response_time_ms, - client_attempt_id, - happened_at, - ); - self.queue.swap(self.current_index, index); - self.complete_current(library)?; - return Ok(attempt); - } - let known = match answers { - Some(answers) => answers.contains(&actual_key), - None => self.is_active_repertoire_answer( - library, - &actual_key.position_fen4, - &actual_uci, - )?, - }; - if known { - return Err(LearningSessionError::RepertoireAlternative { - already_completed: self.completed_keys.contains(&actual_key), - }); - } - } - let event_type = match self.phase { - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent => { - if correct { - TrainingEventType::CorrectIndependent - } else { - TrainingEventType::IncorrectIndependent - } - } - LearningSessionPhase::AwaitingReplayAfterError => TrainingEventType::ReplayAfterError, - LearningSessionPhase::PreviewedReplay => TrainingEventType::AutoContext, - phase => { - return Err(LearningSessionError::InvalidPhase { - operation: "play a move", - phase, - }); - } - }; - let independent_time = if event_type.is_independent() { - response_time_ms - } else { - None - }; - let attempt = self.attempt( - &challenge_key, - event_type, - Some(actual_uci), - independent_time, - client_attempt_id, - happened_at, - ); - match self.phase { - LearningSessionPhase::AwaitingIndependent if correct => { - self.complete_current(library)?; - } - LearningSessionPhase::AwaitingContextIndependent if correct => { - self.complete_context(challenge_key, library, learning)?; - } - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent => { - self.phase = LearningSessionPhase::AwaitingReplayAfterError; - } - LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay - if correct => - { - 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)?; - } - } - _ => {} - } - Ok(attempt) - } - - pub fn validate(&self, library: &Library) -> Result<(), LearningSessionError> { - self.validate_configuration()?; - if self.current_index > self.queue.len() { - return Err(LearningSessionError::InvalidSnapshot( - "current index is outside the fixed queue", - )); - } - let mut keys = BTreeSet::new(); - if self.queue.iter().any(|target| !keys.insert(&target.key)) { - return Err(LearningSessionError::InvalidSnapshot( - "fixed queue contains a duplicate learning item", - )); - } - let Some(target) = self.current_target() else { - if self.phase != LearningSessionPhase::Finished { - return Err(LearningSessionError::InvalidSnapshot( - "a session without a current target must be finished", - )); - } - return Ok(()); - }; - if self.phase == LearningSessionPhase::Finished { - return Err(LearningSessionError::InvalidSnapshot( - "a session with a current target cannot be finished", - )); - } - if self.completed_keys.contains(&target.key) { - return Err(LearningSessionError::InvalidSnapshot( - "the current learning item is already completed in this pass", - )); - } - let positions = self.replay_target(library, target)?; - let prefix_len = target.path.len() - 1; - let own_context = self.context_index < prefix_len - && LearningSide::from(positions[self.context_index].turn()) == self.stats_scope.side; - let legacy_context_needs_check = self.context_index < prefix_len - && self.context_needs_check(target, &positions, self.context_index, None); - match self.phase { - LearningSessionPhase::AdvancingContext - if self.context_index < prefix_len && !legacy_context_needs_check => {} - LearningSessionPhase::AwaitingContextIndependent if own_context => {} - LearningSessionPhase::AwaitingIndependent if self.context_index == prefix_len => {} - LearningSessionPhase::AwaitingReplayAfterError - if self.context_index == prefix_len || own_context => {} - LearningSessionPhase::PreviewedReplay if self.context_index == prefix_len => {} - _ => { - return Err(LearningSessionError::InvalidSnapshot( - "phase and automatic context index disagree", - )); - } - } - if positions.len() != target.path.len() + 1 { - return Err(LearningSessionError::InvalidSnapshot( - "target path replay is incomplete", - )); - } - Ok(()) - } - - pub(crate) fn validate_configuration(&self) -> Result<(), LearningSessionError> { - if self.session.id.is_empty() { - return Err(LearningSessionError::EmptySessionId); - } - if !matches!( - self.session.mode, - QueueMode::SpacedRepetition | QueueMode::ReviewInOrder | QueueMode::LeastRecent - ) { - return Err(LearningSessionError::UnsupportedMode(self.session.mode)); - } - if self.session.side != training_mode(self.stats_scope.side) { - return Err(LearningSessionError::SessionSideMismatch); - } - Ok(()) - } - - fn require_phase( - &self, - operation: &'static str, - expected: LearningSessionPhase, - ) -> Result<(), LearningSessionError> { - self.validate_configuration()?; - if self.phase == expected { - Ok(()) - } else { - Err(LearningSessionError::InvalidPhase { - operation, - phase: self.phase, - }) - } - } - - fn attempt( - &self, - key: &LearningItemKey, - event_type: TrainingEventType, - actual_uci: Option, - response_time_ms: Option, - client_attempt_id: String, - happened_at: i64, - ) -> TrainingAttempt { - TrainingAttempt { - user_id: key.user_id.clone(), - position_fen4: key.position_fen4.clone(), - client_attempt_id, - session_id: self.session.id.clone(), - event_type, - expected_uci: key.expected_uci.clone(), - actual_uci, - response_time_ms, - happened_at, - } - } - - fn complete_current(&mut self, library: &Library) -> Result<(), LearningSessionError> { - if let Some(target) = self.current_target() { - self.completed_keys.insert(target.key.clone()); - } - self.current_index += 1; - while self - .current_target() - .is_some_and(|target| self.completed_keys.contains(&target.key)) - { - self.current_index += 1; - } - if self.session.mode == QueueMode::ReviewInOrder - && !self.single_pass - && self.current_index >= self.queue.len() - && !self.queue.is_empty() - { - self.current_index = 0; - self.completed_keys.clear(); - self.cycle = self.cycle.saturating_add(1); - } - 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, - library: &Library, - learning: Option<&LearningData>, - ) -> Result<(), LearningSessionError> { - self.completed_keys.insert(key); - self.context_index += 1; - self.phase = LearningSessionPhase::AdvancingContext; - self.sync_context_phase(library, learning) - } - - fn reset_current_target_with_library( - &mut self, - library: &Library, - ) -> Result<(), LearningSessionError> { - self.reset_current_target(); - self.sync_context_phase(library, None) - } - - fn sync_context_phase( - &mut self, - library: &Library, - learning: Option<&LearningData>, - ) -> Result<(), LearningSessionError> { - self.validate_configuration()?; - let Some(target) = self.current_target().cloned() else { - self.phase = LearningSessionPhase::Finished; - return Ok(()); - }; - let positions = self.replay_target(library, &target)?; - let prefix_len = target.path.len() - 1; - if self.context_index > prefix_len { - return Err(LearningSessionError::InvalidSnapshot( - "context index is outside the target path", - )); - } - if self.context_index == prefix_len { - if !matches!( - self.phase, - LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay - ) { - self.phase = LearningSessionPhase::AwaitingIndependent; - } - return Ok(()); - } - if self.is_context_challenge(&target) { - if LearningSide::from(positions[self.context_index].turn()) == self.stats_scope.side { - return Ok(()); - } - return Err(LearningSessionError::InvalidSnapshot( - "opponent context cannot require an independent answer", - )); - } - let plan = learning.map(|learning| self.context_plan(&target, &positions, learning)); - if let Some(plan) = &plan - && self.phase == LearningSessionPhase::AdvancingContext - && self.context_index < plan.skip_prefix - { - self.context_index = plan.skip_prefix; - if self.context_index == prefix_len { - self.phase = LearningSessionPhase::AwaitingIndependent; - return Ok(()); - } - } - self.phase = - if self.context_needs_check(&target, &positions, self.context_index, plan.as_ref()) { - LearningSessionPhase::AwaitingContextIndependent - } else { - LearningSessionPhase::AdvancingContext - }; - Ok(()) - } - - fn context_plan( - &self, - target: &LearningSessionTarget, - positions: &[Chess], - learning: &LearningData, - ) -> LearningContextPlan { - #[cfg(test)] - { - self.runtime - .0 - .lock() - .unwrap_or_else(|error| error.into_inner()) - .plans += 1; - } - let queue_keys = (self.session.mode == QueueMode::LeastRecent).then(|| { - self.queue - .iter() - .map(|target| &target.key) - .collect::>() - }); - let moves = (0..target.path.len().saturating_sub(1)) - .map(|index| { - let key = LearningItemKey::new( - target.key.user_id.clone(), - fen4(&positions[index]), - target.path[index].clone(), - ); - LearningContextMove { - own_move: LearningSide::from(positions[index].turn()) == self.stats_scope.side, - least_recent_target: queue_keys - .as_ref() - .is_some_and(|keys| keys.contains(&key)), - key, - } - }) - .collect::>(); - plan_context( - &moves, - learning, - &self.context_policy, - &self.completed_keys, - self.session.mode == QueueMode::LeastRecent, - self.stats_scope.as_of, - ) - } - - fn context_needs_check( - &self, - target: &LearningSessionTarget, - positions: &[Chess], - index: usize, - plan: Option<&LearningContextPlan>, - ) -> bool { - if index >= target.path.len().saturating_sub(1) - || LearningSide::from(positions[index].turn()) != self.stats_scope.side - { - return false; - } - if let Some(plan) = plan { - return plan.actions[index] == LearningContextAction::Independent; - } - if self.session.mode != QueueMode::LeastRecent { - return false; - } - let key = LearningItemKey::new( - target.key.user_id.clone(), - fen4(&positions[index]), - target.path[index].clone(), - ); - !self.completed_keys.contains(&key) && self.queue.iter().any(|target| target.key == key) - } - - fn is_context_challenge(&self, target: &LearningSessionTarget) -> bool { - self.context_index < target.path.len().saturating_sub(1) - && matches!( - self.phase, - LearningSessionPhase::AwaitingContextIndependent - | LearningSessionPhase::AwaitingReplayAfterError - | LearningSessionPhase::PreviewedReplay - ) - } - - 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, - Some(_) => LearningSessionPhase::AwaitingIndependent, - }; - } -} - -fn checked_attempt_id(id: String) -> Result { - if id.is_empty() { - Err(LearningSessionError::EmptyClientAttemptId) - } else { - Ok(id) - } -} - -fn training_mode(side: LearningSide) -> TrainingMode { - match side { - LearningSide::White => TrainingMode::White, - LearningSide::Black => TrainingMode::Black, - } -} - -fn select_queue( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - mode: QueueMode, -) -> Result, LearningSessionError> { - match mode { - QueueMode::SpacedRepetition => select_targets( - library, - learning, - scope, - |item| item.is_some_and(|item| item.is_due(scope.as_of)), - LearningPriority::BreadthOverDepth, - ), - QueueMode::ReviewInOrder => { - select_targets(library, learning, scope, |_| true, scope.learning_priority) - } - QueueMode::LeastRecent => { - let mut memberships = - select_memberships(library, learning, scope, |_| true, scope.learning_priority)?; - sort_least_recent(&mut memberships, learning, scope.learning_priority); - Ok(memberships - .into_iter() - .map(LearningSessionTarget::from) - .collect()) - } - QueueMode::Practice => Err(LearningSessionError::UnsupportedMode(mode)), - } -} - -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, - scope: &StatsScope, - include: impl Fn(Option<&super::learning::LearningItem>) -> bool, - priority: LearningPriority, -) -> Result, LearningSessionError> { - Ok( - select_memberships(library, learning, scope, include, priority)? - .into_iter() - .map(LearningSessionTarget::from) - .collect(), - ) -} - -fn select_memberships( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - include: impl Fn(Option<&super::learning::LearningItem>) -> bool, - priority: LearningPriority, -) -> Result, LearningSessionError> { - let memberships = active_learning_memberships(library, scope)?; - let mut by_key = BTreeMap::new(); - for membership in memberships { - by_key - .entry(membership.key.clone()) - .and_modify(|existing: &mut LearningItemMembership| { - if membership_order(&membership) < membership_order(existing) { - *existing = membership.clone(); - } - }) - .or_insert(membership); - } - let mut memberships: Vec<_> = by_key - .into_values() - .filter(|membership| include(learning.item(&membership.key))) - .collect(); - sort_by_priority(&mut memberships, priority); - Ok(memberships) -} - -fn membership_order( - membership: &LearningItemMembership, -) -> (&RepertoireId, u32, &[String], &LearningItemKey) { - ( - &membership.repertoire_id, - membership.min_depth, - &membership.path, - &membership.key, - ) -} - -impl LearningSessionSnapshot { - fn replay_target( - &self, - library: &Library, - target: &LearningSessionTarget, - ) -> Result>, LearningSessionError> { - let side = self.stats_scope.side; - if target.path.is_empty() || target.path.last() != Some(&target.key.expected_uci) { - return Err(LearningSessionError::InvalidTargetPath { - repertoire_id: target.repertoire_id.clone(), - path: target.path.clone(), - }); - } - let repertoire = library.repertoire(&target.repertoire_id).ok_or_else(|| { - LearningSessionError::RepertoireNotFound(target.repertoire_id.clone()) - })?; - let mut runtime = self - .runtime - .0 - .lock() - .unwrap_or_else(|error| error.into_inner()); - if runtime.source.as_ref().is_none_or(|source| { - source.repertoire_id != target.repertoire_id || source.pgn != repertoire.pgn - }) { - runtime.source = Some(ReplaySource { - repertoire_id: target.repertoire_id.clone(), - pgn: repertoire.pgn.clone(), - start: repertoire.game().start().position().clone(), - target: None, - }); - #[cfg(test)] - { - runtime.parses += 1; - } - } - // The source was installed above. Avoid an assumption on user data at this boundary. - let Some(source) = runtime.source.as_ref() else { - return Err(LearningSessionError::InvalidSnapshot( - "replay source unavailable", - )); - }; - if let Some(cached) = &source.target - && cached.target == *target - && cached.side == side - { - return Ok(Arc::clone(&cached.positions)); - } - let mut position = source.start.clone(); - let mut positions = vec![position.clone()]; - for uci in &target.path { - let mv = uci - .parse::() - .ok() - .and_then(|parsed| parsed.to_move(&position).ok()) - .ok_or_else(|| LearningSessionError::InvalidTargetPath { - repertoire_id: target.repertoire_id.clone(), - path: target.path.clone(), - })?; - position.play_unchecked(mv); - positions.push(position.clone()); - } - let parent = &positions[target.path.len() - 1]; - if fen4(parent) != target.key.position_fen4 { - return Err(LearningSessionError::TargetPositionMismatch); - } - if LearningSide::from(parent.turn()) != side { - return Err(LearningSessionError::TargetSideMismatch); - } - let positions = Arc::new(positions); - if let Some(source) = runtime.source.as_mut() { - source.target = Some(ReplayedTarget { - target: target.clone(), - side, - positions: Arc::clone(&positions), - }); - } - #[cfg(test)] - { - runtime.replays += 1; - } - Ok(positions) - } - - #[cfg(test)] - pub(super) fn runtime_work_counts(&self) -> (usize, usize, usize) { - let runtime = self - .runtime - .0 - .lock() - .unwrap_or_else(|error| error.into_inner()); - (runtime.parses, runtime.replays, runtime.plans) - } -} - -fn learning_position(position: &Chess) -> LearningPosition { - LearningPosition { - fen: Fen::from_position(position, EnPassantMode::Legal).to_string(), - fen4: fen4(position), - } -} diff --git a/crates/trainer/src/repertoire/line_analytics.rs b/crates/trainer/src/repertoire/line_analytics.rs deleted file mode 100644 index f45d629..0000000 --- a/crates/trainer/src/repertoire/line_analytics.rs +++ /dev/null @@ -1,107 +0,0 @@ -use std::collections::BTreeMap; - -use serde::{Deserialize, Serialize}; - -use super::aggregate::{LearningAggregate, aggregate}; -use super::learning::{LearningData, LearningItem, LearningItemKey}; -use super::learning_graph::{ - LearningGraphError, StatsScope, aggregate_scope, all_path_learning_memberships, -}; -use super::model::{Library, RepertoireId}; -use super::scope::TrainingScope; -use super::srs::SrsSettings; -use super::tree::RepertoireTree; - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct LineLearningAnalytics { - pub repertoire_id: RepertoireId, - pub line: Vec, - pub summary: LearningAggregate, - pub line_learnt: bool, - pub line_fresh: bool, -} - -pub fn line_learning_analytics( - library: &Library, - learning: &LearningData, - scope: &StatsScope, - settings: &SrsSettings, -) -> Result, LearningGraphError> { - let memberships = all_path_learning_memberships(library, scope)?; - let scoped = aggregate_scope(library, learning, scope, settings)?; - let items_by_key: BTreeMap<&LearningItemKey, &LearningItem> = - scoped.items.iter().map(|item| (&item.key, item)).collect(); - let mut terminal_lines: BTreeMap>> = BTreeMap::new(); - for id in &scope.repertoire_ids { - let repertoire = library - .repertoire(id) - .ok_or_else(|| LearningGraphError::RepertoireNotFound(id.clone()))?; - let disabled_prefixes = if scope.only_active { - repertoire.disabled_prefixes.clone() - } else { - Vec::new() - }; - let tree = RepertoireTree::from_game( - repertoire.game(), - scope.max_depth.unwrap_or(u32::MAX), - disabled_prefixes, - ); - let lines = terminal_lines.entry(id.clone()).or_default(); - tree.visit_source_paths(&TrainingScope::whole(), |line| { - if scope - .branch_root - .as_deref() - .is_none_or(|root| line.starts_with(root)) - { - lines.push(line.to_vec()); - } - std::ops::ControlFlow::Continue(()) - }) - .map_err(|message| LearningGraphError::TrainingPathGeneration { - repertoire_id: id.clone(), - message, - })?; - lines.sort(); - lines.dedup(); - } - - let mut lines: BTreeMap< - (RepertoireId, Vec), - BTreeMap<&LearningItemKey, &LearningItem>, - > = BTreeMap::new(); - for membership in memberships { - let Some((key, item)) = items_by_key.get_key_value(&membership.key) else { - continue; - }; - let Some(candidates) = terminal_lines.get(&membership.repertoire_id) else { - continue; - }; - let first = candidates.partition_point(|line| line.as_slice() < membership.path.as_slice()); - for line in &candidates[first..] { - if !line.starts_with(&membership.path) { - break; - } - lines - .entry((membership.repertoire_id.clone(), line.clone())) - .or_default() - .insert(*key, *item); - } - } - - Ok(lines - .into_iter() - .map(|((repertoire_id, line), items)| { - let summary = aggregate(items.values().copied(), scope.as_of, settings); - let line_learnt = - summary.total > 0 && items.values().all(|item| item.correct_streak >= 3); - let line_fresh = line_learnt && summary.uncertain == 0 && summary.due == 0; - LineLearningAnalytics { - repertoire_id, - line, - summary, - line_learnt, - line_fresh, - } - }) - .collect()) -} diff --git a/crates/trainer/src/repertoire/line_tests.rs b/crates/trainer/src/repertoire/line_tests.rs deleted file mode 100644 index b7f6961..0000000 --- a/crates/trainer/src/repertoire/line_tests.rs +++ /dev/null @@ -1,299 +0,0 @@ -use super::*; - -const NOW: i64 = 1_800_000_000; -const DAY: i64 = 24 * 60 * 60; - -fn add_repertoire(library: &mut Library, name: &str, pgn: &str) -> RepertoireId { - library - .create(name, &chess_core::parse_str(pgn).game) - .unwrap() -} - -fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { - let mut library = Library::default(); - let id = add_repertoire(&mut library, "One", pgn); - (library, id) -} - -fn scope(id: RepertoireId) -> StatsScope { - StatsScope::for_repertoire(id, LearningSide::White, NOW) -} - -fn strings(moves: &[&str]) -> Vec { - moves.iter().map(|mv| (*mv).to_owned()).collect() -} - -fn key_at_path(repertoire: &Repertoire, path: &[String], expected_uci: &str) -> LearningItemKey { - let tree = RepertoireTree::from_game(repertoire.game(), u32::MAX, Vec::new()); - let parent = tree.node_at_path(path).unwrap(); - LearningItemKey::local(tree.position_key(parent).unwrap(), expected_uci) -} - -fn line<'a>( - rows: &'a [LineLearningAnalytics], - repertoire_id: &RepertoireId, - path: &[&str], -) -> Option<&'a LineLearningAnalytics> { - rows.iter().find(|row| { - &row.repertoire_id == repertoire_id - && row.line.iter().map(String::as_str).eq(path.iter().copied()) - }) -} - -fn learnt(item: &mut LearningItem, next_review_at: i64) { - item.introduced = true; - item.correct_streak = 3; - item.correct_count = 3; - item.last_review_at = Some(NOW - DAY); - item.last_correct_at = Some(NOW - DAY); - item.last_independent_at = Some(NOW - DAY); - item.next_review_at = Some(next_review_at); - item.previous_interval_seconds = Some(DAY); -} - -fn transposition_pgn() -> &'static str { - "1. e4 d5 (1... Nf6 2. d4 d5 3. c4) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 e6 6. g3 *" -} - -fn branching_pgn() -> &'static str { - "1. e4 e5 (1... c5 2. Nf3) 2. Nf3 Nc6 3. Bb5 *" -} - -#[test] -fn at_30_overlapping_lines_share_items_but_global_scope_deduplicates() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "First", transposition_pgn()); - let second = add_repertoire(&mut library, "Second", transposition_pgn()); - let shared = key_at_path( - library.repertoire(&first).unwrap(), - &strings(&["e2e4", "g8f6", "d2d4", "d7d5"]), - "c2c4", - ); - let mut learning = LearningData::default(); - learnt(learning.ensure_item(shared), NOW + DAY); - let rows = line_learning_analytics( - &library, - &learning, - &scope(first.clone()), - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(rows.len(), 2); - let main_line = line( - &rows, - &first, - &[ - "e2e4", "d7d5", "d2d4", "g8h6", "g1f3", "h6g8", "f3g1", "g8f6", "c2c4", "e7e6", "g2g3", - ], - ) - .unwrap(); - let transposing_line = line(&rows, &first, &["e2e4", "g8f6", "d2d4", "d7d5", "c2c4"]).unwrap(); - assert_eq!(main_line.summary.total, 6); - assert_eq!(transposing_line.summary.total, 3); - for row in [main_line, transposing_line] { - assert_eq!(row.summary.learnt, 1); - assert_eq!(row.summary.accuracy_correct, 3); - assert_eq!(row.summary.accuracy_attempts, 3); - assert!(!row.line_learnt); - assert!(!row.line_fresh); - } - - let global_scope = StatsScope::new([first, second], LearningSide::White, NOW); - let global = - aggregate_scope(&library, &learning, &global_scope, &SrsSettings::default()).unwrap(); - assert_eq!(global.summary.total, 7); - assert_eq!(global.summary.learnt, 1); - assert_eq!(global.summary.accuracy_correct, 3); - assert!(global.summary.total < main_line.summary.total + transposing_line.summary.total); - let mean = (main_line.summary.learnt_percent.unwrap() - + transposing_line.summary.learnt_percent.unwrap()) - / 2.0; - assert!((global.summary.learnt_percent.unwrap() - mean).abs() > f64::EPSILON); -} - -#[test] -fn line_learnt_and_fresh_follow_success_due_uncertain_and_wrong() { - let (library, id) = single_repertoire("1. e4 e5 2. Nf3 *"); - let selected = scope(id.clone()); - let keys = active_learning_keys(&library, &selected).unwrap(); - let mut learning = LearningData::default(); - let initial = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(initial.len(), 1); - assert_eq!(initial[0].summary.total, 2); - assert_eq!(initial[0].summary.unseen, 2); - assert!(!initial[0].line_learnt); - assert!(!initial[0].line_fresh); - - for key in &keys { - let item = learning.ensure_item(key.clone()); - for happened_at in [NOW - 3, NOW - 2, NOW - 1] { - apply_independent_correct(item, happened_at, &SrsSettings::default()); - } - item.next_review_at = Some(NOW + DAY); - item.previous_interval_seconds = Some(DAY); - } - let fresh = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(fresh[0].summary.learnt, 2); - assert_eq!(fresh[0].summary.due, 0); - assert_eq!(fresh[0].summary.uncertain, 0); - assert!(fresh[0].line_learnt); - assert!(fresh[0].line_fresh); - - let first = keys.iter().next().unwrap(); - learning.ensure_item((*first).clone()).next_review_at = Some(NOW); - let due = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(due[0].summary.due, 1); - assert_eq!(due[0].summary.uncertain, 0); - assert!(due[0].line_learnt); - assert!(!due[0].line_fresh); - - learning.ensure_item((*first).clone()).next_review_at = Some(NOW - 8 * DAY); - let uncertain = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(uncertain[0].summary.due, 1); - assert_eq!(uncertain[0].summary.uncertain, 1); - assert!(uncertain[0].line_learnt); - assert!(!uncertain[0].line_fresh); - - apply_independent_wrong( - learning.ensure_item((*first).clone()), - "d2d4", - NOW, - &SrsSettings::default(), - ); - let wrong = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(wrong[0].summary.learning, 1); - assert_eq!(wrong[0].summary.accuracy_wrong, 1); - assert!(!wrong[0].line_learnt); - assert!(!wrong[0].line_fresh); - - for happened_at in [NOW + 1, NOW + 2, NOW + 3] { - apply_independent_correct( - learning.ensure_item((*first).clone()), - happened_at, - &SrsSettings::default(), - ); - } - let mut restored_scope = selected; - restored_scope.as_of = NOW + 3; - let restored = line_learning_analytics( - &library, - &learning, - &restored_scope, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(restored[0].summary.learnt, 2); - assert_eq!(restored[0].summary.due, 0); - assert_eq!(restored[0].summary.uncertain, 0); - assert!(restored[0].line_learnt); - assert!(restored[0].line_fresh); -} - -#[test] -fn empty_lines_are_omitted_and_never_reported_learnt() { - let (library, id) = single_repertoire("1. e4 *"); - let empty_scope = StatsScope::new([], LearningSide::White, NOW); - assert!( - line_learning_analytics( - &library, - &LearningData::default(), - &empty_scope, - &SrsSettings::default(), - ) - .unwrap() - .is_empty() - ); - - let no_black_items = StatsScope::for_repertoire(id, LearningSide::Black, NOW); - let rows = line_learning_analytics( - &library, - &LearningData::default(), - &no_black_items, - &SrsSettings::default(), - ) - .unwrap(); - assert!(rows.is_empty()); - assert!(rows.iter().all(|row| !row.line_learnt && !row.line_fresh)); -} - -#[test] -fn line_scope_honours_max_depth_disable_and_branch_root() { - let (mut library, id) = single_repertoire(branching_pgn()); - let learning = LearningData::default(); - let depth_scope = scope(id.clone()).with_max_depth(Some(2)); - let depth = line_learning_analytics(&library, &learning, &depth_scope, &SrsSettings::default()) - .unwrap(); - assert_eq!(depth.len(), 2); - assert!( - depth - .iter() - .all(|row| row.line.len() == 2 && row.summary.total == 1) - ); - - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&strings(&["e2e4", "c7c5"]), true) - .unwrap(); - let selected = scope(id.clone()); - let disabled = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(disabled.len(), 1); - assert!(!disabled[0].line.starts_with(&strings(&["e2e4", "c7c5"]))); - - let mut include_inactive = selected.clone(); - include_inactive.only_active = false; - let inactive = line_learning_analytics( - &library, - &learning, - &include_inactive, - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(inactive.len(), 2); - - let root = strings(&["e2e4", "e7e5"]); - let rooted = line_learning_analytics( - &library, - &learning, - &selected.with_branch_root(root.clone()), - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(rooted.len(), 1); - assert!(rooted[0].line.starts_with(&root)); - assert_eq!( - rooted[0].line, - strings(&["e2e4", "e7e5", "g1f3", "b8c6", "f1b5"]) - ); - assert_eq!(rooted[0].summary.total, 2); -} - -#[test] -fn line_projection_is_deterministic_and_sorted() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "First", branching_pgn()); - let second = add_repertoire(&mut library, "Second", branching_pgn()); - let selected = StatsScope::new([first, second], LearningSide::White, NOW); - let mut learning = LearningData::default(); - for key in active_learning_keys(&library, &selected).unwrap() { - learning.ensure_item(key); - } - let before = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - let mut sorted = before.clone(); - sorted.sort_by(|left, right| { - (&left.repertoire_id, &left.line).cmp(&(&right.repertoire_id, &right.line)) - }); - assert_eq!(before, sorted); - - learning.items.reverse(); - let after = - line_learning_analytics(&library, &learning, &selected, &SrsSettings::default()).unwrap(); - assert_eq!(before, after); -} diff --git a/crates/trainer/src/repertoire/migration.rs b/crates/trainer/src/repertoire/migration.rs deleted file mode 100644 index 2348973..0000000 --- a/crates/trainer/src/repertoire/migration.rs +++ /dev/null @@ -1,104 +0,0 @@ -#![allow(dead_code)] - -use std::cmp::Ordering; -use std::collections::BTreeMap; - -use crate::repertoire::learning::{LearningData, LearningItem, LearningItemKey}; -use crate::repertoire::stats::{MoveStats, StatsData, TrainingMode}; - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct MigrationReport { - /// Legacy records coalesced into an existing shared learning item. - pub merged: usize, - /// Shared keys whose source records disagreed about streak or schedule. - pub conflicts: usize, - pub skipped_both: usize, -} - -pub(super) fn migrate_v2(stats: &StatsData) -> (LearningData, MigrationReport) { - let mut report = MigrationReport::default(); - let mut groups: BTreeMap> = BTreeMap::new(); - for entry in &stats.move_stats { - if entry.key.mode == TrainingMode::Both && entry.key.expected_uci.is_empty() { - report.skipped_both = report.skipped_both.saturating_add(1); - continue; - } - groups - .entry(LearningItemKey::local( - entry.key.position_fen4.clone(), - entry.key.expected_uci.clone(), - )) - .or_default() - .push(entry); - } - - let items = groups - .into_iter() - .filter_map(|(key, entries)| { - let mut iter = entries.iter().copied(); - let mut latest = iter.next()?; - for entry in iter { - if compare_recency(entry, latest) == Ordering::Greater { - latest = entry; - } - } - - report.merged = report - .merged - .saturating_add(entries.len().saturating_sub(1)); - if entries.iter().any(|entry| { - entry.streak != latest.streak - || entry.due != latest.due - || entry.interval_seconds != latest.interval_seconds - }) { - report.conflicts = report.conflicts.saturating_add(1); - } - - let mut item = LearningItem::new(key); - item.introduced = entries - .iter() - .any(|entry| entry.attempts > 0 || entry.due.is_some()); - if latest.streak < 0 { - item.wrong_streak = latest.streak.unsigned_abs(); - } else { - item.correct_streak = latest.streak as u32; - } - item.last_review_at = latest.last_seen; - item.next_review_at = entries.iter().filter_map(|entry| entry.due).min(); - item.previous_interval_seconds = - latest - .interval_seconds - .or_else(|| match (latest.due, latest.last_seen) { - (Some(due), Some(last_seen)) if due > last_seen => { - Some(due.saturating_sub(last_seen)) - } - _ => None, - }); - Some(item) - }) - .collect(); - - ( - LearningData { - items, - attempts: Vec::new(), - extensions: BTreeMap::new(), - }, - report, - ) -} - -fn compare_recency(left: &MoveStats, right: &MoveStats) -> Ordering { - left.last_seen - .cmp(&right.last_seen) - .then_with(|| left.key.repertoire_id.cmp(&right.key.repertoire_id)) - .then_with(|| mode_rank(left.key.mode).cmp(&mode_rank(right.key.mode))) -} - -fn mode_rank(mode: TrainingMode) -> u8 { - match mode { - TrainingMode::White => 0, - TrainingMode::Black => 1, - TrainingMode::Both => 2, - } -} diff --git a/crates/trainer/src/repertoire/mod.rs b/crates/trainer/src/repertoire/mod.rs deleted file mode 100644 index 183f091..0000000 --- a/crates/trainer/src/repertoire/mod.rs +++ /dev/null @@ -1,89 +0,0 @@ -//! Versioned opening repertoires, tree training and their persistent stores. -//! -//! This module is independent from the legacy line trainer in the crate root. - -mod aggregate; -mod branch_analytics; -mod learning; -mod learning_analytics; -mod learning_graph; -mod learning_modes; -mod learning_session; -mod line_analytics; -mod model; -mod scope; -mod srs; -mod stats; -mod store; -mod tree; - -pub use aggregate::{ - LearningAggregate, RepertoireStatus, aggregate, global_total_invariant_violation, is_uncertain, - log_global_total_invariant, -}; -pub use branch_analytics::{BranchLearningAnalytics, branch_learning_analytics}; -pub use learning::{ - AttemptApplication, IndependentOutcome, IndependentResult, LOCAL_PROFILE_ID, LearningData, - LearningError, LearningItem, LearningItemKey, RECENT_INDEPENDENT_OUTCOMES_LIMIT, - TrainingAttempt, TrainingEventType, WrongMoveStats, is_resistant, -}; -pub use learning_analytics::{ - AttemptsHistogram, CorrectStreakHistogram, LearningSnapshot, LocalDatePolicy, - MoveLearningAnalytics, MoveLearningStatus, SCHEDULED_MONTH_SECONDS, SCHEDULED_WEEK_SECONDS, - SCHEDULED_YEAR_SECONDS, ScheduledBuckets, SequenceHistograms, WrongStreakHistogram, - attempts_histogram, correct_streak_histogram, move_learning_analytics, scheduled_buckets, - scoped_move_learning_analytics, sequence_histograms, wrong_streak_histogram, -}; -pub use learning_graph::{ - LearningGraphError, LearningItemMembership, ResetImpactProjection, ResetRepertoireImpact, - ScopedLearningAggregate, StatsScope, active_learning_keys, active_learning_memberships, - aggregate_scope, reset_impact, -}; -pub use learning_modes::LearningPriority; -pub use learning_session::{ - LearningContextPolicy, LearningContextStep, LearningPosition, LearningPresentation, - LearningSessionError, LearningSessionPhase, LearningSessionSnapshot, LearningSessionTarget, -}; -pub use line_analytics::{LineLearningAnalytics, line_learning_analytics}; -pub use model::{ - DEFAULT_MAX_PLIES, LIBRARY_VERSION, LearningSide, LegacyMigrationReport, Library, MergeReport, - Repertoire, RepertoireError, RepertoireId, -}; -pub use scope::{TrainingScope, TrainingScopeKey}; -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, - UNCERTAIN_INTERVAL_DIVISOR, UNCERTAIN_MIN_GRACE_SECONDS, apply_attempt, - apply_independent_correct, apply_independent_wrong, apply_preview, -}; -pub use stats::{ - 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, fen4}; - -#[cfg(test)] -mod acceptance_tests; -#[cfg(test)] -mod advanced_tests; -#[cfg(test)] -mod analytics_tests; -#[cfg(test)] -mod branch_tests; -#[cfg(test)] -mod daily_tests; -#[cfg(test)] -mod graph_tests; -#[cfg(test)] -mod line_tests; -#[cfg(test)] -mod mode_tests; -#[cfg(test)] -mod session_tests; -#[cfg(test)] -mod tests; diff --git a/crates/trainer/src/repertoire/mode_tests.rs b/crates/trainer/src/repertoire/mode_tests.rs deleted file mode 100644 index b51b7b1..0000000 --- a/crates/trainer/src/repertoire/mode_tests.rs +++ /dev/null @@ -1,695 +0,0 @@ -use std::collections::BTreeSet; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; - -use super::*; - -const NOW: i64 = 1_800_000_000; -const DAY: i64 = 24 * 60 * 60; -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-modes-{}-{}-{name}", - std::process::id(), - sequence - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn path(&self) -> PathBuf { - self.0.join("learning.json") - } - - fn store(&self) -> LearningStore { - LearningStore::new(self.path()) - } -} - -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 { - library - .create(name, &chess_core::parse_str(pgn).game) - .unwrap() -} - -fn single_repertoire(pgn: &str) -> (Library, RepertoireId) { - let mut library = Library::default(); - let id = add_repertoire(&mut library, "Test", pgn); - (library, id) -} - -fn scope(id: RepertoireId, side: LearningSide) -> StatsScope { - StatsScope::for_repertoire(id, side, NOW) -} - -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 mode_session( - id: &str, - library: &Library, - learning: &LearningData, - scope: StatsScope, - mode: QueueMode, -) -> LearningSessionSnapshot { - LearningSessionSnapshot::new_with_mode( - id, - library, - learning, - scope, - SrsSettings::default(), - mode, - ) - .unwrap() -} - -fn queue_labels(session: &LearningSessionSnapshot) -> Vec { - session - .queue - .iter() - .map(|target| format!("{}@{}", target.key.expected_uci, target.min_depth)) - .collect() -} - -fn apply(learning: &mut LearningData, attempt: TrainingAttempt) { - assert_eq!( - learning.apply_attempt(attempt, &SrsSettings::default()), - Ok(AttemptApplication::Applied) - ); -} - -fn complete_target( - session: &mut LearningSessionSnapshot, - learning: &mut LearningData, - library: &Library, - id_prefix: &str, - happened_at: i64, -) { - let original_index = session.current_index; - let original_cycle = session.cycle; - let original_key = session.current_target().unwrap().key.clone(); - for step in 0..32 { - match session.phase { - LearningSessionPhase::AdvancingContext => { - let attempt = session - .advance_context( - library, - format!("{id_prefix}-{original_cycle}-{original_index}-context-{step}"), - happened_at, - ) - .unwrap(); - apply(learning, attempt); - } - LearningSessionPhase::AwaitingIndependent - | LearningSessionPhase::AwaitingContextIndependent => { - let expected = session.current_expected_uci().unwrap().to_owned(); - let attempt = session - .play_uci( - library, - &expected, - format!("{id_prefix}-{original_cycle}-{original_index}-answer-{step}"), - happened_at, - Some(100 + step), - ) - .unwrap(); - apply(learning, attempt); - } - phase => panic!("unexpected phase while completing target: {phase:?}"), - } - if session.phase == LearningSessionPhase::Finished - || session.current_index != original_index - || session.cycle != original_cycle - || session - .current_target() - .is_none_or(|target| target.key != original_key) - { - return; - } - } - panic!("target did not complete"); -} - -fn commit( - store: &LearningStore, - session: &mut LearningSessionSnapshot, - attempt: TrainingAttempt, -) -> PersistedSessionAttempt { - let persisted = store.apply_attempt_and_session(attempt, session).unwrap(); - *session = persisted.session.clone(); - persisted -} - -fn introduced_at(learning: &mut LearningData, key: LearningItemKey, last_review_at: i64) { - let item = learning.ensure_item(key); - item.introduced = true; - item.correct_streak = 1; - item.correct_count = 1; - item.last_review_at = Some(last_review_at); - item.last_correct_at = Some(last_review_at); - item.next_review_at = Some(NOW + 10 * DAY); - item.previous_interval_seconds = Some(DAY); -} - -fn journal_attempt(key: &LearningItemKey, id: &str, happened_at: i64) -> TrainingAttempt { - TrainingAttempt { - user_id: key.user_id.clone(), - position_fen4: key.position_fen4.clone(), - client_attempt_id: id.into(), - session_id: "at22".into(), - event_type: TrainingEventType::CorrectIndependent, - expected_uci: key.expected_uci.clone(), - actual_uci: Some(key.expected_uci.clone()), - response_time_ms: Some(200), - happened_at, - } -} - -#[test] -fn learning_priorities_use_pgn_order_depth_rav_and_deterministic_bfs_fallback() { - let (library, id) = single_repertoire( - "1. e4 e5 (1... c5 2. c4 Nc6 (2... e6 3. g3)) (1... Nf6 2. d4) 2. Nf3 Nc6 *", - ); - let selected = scope(id, LearningSide::White); - let learning = LearningData::default(); - let order = |priority| { - queue_labels(&mode_session( - "priority", - &library, - &learning, - selected.clone().with_learning_priority(priority), - QueueMode::ReviewInOrder, - )) - }; - - assert_eq!( - order(LearningPriority::DepthFirst), - ["e2e4@1", "g1f3@3", "c2c4@3", "g2g3@5", "d2d4@3"] - ); - assert_eq!( - order(LearningPriority::BreadthOverDepth), - ["e2e4@1", "g1f3@3", "c2c4@3", "d2d4@3", "g2g3@5"] - ); - assert_eq!( - order(LearningPriority::MainLinesFirst), - ["e2e4@1", "g1f3@3", "c2c4@3", "d2d4@3", "g2g3@5"] - ); - assert_eq!( - order(LearningPriority::CommonPositionsFirst), - order(LearningPriority::BreadthOverDepth) - ); - - let memberships = active_learning_memberships(&library, &selected).unwrap(); - let nested = memberships - .iter() - .find(|membership| membership.key.expected_uci == "g2g3") - .unwrap(); - assert_eq!(nested.min_depth, 5); - assert_eq!(nested.variation_depth, 2); - assert!( - memberships - .iter() - .all(|membership| { membership.pgn_order > 0 }) - ); - assert!(matches!( - LearningSessionSnapshot::new_with_mode( - "practice", - &library, - &learning, - selected, - SrsSettings::default(), - QueueMode::Practice, - ), - Err(LearningSessionError::UnsupportedMode(QueueMode::Practice)) - )); -} - -#[test] -fn at_20_review_in_order_covers_each_key_once_updates_srs_and_wraps() { - let (library, id) = single_repertoire("1. e4 e5 (1... c5 2. c4) 2. Nf3 Nc6 *"); - let selected = scope(id, LearningSide::White); - let mut learning = LearningData::default(); - let mut session = mode_session( - "at20", - &library, - &learning, - selected, - QueueMode::ReviewInOrder, - ); - let expected = ["e2e4", "g1f3", "c2c4"]; - assert_eq!( - session - .queue - .iter() - .map(|target| target.key.expected_uci.as_str()) - .collect::>(), - expected - ); - - let mut first_cycle = Vec::new(); - for expected_uci in expected { - let current = session.current_target().unwrap().key.clone(); - assert_eq!(current.expected_uci, expected_uci); - assert!(!session.completed_keys.contains(¤t)); - first_cycle.push(current.clone()); - complete_target(&mut session, &mut learning, &library, "at20-first", NOW); - assert_eq!(learning.item(¤t).unwrap().correct_count, 1); - assert_eq!(learning.item(¤t).unwrap().correct_streak, 1); - assert_eq!( - learning.item(¤t).unwrap().next_review_at, - Some(NOW + DAY) - ); - } - assert_eq!( - first_cycle.len(), - first_cycle.iter().collect::>().len() - ); - assert_eq!(session.cycle, 1); - assert!(session.completed_keys.is_empty()); - assert_eq!(session.current_target().unwrap().key.expected_uci, "e2e4"); - - let e4 = session.current_target().unwrap().key.clone(); - complete_target( - &mut session, - &mut learning, - &library, - "at20-second", - NOW + DAY, - ); - assert_eq!(learning.item(&e4).unwrap().correct_count, 2); - assert_eq!(learning.item(&e4).unwrap().correct_streak, 2); - assert_eq!(session.cycle, 1); - assert!(session.completed_keys.contains(&e4)); - assert!( - !session - .completed_keys - .contains(&session.current_target().unwrap().key) - ); -} - -#[test] -fn review_cursor_resumes_mid_cycle_and_duplicate_event_does_not_advance_twice() { - let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 *"); - let selected = scope(id, LearningSide::White); - let learning = LearningData::default(); - let dir = TestDir::new("review-resume"); - let store = dir.store(); - let mut session = mode_session( - "review-resume", - &library, - &learning, - selected, - QueueMode::ReviewInOrder, - ); - let attempt = session - .play_uci(&library, "e2e4", "review-first", NOW, Some(100)) - .unwrap(); - commit(&store, &mut session, attempt.clone()); - let bytes = std::fs::read(dir.path()).unwrap(); - - let restored = store - .load() - .unwrap() - .session_snapshot("review-resume") - .cloned() - .unwrap() - .resume(&library) - .unwrap(); - assert_eq!(restored.current_index, 1); - assert_eq!(restored.cycle, 0); - assert_eq!(restored.completed_keys, session.completed_keys); - assert_eq!(restored.current_target().unwrap().key.expected_uci, "g1f3"); - - let mut duplicate_next = restored.clone(); - duplicate_next.current_index = 0; - duplicate_next.completed_keys.clear(); - duplicate_next.cycle = 9; - let duplicate = store - .apply_attempt_and_session(attempt, &mut duplicate_next) - .unwrap(); - assert_eq!(duplicate.application, AttemptApplication::Duplicate); - assert_eq!(duplicate.session, restored); - assert_eq!(duplicate.learning.attempts.len(), 1); - assert_eq!(std::fs::read(dir.path()).unwrap(), bytes); -} - -#[test] -fn at_21_variation_wrong_waits_for_the_next_due_pass_not_less_than_thirty_seconds() { - let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - let selected = scope(id, LearningSide::White); - let mut learning = LearningData::default(); - for expected in ["e2e4", "g1f3", "f1b5"] { - let key = key_for(&library, &selected, expected); - introduced_at(&mut learning, key.clone(), NOW - DAY); - learning.ensure_item(key).next_review_at = Some(NOW); - } - let e4 = key_for(&library, &selected, "e2e4"); - let mut session = LearningSessionSnapshot::new( - "at21", - &library, - &learning, - selected.clone(), - SrsSettings::default(), - ) - .unwrap(); - let original_queue = session.queue.clone(); - - let wrong = session - .play_uci(&library, "d2d4", "at21-wrong", NOW, Some(400)) - .unwrap(); - apply(&mut learning, wrong); - assert_eq!(learning.item(&e4).unwrap().next_review_at, Some(NOW + 30)); - assert_eq!(session.queue, original_queue); - assert_eq!(session.current_target().unwrap().key, e4); - let replay = session - .play_uci(&library, "e2e4", "at21-replay", NOW + 1, Some(900)) - .unwrap(); - apply(&mut learning, replay); - assert_eq!(session.queue, original_queue); - assert_eq!(session.current_target().unwrap().key.expected_uci, "g1f3"); - assert_eq!( - session - .queue - .iter() - .filter(|target| target.key == e4) - .count(), - 1 - ); - - complete_target(&mut session, &mut learning, &library, "at21-nf3", NOW + 2); - complete_target(&mut session, &mut learning, &library, "at21-bb5", NOW + 3); - assert_eq!(session.phase, LearningSessionPhase::Finished); - - session.stats_scope.as_of = NOW + 29; - assert_eq!(session.start_next_pass(&library, &learning).unwrap(), 0); - session.stats_scope.as_of = NOW + 30; - assert_eq!(session.start_next_pass(&library, &learning).unwrap(), 1); - assert_eq!(session.current_target().unwrap().key, e4); -} - -#[test] -fn least_recent_prioritizes_unseen_then_oldest_and_skips_early_checked_context() { - let (library, id) = single_repertoire("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - let selected = scope(id, LearningSide::White); - let e4 = key_for(&library, &selected, "e2e4"); - let nf3 = key_for(&library, &selected, "g1f3"); - let bb5 = key_for(&library, &selected, "f1b5"); - let mut learning = LearningData::default(); - introduced_at(&mut learning, e4.clone(), NOW - 10); - introduced_at(&mut learning, nf3.clone(), NOW - 100); - - let unseen_first = mode_session( - "least-unseen", - &library, - &learning, - selected.clone(), - QueueMode::LeastRecent, - ); - assert_eq!( - unseen_first - .queue - .iter() - .map(|target| target.key.expected_uci.as_str()) - .collect::>(), - ["f1b5", "g1f3", "e2e4"] - ); - - introduced_at(&mut learning, bb5.clone(), NOW - 50); - let mut session = mode_session( - "least-context", - &library, - &learning, - selected, - QueueMode::LeastRecent, - ); - assert_eq!( - session - .queue - .iter() - .map(|target| target.key.expected_uci.as_str()) - .collect::>(), - ["g1f3", "f1b5", "e2e4"] - ); - assert_eq!( - session.phase, - LearningSessionPhase::AwaitingContextIndependent - ); - assert_eq!(session.current_expected_uci(), Some("e2e4")); - - complete_target(&mut session, &mut learning, &library, "least-nf3", NOW); - assert!(session.completed_keys.contains(&e4)); - assert!(session.completed_keys.contains(&nf3)); - complete_target(&mut session, &mut learning, &library, "least-bb5", NOW + 1); - assert_eq!(session.phase, LearningSessionPhase::Finished); - assert_eq!(session.completed_keys.len(), 3); - for key in [e4, nf3, bb5] { - let independent = learning - .attempts - .iter() - .filter(|attempt| attempt.item_key() == key && attempt.event_type.is_independent()) - .count(); - assert_eq!(independent, 1, "duplicate review for {key:?}"); - } -} - -#[test] -fn at_22_shared_reset_preserves_cursor_journal_extensions_and_review_reset_preserves_srs() { - let mut library = Library::default(); - let first = add_repertoire(&mut library, "First", "1. e4 e5 2. Nf3 *"); - let second = add_repertoire(&mut library, "Second", "1. e4 c5 2. c4 *"); - let first_scope = scope(first, LearningSide::White); - let second_scope = scope(second, LearningSide::White); - let shared = key_for(&library, &first_scope, "e2e4"); - let nf3 = key_for(&library, &first_scope, "g1f3"); - let second_only = key_for(&library, &second_scope, "c2c4"); - let mut learning = LearningData::default(); - introduced_at(&mut learning, shared.clone(), NOW - 3 * DAY); - introduced_at(&mut learning, nf3.clone(), NOW - 2 * DAY); - introduced_at(&mut learning, second_only.clone(), NOW - DAY); - learning - .ensure_item(shared.clone()) - .independent_response_times_ms - .push(500); - learning - .attempts - .push(journal_attempt(&shared, "at22-old", NOW - DAY)); - let second_before = learning.item(&second_only).unwrap().clone(); - let pgn_before: Vec<_> = library - .repertoires - .iter() - .map(|repertoire| repertoire.pgn.clone()) - .collect(); - - let impact = reset_impact(&library, &first_scope).unwrap(); - assert_eq!((impact.reset_count, impact.shared_count), (2, 1)); - assert_eq!( - impact - .affected_repertoires - .iter() - .map(|repertoire| repertoire.name.as_str()) - .collect::>(), - BTreeSet::from(["First", "Second"]) - ); - - let dir = TestDir::new("shared-reset"); - let store = dir.store(); - std::fs::write( - dir.path(), - serde_json::to_vec_pretty(&LearningStoreData { - learning, - ..LearningStoreData::default() - }) - .unwrap(), - ) - .unwrap(); - let mut review = mode_session( - "at22", - &library, - &store.load().unwrap().learning, - first_scope.clone(), - QueueMode::ReviewInOrder, - ); - let review_attempt = review - .play_uci(&library, "e2e4", "at22-review", NOW, Some(250)) - .unwrap(); - commit(&store, &mut review, review_attempt); - let cursor_before = store - .load() - .unwrap() - .session_snapshot("at22") - .cloned() - .unwrap(); - assert_eq!(cursor_before.current_index, 1); - assert_eq!(cursor_before.completed_keys.len(), 1); - - let marker = serde_json::json!({"preserved": [1, {"nested": true}]}); - let mut raw: serde_json::Value = - serde_json::from_slice(&std::fs::read(dir.path()).unwrap()).unwrap(); - raw["future_root"] = marker.clone(); - raw["learning"]["future_learning"] = marker.clone(); - raw["learning"]["attempts"][0]["future_attempt"] = marker.clone(); - raw["session_snapshots"][0]["future_snapshot"] = marker.clone(); - raw["session_snapshots"][0]["queue"][0]["future_target"] = marker.clone(); - raw["legacy_practice"] = serde_json::json!({"raw_legacy": marker.clone()}); - let shared_index = raw["learning"]["items"] - .as_array() - .unwrap() - .iter() - .position(|item| { - item["key"]["position_fen4"] == serde_json::json!(shared.position_fen4.clone()) - && item["key"]["expected_uci"] == serde_json::json!("e2e4") - }) - .unwrap(); - raw["learning"]["items"][shared_index]["future_item"] = marker.clone(); - std::fs::write(dir.path(), serde_json::to_vec_pretty(&raw).unwrap()).unwrap(); - - #[cfg(unix)] - let old_path = dir.0.join("before-reset.json"); - #[cfg(unix)] - std::fs::hard_link(dir.path(), &old_path).unwrap(); - - let reset = store - .reset_learning(active_learning_keys(&library, &first_scope).unwrap()) - .unwrap(); - assert_eq!(reset.reset_count, 2); - assert_eq!( - reset.learning.item(&shared), - Some(&LearningItem::new(shared.clone())) - ); - assert_eq!( - reset.learning.item(&nf3), - Some(&LearningItem::new(nf3.clone())) - ); - assert_eq!(reset.learning.item(&second_only), Some(&second_before)); - assert!(reset.learning.item(&shared).unwrap().is_unseen()); - assert!(reset.learning.item(&nf3).unwrap().is_unseen()); - assert_eq!(reset.learning.attempts.len(), 2); - assert_eq!( - store.load().unwrap().session_snapshot("at22").unwrap(), - &cursor_before - ); - let second_summary = aggregate_scope( - &library, - &reset.learning, - &second_scope, - &SrsSettings::default(), - ) - .unwrap(); - assert!( - second_summary - .items - .iter() - .find(|item| item.key == shared) - .unwrap() - .is_unseen() - ); - assert_eq!( - library - .repertoires - .iter() - .map(|repertoire| repertoire.pgn.clone()) - .collect::>(), - pgn_before - ); - - let persisted_raw: serde_json::Value = - serde_json::from_slice(&std::fs::read(dir.path()).unwrap()).unwrap(); - for pointer in [ - "/future_root", - "/learning/future_learning", - "/learning/attempts/0/future_attempt", - "/session_snapshots/0/future_snapshot", - "/session_snapshots/0/queue/0/future_target", - "/legacy_practice/raw_legacy", - ] { - assert_eq!(persisted_raw.pointer(pointer), Some(&marker), "{pointer}"); - } - assert_eq!( - persisted_raw["learning"]["items"][shared_index]["future_item"], - marker - ); - #[cfg(unix)] - { - let old = LearningStore::new(old_path).load().unwrap(); - assert!(old.learning.item(&shared).unwrap().introduced); - assert_eq!(old.session_snapshot("at22"), Some(&cursor_before)); - } - - let duplicate = store - .apply_attempt( - journal_attempt(&shared, "at22-review", NOW), - &SrsSettings::default(), - ) - .unwrap(); - assert_eq!(duplicate.application, AttemptApplication::Duplicate); - assert!(duplicate.learning.item(&shared).unwrap().is_unseen()); - let fresh = store - .apply_attempt( - journal_attempt(&shared, "at22-fresh", NOW + DAY), - &SrsSettings::default(), - ) - .unwrap(); - let fresh_shared = fresh.learning.item(&shared).unwrap(); - assert_eq!(fresh_shared.correct_streak, 1); - assert_eq!(fresh_shared.correct_count, 1); - assert_eq!(fresh_shared.wrong_count, 0); - assert_eq!(fresh_shared.accuracy_percent(), Some(100.0)); - assert_eq!(fresh_shared.independent_response_times_ms, [200]); - assert_eq!(fresh.learning.attempts.len(), 3); - - let before_review_reset = store.load().unwrap().learning; - store.reset_review_order(&mut review).unwrap(); - assert_eq!(review.current_index, 0); - assert_eq!(review.cycle, 0); - assert!(review.completed_keys.is_empty()); - assert_eq!(store.load().unwrap().learning, before_review_reset); -} - -#[test] -fn old_scope_and_mode_snapshot_defaults_remain_deserializable() { - let (library, id) = single_repertoire("1. e4 *"); - let selected = scope(id, LearningSide::White); - let session = mode_session( - "defaults", - &library, - &LearningData::default(), - selected, - QueueMode::ReviewInOrder, - ); - let mut raw = serde_json::to_value(session).unwrap(); - raw.as_object_mut().unwrap().remove("cycle"); - raw["stats_scope"] - .as_object_mut() - .unwrap() - .remove("learning_priority"); - for field in ["pgn_order", "variation_depth"] { - raw["queue"][0].as_object_mut().unwrap().remove(field); - } - - let restored: LearningSessionSnapshot = serde_json::from_value(raw).unwrap(); - assert_eq!(restored.cycle, 0); - assert_eq!( - restored.stats_scope.learning_priority, - LearningPriority::DepthFirst - ); - assert_eq!(restored.queue[0].pgn_order, 0); - assert_eq!(restored.queue[0].variation_depth, 0); - restored.resume(&library).unwrap(); -} diff --git a/crates/trainer/src/repertoire/model.rs b/crates/trainer/src/repertoire/model.rs deleted file mode 100644 index 04aeebf..0000000 --- a/crates/trainer/src/repertoire/model.rs +++ /dev/null @@ -1,789 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::fmt; -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; - -use chess_core::shakmaty::uci::UciMove; -use chess_core::shakmaty::{CastlingMode, Color, Position}; -use chess_core::{EditError, Game, MoveKind, NodeId, StartPosition, paste}; -use serde::{Deserialize, Serialize}; -use web_time::{SystemTime, UNIX_EPOCH}; - -use super::tree::{RepertoireTree, fen4}; - -pub const LIBRARY_VERSION: u32 = 1; -pub const DEFAULT_MAX_PLIES: u32 = 20; - -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(transparent)] -pub struct RepertoireId(String); - -impl RepertoireId { - pub fn as_str(&self) -> &str { - &self.0 - } - - fn new() -> Self { - let nanos = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_nanos()); - let sequence = NEXT_ID.fetch_add(1, Ordering::Relaxed); - Self(format!("r-{nanos:x}-{}-{sequence:x}", std::process::id())) - } - - pub(crate) fn legacy(start: &str) -> Self { - Self(format!("legacy-{:016x}", stable_hash(start.as_bytes()))) - } -} - -impl fmt::Display for RepertoireId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(rename_all = "SCREAMING_SNAKE_CASE")] -pub enum LearningSide { - White, - Black, -} - -impl LearningSide { - pub fn color(self) -> Color { - match self { - Self::White => Color::White, - Self::Black => Color::Black, - } - } -} - -impl From for LearningSide { - fn from(color: Color) -> Self { - match color { - Color::White => Self::White, - Color::Black => Self::Black, - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct Repertoire { - pub id: RepertoireId, - pub name: String, - pub pgn: String, - pub max_plies: u32, - pub disabled_prefixes: Vec>, - #[serde(skip_serializing_if = "BTreeMap::is_empty")] - pub main_answer_overrides: BTreeMap, - pub path: Option, - pub detached: bool, -} - -impl Default for Repertoire { - fn default() -> Self { - Self { - id: RepertoireId::new(), - name: String::new(), - pgn: Game::new().to_pgn(), - max_plies: DEFAULT_MAX_PLIES, - disabled_prefixes: Vec::new(), - main_answer_overrides: BTreeMap::new(), - path: None, - detached: false, - } - } -} - -impl Repertoire { - pub fn game(&self) -> Game { - chess_core::parse_str(&self.pgn).game - } - - pub fn set_max_plies(&mut self, max_plies: u32) { - self.max_plies = max_plies; - } - - pub fn set_prefix_disabled( - &mut self, - prefix: &[String], - disabled: bool, - ) -> Result<(), RepertoireError> { - if prefix.is_empty() || prefix.iter().any(|m| m.is_empty()) { - return Err(RepertoireError::EmptyDisabledPrefix); - } - self.disabled_prefixes - .retain(|existing| existing.as_slice() != prefix); - if disabled { - self.disabled_prefixes.push(prefix.to_vec()); - } - self.disabled_prefixes.sort(); - self.disabled_prefixes.dedup(); - Ok(()) - } - - pub fn is_prefix_disabled(&self, path: &[String]) -> bool { - self.disabled_prefixes - .iter() - .any(|prefix| path.starts_with(prefix)) - } - - pub fn main_answer_override(&self, position_fen4: &str) -> Option<&str> { - self.main_answer_overrides - .get(position_fen4) - .map(String::as_str) - } - - pub fn set_main_answer_override( - &mut self, - position_fen4: &str, - expected_uci: &str, - side: LearningSide, - ) -> Result<(), RepertoireError> { - let tree = RepertoireTree::new(self); - let game = tree.game(); - let mut position_found = false; - for node in game.attached_nodes() { - if tree.position_key(node) != Some(position_fen4) || tree.path(node).is_none() { - continue; - } - position_found = true; - let actual_side = game - .position(node) - .map(|position| LearningSide::from(position.turn())); - if actual_side != Some(side) { - return Err(RepertoireError::MainAnswerWrongSide { - position_fen4: position_fen4.to_owned(), - expected: side, - actual: actual_side, - }); - } - let exists = game.children(node).iter().any(|child| { - let Some(game_move) = game.game_move(*child) else { - return false; - }; - match game_move.kind { - MoveKind::Normal(mv) => { - mv.to_uci(CastlingMode::Standard).to_string() == expected_uci - } - MoveKind::Null => false, - } - }); - if exists { - self.main_answer_overrides - .insert(position_fen4.to_owned(), expected_uci.to_owned()); - return Ok(()); - } - } - if position_found { - Err(RepertoireError::MainAnswerMoveNotFound { - position_fen4: position_fen4.to_owned(), - expected_uci: expected_uci.to_owned(), - }) - } else { - Err(RepertoireError::MainAnswerPositionNotFound( - position_fen4.to_owned(), - )) - } - } - - pub fn clear_main_answer_override(&mut self, position_fen4: &str) -> Option { - self.main_answer_overrides.remove(position_fen4) - } -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(default)] -pub struct Library { - pub version: u32, - pub revision: u64, - pub repertoires: Vec, -} - -impl Default for Library { - fn default() -> Self { - Self { - version: LIBRARY_VERSION, - revision: 0, - repertoires: Vec::new(), - } - } -} - -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub struct MergeReport { - pub added_nodes: usize, - pub merged_nodes: usize, - pub annotation_changes: usize, -} - -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct LegacyMigrationReport { - pub repertoires: usize, - pub lines: usize, - pub skipped: Vec, -} - -#[derive(Debug)] -pub enum RepertoireError { - EmptyName, - NotFound(RepertoireId), - DuplicateId(RepertoireId), - EmptyDisabledPrefix, - MainAnswerPositionNotFound(String), - MainAnswerMoveNotFound { - position_fen4: String, - expected_uci: String, - }, - MainAnswerWrongSide { - position_fen4: String, - expected: LearningSide, - actual: Option, - }, - DifferentStart { - expected: String, - actual: String, - }, - UnparsedMerge, - Merge(String), - Edit(EditError), -} - -impl fmt::Display for RepertoireError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::EmptyName => f.write_str("repertoire name must not be empty"), - Self::NotFound(id) => write!(f, "repertoire not found: {id}"), - Self::DuplicateId(id) => write!(f, "repertoire id is already present: {id}"), - Self::EmptyDisabledPrefix => f.write_str("disabled UCI prefix must not be empty"), - Self::MainAnswerPositionNotFound(position) => { - write!( - f, - "main-answer position is not present in the PGN: {position}" - ) - } - Self::MainAnswerMoveNotFound { - position_fen4, - expected_uci, - } => write!( - f, - "main answer {expected_uci} is not a PGN move at {position_fen4}" - ), - Self::MainAnswerWrongSide { - position_fen4, - expected, - actual, - } => write!( - f, - "main answer side mismatch at {position_fen4}: requested {expected:?}, position has {actual:?}" - ), - Self::DifferentStart { expected, actual } => write!( - f, - "different starting positions: repertoire has {expected}, imported game has {actual}" - ), - Self::UnparsedMerge => { - f.write_str("cannot merge an unparsed PGN tail into an existing move") - } - Self::Merge(message) => write!(f, "PGN merge failed: {message}"), - Self::Edit(error) => error.fmt(f), - } - } -} - -impl std::error::Error for RepertoireError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Edit(error) => Some(error), - _ => None, - } - } -} - -impl From for RepertoireError { - fn from(error: EditError) -> Self { - Self::Edit(error) - } -} - -impl Library { - pub fn validate(&self) -> Result<(), RepertoireError> { - let mut ids = BTreeSet::new(); - for repertoire in &self.repertoires { - if !ids.insert(repertoire.id.clone()) { - return Err(RepertoireError::DuplicateId(repertoire.id.clone())); - } - } - Ok(()) - } - - pub fn repertoire(&self, id: &RepertoireId) -> Option<&Repertoire> { - self.repertoires.iter().find(|r| &r.id == id) - } - - pub fn repertoire_mut(&mut self, id: &RepertoireId) -> Option<&mut Repertoire> { - self.repertoires.iter_mut().find(|r| &r.id == id) - } - - pub fn create_empty( - &mut self, - name: impl Into, - ) -> Result { - self.create(name, &Game::new()) - } - - pub fn create( - &mut self, - name: impl Into, - game: &Game, - ) -> Result { - let name = checked_name(name.into())?; - let id = RepertoireId::new(); - self.repertoires.push(Repertoire { - id: id.clone(), - name, - pgn: game.to_pgn(), - max_plies: DEFAULT_MAX_PLIES, - disabled_prefixes: Vec::new(), - main_answer_overrides: BTreeMap::new(), - path: None, - detached: false, - }); - Ok(id) - } - - pub fn rename( - &mut self, - id: &RepertoireId, - name: impl Into, - ) -> Result<(), RepertoireError> { - let name = checked_name(name.into())?; - self.repertoire_mut(id) - .ok_or_else(|| RepertoireError::NotFound(id.clone()))? - .name = name; - Ok(()) - } - - pub fn delete(&mut self, id: &RepertoireId) -> Result { - let index = self - .repertoires - .iter() - .position(|r| &r.id == id) - .ok_or_else(|| RepertoireError::NotFound(id.clone()))?; - Ok(self.repertoires.remove(index)) - } - - /// Merges the complete source tree. The source game is never modified; an error - /// leaves the repertoire at its previous PGN snapshot. - pub fn add_game( - &mut self, - id: &RepertoireId, - source: &Game, - ) -> Result { - let repertoire = self - .repertoire_mut(id) - .ok_or_else(|| RepertoireError::NotFound(id.clone()))?; - let mut target = repertoire.game(); - check_start(&target, source)?; - let target_is_empty = target.children(NodeId::ROOT).is_empty() - && target.node(NodeId::ROOT).is_some_and(|root| { - root.nags().is_empty() - && root.comments_before().is_empty() - && root.comments_after().is_empty() - && root.unparsed().is_empty() - }); - if target_is_empty { - repertoire.pgn = source.to_pgn(); - return Ok(MergeReport { - added_nodes: source.attached_nodes().len().saturating_sub(1), - merged_nodes: 1, - annotation_changes: 0, - }); - } - let mut report = MergeReport::default(); - merge_annotations(&mut target, NodeId::ROOT, source, NodeId::ROOT, &mut report)?; - report.merged_nodes += 1; - merge_children( - &mut target, - NodeId::ROOT, - source, - NodeId::ROOT, - true, - &mut report, - )?; - repertoire.pgn = target.to_pgn(); - Ok(report) - } - - /// Adds exactly the path from the source root through `at`, without siblings or - /// descendants of `at`. Node comments and NAGs on the selected path are merged. - pub fn add_prefix( - &mut self, - id: &RepertoireId, - source: &Game, - at: NodeId, - ) -> Result { - if !source.is_attached(at) { - return Err(RepertoireError::Merge( - "selected source node is not attached".into(), - )); - } - let repertoire = self - .repertoire_mut(id) - .ok_or_else(|| RepertoireError::NotFound(id.clone()))?; - let mut target = repertoire.game(); - check_start(&target, source)?; - let mut report = MergeReport::default(); - merge_annotations(&mut target, NodeId::ROOT, source, NodeId::ROOT, &mut report)?; - report.merged_nodes += 1; - let mut target_parent = NodeId::ROOT; - for source_node in source.path(at).into_iter().skip(1) { - target_parent = merge_node( - &mut target, - target_parent, - source, - source_node, - false, - &mut report, - )?; - } - repertoire.pgn = target.to_pgn(); - Ok(report) - } - - /// Deterministically reconstructs playable lines stored in legacy line keys. The - /// legacy aggregates remain in `StatsData::legacy_lines`; no per-move history is - /// inferred from them. - pub fn migrate_legacy_lines( - &mut self, - legacy: &serde_json::Map, - ) -> LegacyMigrationReport { - let mut groups: BTreeMap>> = BTreeMap::new(); - let mut report = LegacyMigrationReport::default(); - for key in legacy.keys() { - let Some((start, moves)) = key.split_once(" | ") else { - report.skipped.push(key.clone()); - continue; - }; - let line: Vec = moves - .split_whitespace() - .filter(|m| !m.is_empty()) - .map(str::to_owned) - .collect(); - if line.is_empty() || line.iter().any(|m| m.parse::().is_err()) { - report.skipped.push(key.clone()); - continue; - } - groups.entry(start.to_owned()).or_default().push(line); - } - for (start, mut lines) in groups { - lines.sort(); - lines.dedup(); - let id = RepertoireId::legacy(&start); - if self.repertoire(&id).is_none() { - let Ok(position) = StartPosition::from_fen(&format!("{start} 0 1")) else { - report - .skipped - .extend(lines.into_iter().map(|line| line.join(" "))); - continue; - }; - let number = self - .repertoires - .iter() - .filter(|r| r.id.as_str().starts_with("legacy-")) - .count() - + 1; - self.repertoires.push(Repertoire { - id: id.clone(), - name: format!("Перенесённые линии {number}"), - pgn: Game::from_start(position).to_pgn(), - max_plies: DEFAULT_MAX_PLIES, - disabled_prefixes: Vec::new(), - main_answer_overrides: BTreeMap::new(), - path: None, - detached: false, - }); - report.repertoires += 1; - } - let Some(mut game) = self.repertoire(&id).map(Repertoire::game) else { - continue; - }; - for line in lines { - match game.add_uci_line(NodeId::ROOT, &line) { - Ok(_) => report.lines += 1, - Err(_) => report.skipped.push(line.join(" ")), - } - } - if let Some(repertoire) = self.repertoire_mut(&id) { - repertoire.pgn = game.to_pgn(); - } - } - report - } -} - -fn checked_name(name: String) -> Result { - let name = name.trim(); - if name.is_empty() { - Err(RepertoireError::EmptyName) - } else { - Ok(name.to_owned()) - } -} - -fn check_start(target: &Game, source: &Game) -> Result<(), RepertoireError> { - let expected = fen4(target.start().position()); - let actual = fen4(source.start().position()); - if expected == actual { - Ok(()) - } else { - Err(RepertoireError::DifferentStart { expected, actual }) - } -} - -fn merge_children( - target: &mut Game, - target_parent: NodeId, - source: &Game, - source_parent: NodeId, - recursive: bool, - report: &mut MergeReport, -) -> Result<(), RepertoireError> { - for source_child in source.children(source_parent) { - merge_node( - target, - target_parent, - source, - *source_child, - recursive, - report, - )?; - } - Ok(()) -} - -fn merge_node( - target: &mut Game, - target_parent: NodeId, - source: &Game, - source_node: NodeId, - recursive: bool, - report: &mut MergeReport, -) -> Result { - let kind = source - .game_move(source_node) - .map(|m| m.kind) - .ok_or_else(|| RepertoireError::Merge("source node has no move".into()))?; - if let Some(existing) = target - .children(target_parent) - .iter() - .copied() - .find(|child| target.game_move(*child).is_some_and(|m| m.kind == kind)) - { - report.merged_nodes += 1; - merge_annotations(target, existing, source, source_node, report)?; - if recursive { - merge_unparsed(target, existing, source, source_node)?; - } - if recursive { - merge_children(target, existing, source, source_node, true, report)?; - } - return Ok(existing); - } - - let plain = matches!(kind, MoveKind::Normal(_)) - && source - .node(source_node) - .is_some_and(|n| n.unparsed().is_empty()); - let target_node = if plain { - let MoveKind::Normal(mv) = kind else { - return Err(RepertoireError::Merge("invalid normal move".into())); - }; - let id = target.add_line(target_parent, &[mv])?; - merge_annotations(target, id, source, source_node, report)?; - report.added_nodes += 1; - id - } else { - let text = subtree_pgn(source, source_node, recursive, recursive); - // Clipboard matching searches the entire target for a matching position and - // may choose another occurrence. An empty local target makes the graft exact: - // no matched prefix, transposition or extra branch can redirect the insertion. - let fen = target - .fen(target_parent) - .ok_or_else(|| RepertoireError::Merge("missing target parent position".into()))?; - let start = StartPosition::from_fen(&fen) - .map_err(|error| RepertoireError::Merge(error.to_string()))?; - let local = Game::from_start(start); - let mut plan = paste::plan(&local, NodeId::ROOT, &text) - .map_err(|e| RepertoireError::Merge(format!("{e:?}")))?; - if plan.at != NodeId::ROOT { - return Err(RepertoireError::Merge( - "PGN graft did not start at its root".into(), - )); - } - plan.at = target_parent; - plan.continuation = target.children(target_parent).is_empty(); - let id = target.apply_paste(&plan)?; - let count = if recursive { - subtree_len(source, source_node) - } else { - 1 - }; - report.added_nodes += count; - id - }; - if plain && recursive { - merge_children(target, target_node, source, source_node, true, report)?; - } - Ok(target_node) -} - -fn merge_unparsed( - target: &Game, - target_node: NodeId, - source: &Game, - source_node: NodeId, -) -> Result<(), RepertoireError> { - let Some(source_node) = source.node(source_node) else { - return Ok(()); - }; - if source_node.unparsed().is_empty() { - return Ok(()); - } - if target - .node(target_node) - .is_some_and(|node| node.unparsed() == source_node.unparsed()) - { - Ok(()) - } else { - Err(RepertoireError::UnparsedMerge) - } -} - -fn subtree_len(game: &Game, root: NodeId) -> usize { - let mut stack = vec![root]; - let mut count = 0; - while let Some(node) = stack.pop() { - count += 1; - stack.extend(game.children(node)); - } - count -} - -fn merge_annotations( - target: &mut Game, - target_node: NodeId, - source: &Game, - source_node: NodeId, - report: &mut MergeReport, -) -> Result<(), RepertoireError> { - let (Some(source_node), Some(current)) = (source.node(source_node), target.node(target_node)) - else { - return Err(RepertoireError::Merge("missing annotation node".into())); - }; - let nags = union(current.nags().to_vec(), source_node.nags().to_vec()); - let before = union( - current.comments_before().to_vec(), - source_node.comments_before().to_vec(), - ); - let after = union( - current.comments_after().to_vec(), - source_node.comments_after().to_vec(), - ); - let changed = nags.len() != current.nags().len() - || before.len() != current.comments_before().len() - || after.len() != current.comments_after().len(); - target.annotate(target_node, nags, after)?; - target.set_comments_before(target_node, before)?; - report.annotation_changes += usize::from(changed); - Ok(()) -} - -fn union(mut target: Vec, source: Vec) -> Vec { - for value in source { - if !target.contains(&value) { - target.push(value); - } - } - target -} - -fn subtree_pgn(source: &Game, node: NodeId, recursive: bool, raw: bool) -> String { - let fen = source - .position_before(node) - .map(|p| { - chess_core::shakmaty::fen::Fen::from_position( - p, - chess_core::shakmaty::EnPassantMode::Legal, - ) - }) - .map(|f| f.to_string()) - .unwrap_or_else(|| source.start().fen()); - let mut out = format!("[SetUp \"1\"]\n[FEN \"{fen}\"]\n\n"); - write_move(source, node, &mut out, raw); - if recursive { - write_line(source, node, &mut out); - } - out.push_str(" *\n"); - out -} - -fn write_line(game: &Game, parent: NodeId, out: &mut String) { - let mut current = parent; - while let Some(main) = game.children(current).first().copied() { - write_move(game, main, out, true); - for alternative in game.children(current).iter().skip(1) { - out.push_str(" ("); - write_move(game, *alternative, out, true); - write_line(game, *alternative, out); - out.push(')'); - } - current = main; - } -} - -fn write_move(game: &Game, node: NodeId, out: &mut String, raw: bool) { - let Some(data) = game.node(node) else { - return; - }; - for comment in data.comments_before() { - write_comment(comment, out); - } - if let Some(mv) = data.game_move() { - out.push(' '); - out.push_str(&mv.san); - } - for nag in data.nags() { - out.push_str(&format!(" ${}", nag.0)); - } - for comment in data.comments_after() { - write_comment(comment, out); - } - if raw { - for text in data.unparsed() { - out.push(' '); - out.push_str(text); - } - } -} - -fn write_comment(comment: &str, out: &mut String) { - if comment.contains('}') { - for line in comment.lines() { - out.push_str(&format!("\n;{}\n", line.trim())); - } - } else { - out.push_str(&format!(" {{{comment}}}")); - } -} - -pub(crate) fn stable_hash(bytes: &[u8]) -> u64 { - let mut hash = 0xcbf29ce484222325_u64; - for byte in bytes { - hash ^= u64::from(*byte); - hash = hash.wrapping_mul(0x100000001b3); - } - hash -} diff --git a/crates/trainer/src/repertoire/scope.rs b/crates/trainer/src/repertoire/scope.rs deleted file mode 100644 index 38e788d..0000000 --- a/crates/trainer/src/repertoire/scope.rs +++ /dev/null @@ -1,43 +0,0 @@ -use serde::{Deserialize, Serialize}; - -/// A durable training area. The selected move is included; `end_prefix`, when present, -/// is also included and forms an early boundary. Node IDs never participate. -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(default)] -pub struct TrainingScope { - pub prefix: Vec, - pub end_prefix: Option>, - /// Replay the path before the selected move/target as automatic context. - pub include_context: bool, -} - -impl TrainingScope { - pub fn whole() -> Self { - Self::default() - } - - pub(crate) fn parent_prefix(&self) -> &[String] { - self.prefix - .get(..self.prefix.len().saturating_sub(1)) - .unwrap_or(&[]) - } -} - -impl Default for TrainingScope { - fn default() -> Self { - Self { - prefix: Vec::new(), - end_prefix: None, - include_context: true, - } - } -} - -/// Identity of a training area for queues and history. Context presentation deliberately -/// does not split learning data. -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -#[serde(default)] -pub struct TrainingScopeKey { - pub prefix: Vec, - pub end_prefix: Option>, -} diff --git a/crates/trainer/src/repertoire/session_tests.rs b/crates/trainer/src/repertoire/session_tests.rs deleted file mode 100644 index 5a42576..0000000 --- a/crates/trainer/src/repertoire/session_tests.rs +++ /dev/null @@ -1,1178 +0,0 @@ -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; - -use super::*; - -const NOW: i64 = 1_800_000_000; -const DAY: i64 = 24 * 60 * 60; -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-session-{}-{}-{name}", - std::process::id(), - sequence - )); - 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")) - } - - fn path(&self) -> PathBuf { - self.0.join("learning.json") - } -} - -impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -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 scope(id: RepertoireId, side: LearningSide) -> StatsScope { - StatsScope::for_repertoire(id, side, NOW) -} - -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 introduce_at(learning: &mut LearningData, key: LearningItemKey, next_review_at: i64) { - let item = learning.ensure_item(key); - item.introduced = true; - item.next_review_at = Some(next_review_at); -} - -fn due_session( - id: &str, - library: &Library, - learning: &LearningData, - scope: StatsScope, -) -> LearningSessionSnapshot { - LearningSessionSnapshot::new(id, library, learning, scope, SrsSettings::default()).unwrap() -} - -fn seed_store(dir: &TestDir, learning: &LearningData) { - let data = LearningStoreData { - learning: learning.clone(), - ..LearningStoreData::default() - }; - let bytes = serde_json::to_vec_pretty(&data).unwrap(); - std::fs::write(dir.path(), bytes).unwrap(); -} - -fn commit( - store: &LearningStore, - session: &mut LearningSessionSnapshot, - attempt: TrainingAttempt, -) -> PersistedSessionAttempt { - let persisted = store.apply_attempt_and_session(attempt, session).unwrap(); - *session = persisted.session.clone(); - persisted -} - -fn play( - store: &LearningStore, - library: &Library, - session: &mut LearningSessionSnapshot, - uci: &str, - id: &str, - at: i64, - response_time_ms: Option, -) -> PersistedSessionAttempt { - let attempt = session - .play_uci(library, uci, id, at, response_time_ms) - .unwrap(); - commit(store, session, attempt) -} - -fn advance( - store: &LearningStore, - library: &Library, - session: &mut LearningSessionSnapshot, - id: &str, - at: i64, -) -> PersistedSessionAttempt { - let attempt = session.advance_context(library, id, at).unwrap(); - commit(store, session, attempt) -} - -fn restore(store: &LearningStore, library: &Library, id: &str) -> LearningSessionSnapshot { - store - .load() - .unwrap() - .session_snapshot(id) - .cloned() - .unwrap() - .resume(library) - .unwrap() -} - -#[cfg(unix)] -fn file_inode(path: &std::path::Path) -> u64 { - use std::os::unix::fs::MetadataExt as _; - std::fs::metadata(path).unwrap().ino() -} - -#[test] -fn initial_queue_is_due_only_and_zero_due_finishes_without_unseen() { - let (library, id) = library("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let nf3 = key_for(&library, &scope, "g1f3"); - let bb5 = key_for(&library, &scope, "f1b5"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, e4.clone(), NOW); - introduce_at(&mut learning, nf3, NOW + DAY); - - let session = due_session("due", &library, &learning, scope.clone()); - assert_eq!(session.queue.len(), 1); - assert_eq!(session.current_target().unwrap().key, e4); - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - assert!(!session.queue.iter().any(|target| target.key == bb5)); - - let empty = due_session("empty", &library, &LearningData::default(), scope); - assert_eq!(empty.phase, LearningSessionPhase::Finished); - assert!(empty.queue.is_empty()); - assert_eq!(empty.remaining(), 0); -} - -#[test] -fn introduction_is_explicit_and_does_not_introduce_until_an_answer() { - let (library, id) = library("1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *"); - let scope = scope(id, LearningSide::White); - let learning = LearningData::default(); - let mut session = due_session("introduce", &library, &learning, scope.clone()); - assert_eq!(session.phase, LearningSessionPhase::Finished); - - assert_eq!(session.introduce_new(&library, &learning).unwrap(), 3); - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - assert!(learning.items.is_empty()); - assert!(session.completed_keys.is_empty()); - - let store = TestDir::new("introduce"); - let store = store.store(); - let persisted = play( - &store, - &library, - &mut session, - "e2e4", - "first-new", - NOW, - Some(100), - ); - let first = persisted - .learning - .item(&key_for(&library, &scope, "e2e4")) - .unwrap(); - assert!(first.introduced); - assert_eq!(first.correct_streak, 1); - assert_eq!(session.completed_keys.len(), 1); -} - -#[test] -fn illegal_input_and_unscheduled_repertoire_answer_do_not_change_learning() { - let (library, id) = library("1. e4 (1. d4) e5 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, e4.clone(), NOW); - let before = learning.item(&e4).unwrap().clone(); - let dir = TestDir::new("illegal"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("strict", &library, &learning, scope); - - let illegal = play( - &store, - &library, - &mut session, - "e2e5", - "illegal", - NOW, - Some(9_999), - ); - assert_eq!( - illegal.learning.attempts[0].event_type, - TrainingEventType::IllegalMove - ); - assert_eq!(illegal.learning.attempts[0].response_time_ms, None); - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - assert_eq!(illegal.learning.item(&e4), Some(&before)); - - let before_session = session.clone(); - assert!(matches!( - session.play_uci(&library, "d2d4", "legal-alternative", NOW + 1, Some(250)), - Err(LearningSessionError::RepertoireAlternative { - already_completed: false - }) - )); - assert_eq!(session, before_session); - let unchanged = store.load().unwrap().learning; - assert_eq!(unchanged.attempts.len(), 1); - assert_eq!(unchanged.item(&e4), Some(&before)); -} - -#[test] -fn at_05_wrong_then_repeated_replay_records_one_independent_wrong() { - let (library, id) = library("1. e4 e5 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, e4.clone(), NOW); - let dir = TestDir::new("wrong-replay"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("wrong-replay", &library, &learning, scope); - - let wrong = play( - &store, - &library, - &mut session, - "d2d4", - "wrong", - NOW, - Some(500), - ); - let after_wrong = wrong.learning.item(&e4).unwrap().clone(); - assert_eq!(after_wrong.correct_streak, 0); - assert_eq!(after_wrong.wrong_count, 1); - assert_eq!(after_wrong.next_review_at, Some(NOW + 30)); - assert_eq!(after_wrong.independent_response_times_ms, [500]); - assert_eq!( - session - .presentation(&library) - .unwrap() - .revealed_move - .as_deref(), - Some("e2e4") - ); - - let repeated_wrong = play( - &store, - &library, - &mut session, - "c2c4", - "replay-wrong", - NOW + 1, - Some(800), - ); - assert_eq!( - repeated_wrong.learning.attempts[1].event_type, - TrainingEventType::ReplayAfterError - ); - assert_eq!(repeated_wrong.learning.attempts[1].response_time_ms, None); - assert_eq!(repeated_wrong.learning.item(&e4), Some(&after_wrong)); - assert_eq!( - session.phase, - LearningSessionPhase::AwaitingReplayAfterError - ); - - let replayed = play( - &store, - &library, - &mut session, - "e2e4", - "replay-expected", - NOW + 2, - Some(900), - ); - assert_eq!( - replayed.learning.attempts[2].event_type, - TrainingEventType::ReplayAfterError - ); - assert_eq!(replayed.learning.attempts[2].response_time_ms, None); - assert_eq!(replayed.learning.item(&e4), Some(&after_wrong)); - assert_eq!( - replayed - .learning - .item(&e4) - .unwrap() - .independent_attempt_count(), - 1 - ); - assert_eq!(session.phase, LearningSessionPhase::Finished); - assert!(session.completed_keys.contains(&e4)); -} - -#[test] -fn pending_alternative_credits_only_the_played_answer_and_keeps_original_pending() { - let (library, id) = library("1. e4 (1. d4) *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let d4 = key_for(&library, &scope, "d2d4"); - let mut session = due_session("alternatives", &library, &LearningData::default(), scope); - assert_eq!( - session - .introduce_new(&library, &LearningData::default()) - .unwrap(), - 2 - ); - assert_eq!(session.current_target().unwrap().key, e4); - let dir = TestDir::new("alternatives"); - let store = dir.store(); - let first = play( - &store, - &library, - &mut session, - "d2d4", - "d4-first", - NOW, - Some(123), - ); - assert_eq!(first.learning.attempts[0].item_key(), d4); - assert_eq!(first.learning.item(&d4).unwrap().correct_count, 1); - assert!(first.learning.item(&e4).is_none()); - assert_eq!(session.current_target().unwrap().key, e4); - assert_eq!(session.remaining(), 1); - session = restore(&store, &library, "alternatives"); - let before = session.clone(); - assert!(matches!( - session.play_uci(&library, "d2d4", "d4-again", NOW + 1, Some(12)), - Err(LearningSessionError::RepertoireAlternative { - already_completed: true - }) - )); - assert_eq!(session, before); - assert_eq!(store.load().unwrap().learning.attempts.len(), 1); - let second = play( - &store, - &library, - &mut session, - "e2e4", - "e4-next", - NOW + 2, - Some(124), - ); - assert_eq!(second.learning.item(&e4).unwrap().correct_count, 1); - assert_eq!(second.learning.item(&d4).unwrap().correct_count, 1); - assert_eq!(session.phase, LearningSessionPhase::Finished); - assert_eq!(session.completed_keys.len(), 2); -} - -#[test] -fn prepared_answer_cache_preserves_live_classification_and_credit() { - let (library, id) = library("1. e4 (1. d4) (1. c4) *"); - let selected = scope(id, LearningSide::White); - let answers = active_learning_keys(&library, &selected).unwrap(); - let mut learning = LearningData::default(); - for uci in ["e2e4", "d2d4"] { - introduce_at(&mut learning, key_for(&library, &selected, uci), NOW); - } - let original = due_session("answer-cache", &library, &learning, selected); - for uci in ["e2e4", "d2d4", "c2c4", "a2a3", "e2e5"] { - let mut direct = original.clone(); - let mut cached = original.clone(); - let first = - direct.play_uci_with_learning(&library, &learning, uci, "answer", NOW, Some(123)); - let second = cached.play_uci_with_learning_answers( - &library, - &learning, - &answers, - uci, - "answer", - NOW, - Some(123), - ); - assert_eq!(first, second, "different event for {uci}"); - assert_eq!(direct, cached, "different session transition for {uci}"); - } -} - -#[test] -fn alternative_during_context_does_not_continue_the_unplayed_branch() { - let (library, id) = library("1. e4 (1. d4 d5 2. c4) e5 2. Nf3 (2. Bc4) Nc6 *"); - let scope = scope(id, LearningSide::White); - let mut session = LearningSessionSnapshot::new_with_mode( - "context-alternative", - &library, - &LearningData::default(), - scope, - SrsSettings::default(), - QueueMode::LeastRecent, - ) - .unwrap(); - let deep = session - .queue - .iter() - .position(|target| target.key.expected_uci == "g1f3") - .unwrap(); - session.queue.swap(0, deep); - session.phase = LearningSessionPhase::AwaitingContextIndependent; - session.context_index = 0; - let original = session.current_target().unwrap().key.clone(); - session.validate(&library).unwrap(); - let dir = TestDir::new("context-alternative"); - let first = play( - &dir.store(), - &library, - &mut session, - "d2d4", - "d4-context", - NOW, - Some(300), - ); - assert_eq!(first.learning.attempts[0].expected_uci, "d2d4"); - assert_eq!( - first.learning.attempts[0].event_type, - TrainingEventType::CorrectIndependent - ); - assert!(!session.completed_keys.contains(&original)); - assert!( - session - .queue - .iter() - .skip(session.current_index) - .any(|target| target.key == original) - ); - assert_eq!( - session.context_index, 0, - "do not increment the e4 path after playing d4" - ); - session.validate(&library).unwrap(); - let restored = restore(&dir.store(), &library, "context-alternative"); - assert_eq!(restored, session); -} - -#[test] -fn replay_stays_on_revealed_answer_and_disabled_alternative_is_not_accepted() { - let (mut library, id) = library("1. e4 (1. d4) *"); - let selected = scope(id.clone(), LearningSide::White); - let mut session = due_session( - "replay-choices", - &library, - &LearningData::default(), - selected.clone(), - ); - session - .introduce_new(&library, &LearningData::default()) - .unwrap(); - session.preview("preview", NOW).unwrap(); - let before = session.clone(); - assert!(matches!( - session.play_uci(&library, "d2d4", "other-preview", NOW, None), - Err(LearningSessionError::RepertoireAlternative { - already_completed: false - }) - )); - assert_eq!(session, before); - library - .repertoire_mut(&id) - .unwrap() - .set_prefix_disabled(&["d2d4".to_owned()], true) - .unwrap(); - let mut session = due_session( - "disabled-choice", - &library, - &LearningData::default(), - selected, - ); - session - .introduce_new(&library, &LearningData::default()) - .unwrap(); - let attempt = session - .play_uci(&library, "d2d4", "disabled", NOW, Some(123)) - .unwrap(); - assert_eq!(attempt.expected_uci, "e2e4"); - assert_eq!(attempt.event_type, TrainingEventType::IncorrectIndependent); -} - -#[test] -fn at_06_preview_then_played_move_has_no_streak_accuracy_or_extra_preview() { - let (library, id) = library("1. e4 e5 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let mut learning = LearningData::default(); - let item = learning.ensure_item(e4.clone()); - item.introduced = true; - item.correct_streak = 2; - item.wrong_streak = 1; - item.correct_count = 4; - item.wrong_count = 1; - item.last_correct_at = Some(NOW - DAY); - item.last_review_at = Some(NOW - DAY); - item.next_review_at = Some(NOW); - item.previous_interval_seconds = Some(DAY); - let dir = TestDir::new("preview"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("preview", &library, &learning, scope); - - let preview = session.preview("preview", NOW).unwrap().unwrap(); - assert_eq!(preview.event_type, TrainingEventType::Previewed); - assert_eq!(preview.response_time_ms, None); - let previewed = commit(&store, &mut session, preview); - let after_preview = previewed.learning.item(&e4).unwrap().clone(); - assert_eq!(after_preview.next_review_at, Some(NOW + 60)); - assert_eq!(after_preview.correct_streak, 2); - assert_eq!(after_preview.wrong_streak, 1); - assert_eq!(after_preview.correct_count, 4); - assert_eq!(after_preview.wrong_count, 1); - assert_eq!(after_preview.last_correct_at, Some(NOW - DAY)); - assert!(after_preview.independent_response_times_ms.is_empty()); - assert!( - session - .preview("duplicate-hint", NOW + 1) - .unwrap() - .is_none() - ); - assert_eq!(store.load().unwrap().learning.attempts.len(), 1); - - let played = play( - &store, - &library, - &mut session, - "e2e4", - "preview-played", - NOW + 2, - Some(1_000), - ); - assert_eq!( - played.learning.attempts[1].event_type, - TrainingEventType::AutoContext - ); - assert_eq!(played.learning.attempts[1].response_time_ms, None); - assert_eq!(played.learning.item(&e4), Some(&after_preview)); - assert_eq!( - played.learning.item(&e4).unwrap().accuracy_percent(), - Some(80.0) - ); - assert_eq!(session.phase, LearningSessionPhase::Finished); -} - -#[test] -fn at_23_duplicate_does_not_move_session_or_rewrite_file() { - let (library, id) = library("1. e4 e5 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, e4.clone(), NOW); - let dir = TestDir::new("duplicate"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("duplicate", &library, &learning, scope); - store.save_session(&mut session).unwrap(); - let attempt = session - .play_uci(&library, "e2e4", "same-response", NOW, Some(100)) - .unwrap(); - let first = commit(&store, &mut session, attempt.clone()); - assert_eq!(first.application, AttemptApplication::Applied); - let bytes = std::fs::read(dir.path()).unwrap(); - #[cfg(unix)] - let inode = file_inode(&dir.path()); - - let mut duplicate_next = session.clone(); - duplicate_next.completed_keys.clear(); - duplicate_next.current_index = 99; - let duplicate = store - .apply_attempt_and_session(attempt, &mut duplicate_next) - .unwrap(); - assert_eq!(duplicate.application, AttemptApplication::Duplicate); - assert_eq!(duplicate.revision, first.revision); - assert_eq!(duplicate.session, session); - assert_eq!(duplicate.learning.attempts.len(), 1); - assert_eq!(duplicate.learning.item(&e4).unwrap().correct_count, 1); - assert_eq!(std::fs::read(dir.path()).unwrap(), bytes); - #[cfg(unix)] - assert_eq!(file_inode(&dir.path()), inode); -} - -#[cfg(unix)] -#[test] -fn attempt_and_session_replace_the_old_inode_once_with_both_changes() { - let (library, id) = library("1. e4 e5 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, e4, NOW); - let dir = TestDir::new("atomic"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("atomic", &library, &learning, scope); - store.save_session(&mut session).unwrap(); - let old_link = dir.0.join("old-inode.json"); - std::fs::hard_link(dir.path(), &old_link).unwrap(); - let old_inode = file_inode(&dir.path()); - let old_revision = store.load().unwrap().revision; - - let attempt = session - .play_uci(&library, "d2d4", "atomic-wrong", NOW, Some(100)) - .unwrap(); - let persisted = commit(&store, &mut session, attempt); - assert_eq!(persisted.revision, old_revision + 1); - assert_ne!(file_inode(&dir.path()), old_inode); - assert_eq!(file_inode(&old_link), old_inode); - - let old = LearningStore::new(&old_link).load().unwrap(); - assert!(old.learning.attempts.is_empty()); - assert_eq!( - old.session_snapshot("atomic").unwrap().phase, - LearningSessionPhase::AwaitingIndependent - ); - let new = store.load().unwrap(); - assert_eq!(new.learning.attempts.len(), 1); - assert_eq!( - new.session_snapshot("atomic").unwrap().phase, - LearningSessionPhase::AwaitingReplayAfterError - ); -} - -#[test] -fn same_session_conflict_is_explicit_and_different_sessions_keep_both_events() { - let (library, id) = library("1. e4 e5 *"); - let scope = scope(id, LearningSide::White); - let e4 = key_for(&library, &scope, "e2e4"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, e4.clone(), NOW); - let dir = TestDir::new("conflict"); - let first_store = dir.store(); - let second_store = LearningStore::new(dir.path()); - seed_store(&dir, &learning); - let original = due_session("shared-session", &library, &learning, scope.clone()); - let mut left = original.clone(); - let mut right = original; - let left_attempt = left - .play_uci(&library, "d2d4", "left", NOW, Some(100)) - .unwrap(); - let right_attempt = right - .play_uci(&library, "e2e4", "right", NOW, Some(100)) - .unwrap(); - commit(&first_store, &mut left, left_attempt); - let before_conflict = std::fs::read(dir.path()).unwrap(); - - let conflict = second_store.apply_attempt_and_session(right_attempt, &mut right); - assert!(matches!( - conflict, - Err(StoreError::SessionConflict { - expected: 0, - actual: 1, - .. - }) - )); - assert_eq!(std::fs::read(dir.path()).unwrap(), before_conflict); - assert_eq!(first_store.load().unwrap().learning.attempts.len(), 1); - - let mut restored = restore(&first_store, &library, "shared-session"); - play( - &first_store, - &library, - &mut restored, - "e2e4", - "after-reload", - NOW + 1, - None, - ); - assert_eq!(first_store.load().unwrap().learning.attempts.len(), 2); - - let mut other_a = due_session("session-a", &library, &learning, scope.clone()); - let mut other_b = due_session("session-b", &library, &learning, scope); - let a = other_a - .play_uci(&library, "e2e4", "session-a-answer", NOW, Some(100)) - .unwrap(); - let b = other_b - .play_uci(&library, "d2d4", "session-b-answer", NOW, Some(200)) - .unwrap(); - commit(&first_store, &mut other_a, a); - commit(&second_store, &mut other_b, b); - let persisted = first_store.load().unwrap(); - let shared = persisted.learning.item(&e4).unwrap(); - assert_eq!(shared.correct_count, 1); - assert_eq!(shared.wrong_count, 2); - assert!(persisted.session_snapshot("session-a").is_some()); - assert!(persisted.session_snapshot("session-b").is_some()); - assert!( - persisted - .learning - .attempts - .iter() - .any(|attempt| attempt.client_attempt_id == "session-a-answer") - ); - assert!( - persisted - .learning - .attempts - .iter() - .any(|attempt| attempt.client_attempt_id == "session-b-answer") - ); -} - -#[test] -fn snapshot_resumes_every_phase_with_deterministic_context_and_positions() { - let (library, id) = library("1. e4 e5 2. Nf3 Nc6 *"); - let scope = scope(id, LearningSide::Black); - let mut learning = LearningData::default(); - for uci in ["e7e5", "b8c6"] { - introduce_at(&mut learning, key_for(&library, &scope, uci), NOW); - } - let dir = TestDir::new("resume"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("resume", &library, &learning, scope.clone()); - - assert_eq!(session.phase, LearningSessionPhase::AdvancingContext); - store.save_session(&mut session).unwrap(); - session = restore(&store, &library, "resume"); - let presentation = session.presentation(&library).unwrap(); - assert_eq!(presentation.target_path, ["e2e4", "e7e5"]); - assert_eq!(presentation.automatic_context.len(), 1); - assert_eq!(presentation.automatic_context[0].uci, "e2e4"); - assert_eq!( - presentation.current_position.unwrap().fen4, - presentation.automatic_context[0].from.fen4 - ); - - advance(&store, &library, &mut session, "context-e4", NOW); - session = restore(&store, &library, "resume"); - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - assert_eq!( - session - .presentation(&library) - .unwrap() - .current_position - .unwrap() - .fen4, - key_for(&library, &scope, "e7e5").position_fen4 - ); - - play( - &store, - &library, - &mut session, - "e7e6", - "wrong-e6", - NOW, - Some(450), - ); - session = restore(&store, &library, "resume"); - assert_eq!( - session.phase, - LearningSessionPhase::AwaitingReplayAfterError - ); - assert_eq!( - session - .presentation(&library) - .unwrap() - .revealed_move - .as_deref(), - Some("e7e5") - ); - - play( - &store, - &library, - &mut session, - "e7e5", - "replay-e5", - NOW + 1, - Some(999), - ); - session = restore(&store, &library, "resume"); - assert_eq!(session.phase, LearningSessionPhase::AdvancingContext); - assert_eq!(session.current_target().unwrap().key.expected_uci, "b8c6"); - assert_eq!( - session - .presentation(&library) - .unwrap() - .automatic_context - .len(), - 3 - ); - - for (index, uci) in ["e2e4", "e7e5", "g1f3"].into_iter().enumerate() { - advance( - &store, - &library, - &mut session, - &format!("next-context-{index}"), - NOW + 2, - ); - session = restore(&store, &library, "resume"); - if index < 2 { - assert_eq!(session.phase, LearningSessionPhase::AdvancingContext); - } - assert_eq!(session.current_target().unwrap().path[index], uci); - } - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - - let preview = session.preview("preview-nc6", NOW + 3).unwrap().unwrap(); - commit(&store, &mut session, preview); - session = restore(&store, &library, "resume"); - assert_eq!(session.phase, LearningSessionPhase::PreviewedReplay); - assert_eq!( - session - .presentation(&library) - .unwrap() - .revealed_move - .as_deref(), - Some("b8c6") - ); - - play( - &store, - &library, - &mut session, - "b8c6", - "played-preview-nc6", - NOW + 4, - Some(888), - ); - session = restore(&store, &library, "resume"); - assert_eq!(session.phase, LearningSessionPhase::Finished); - assert_eq!(session.completed_keys.len(), 2); - assert!( - session - .presentation(&library) - .unwrap() - .current_position - .is_none() - ); - - let data = store.load().unwrap(); - let e5 = data - .learning - .item(&key_for(&library, &scope, "e7e5")) - .unwrap(); - assert_eq!(e5.independent_response_times_ms, [450]); - let nc6 = data - .learning - .item(&key_for(&library, &scope, "b8c6")) - .unwrap(); - assert!(nc6.independent_response_times_ms.is_empty()); - assert!(data.learning.attempts.iter().all(|attempt| { - attempt.event_type.is_independent() || attempt.response_time_ms.is_none() - })); -} - -#[test] -fn both_and_legacy_queue_modes_are_rejected_on_resume() { - let (library, id) = library("1. e4 *"); - let selected = scope(id, LearningSide::White); - let mut session = due_session("invalid", &library, &LearningData::default(), selected); - session.session.side = TrainingMode::Both; - assert!(matches!( - session.clone().resume(&library), - Err(LearningSessionError::SessionSideMismatch) - )); - session.session.side = TrainingMode::White; - session.session.mode = QueueMode::Practice; - assert!(matches!( - session.resume(&library), - Err(LearningSessionError::UnsupportedMode(QueueMode::Practice)) - )); -} - -#[test] -fn transposition_target_replays_its_saved_membership_path_after_reload() { - let (library, id) = - library("1. e4 d5 (1... Nf6 2. d4 d5) 2. d4 Nh6 3. Nf3 Ng8 4. Ng1 Nf6 5. c4 *"); - let scope = scope(id, LearningSide::White); - let c4 = key_for(&library, &scope, "c2c4"); - let mut learning = LearningData::default(); - introduce_at(&mut learning, c4.clone(), NOW); - let dir = TestDir::new("transposition"); - let store = dir.store(); - seed_store(&dir, &learning); - let mut session = due_session("transposition", &library, &learning, scope); - assert_eq!( - session.current_target().unwrap().path, - [ - "e2e4", "d7d5", "d2d4", "g8h6", "g1f3", "h6g8", "f3g1", "g8f6", "c2c4" - ] - ); - store.save_session(&mut session).unwrap(); - session = restore(&store, &library, "transposition"); - assert_eq!( - session - .presentation(&library) - .unwrap() - .automatic_context - .len(), - 8 - ); - - for index in 0..8 { - advance( - &store, - &library, - &mut session, - &format!("transposition-context-{index}"), - NOW, - ); - } - session = restore(&store, &library, "transposition"); - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - assert_eq!( - session - .presentation(&library) - .unwrap() - .current_position - .unwrap() - .fen4, - c4.position_fen4 - ); - play( - &store, - &library, - &mut session, - "c2c4", - "transposition-answer", - NOW, - Some(100), - ); - assert_eq!(session.phase, LearningSessionPhase::Finished); -} - -#[test] -fn learnt_counter_tracks_persisted_independent_answers_for_both_sides_and_shared_scopes() { - for side in [LearningSide::White, LearningSide::Black] { - let (mut library, first) = library("1. e4 e5 *"); - let second = library - .create( - "Shared continuation", - &chess_core::parse_str("1. e4 e5 2. Nf3 *").game, - ) - .unwrap(); - let expected = if side == LearningSide::White { - "e2e4" - } else { - "e7e5" - }; - let wrong = if side == LearningSide::White { - "d2d4" - } else { - "c7c5" - }; - let key = key_for(&library, &scope(first.clone(), side), expected); - let dir = TestDir::new("learnt-counter-lifecycle"); - let store = dir.store(); - let mut at = NOW; - for (cycle, action) in ["correct", "correct", "preview", "correct", "wrong"] - .into_iter() - .enumerate() - { - let learning = store.load().unwrap().learning; - let mut selected = scope(first.clone(), side); - selected.as_of = at; - let mut session = due_session( - &format!("counter-{cycle}"), - &library, - &learning, - selected.clone(), - ); - if cycle == 0 { - assert_eq!(session.introduce_new(&library, &learning).unwrap(), 1); - } - while session.phase == LearningSessionPhase::AdvancingContext { - let event_id = format!("counter-{cycle}-auto-{}", session.context_index); - advance(&store, &library, &mut session, &event_id, at); - } - assert_eq!(session.phase, LearningSessionPhase::AwaitingIndependent); - if action == "preview" { - let preview = session - .preview(format!("counter-{cycle}-preview"), at) - .unwrap() - .unwrap(); - commit(&store, &mut session, preview); - } - let played = if action == "wrong" { wrong } else { expected }; - let attempt = session - .play_uci( - &library, - played, - format!("counter-{cycle}-answer"), - at, - Some(100), - ) - .unwrap(); - let result = commit(&store, &mut session, attempt.clone()); - let duplicate = commit(&store, &mut session, attempt); - assert_eq!(duplicate.application, AttemptApplication::Duplicate); - assert_eq!(duplicate.learning, result.learning); - if action == "wrong" { - play( - &store, - &library, - &mut session, - expected, - "counter-replay", - at, - None, - ); - } - // Reload exactly what the UI uses after leaving a training session. - let learning = store.load().unwrap().learning; - let expected_streak = [1, 2, 2, 3, 0][cycle]; - let learnt = usize::from(expected_streak >= 3); - assert_eq!(learning.item(&key).unwrap().correct_streak, expected_streak); - let first_summary = - aggregate_scope(&library, &learning, &selected, &SrsSettings::default()) - .unwrap() - .summary; - assert_eq!((first_summary.learnt, first_summary.total), (learnt, 1)); - let shared_scope = StatsScope::new([first.clone(), second.clone()], side, at); - let shared = - aggregate_scope(&library, &learning, &shared_scope, &SrsSettings::default()) - .unwrap() - .summary; - let expected_total = if side == LearningSide::White { 2 } else { 1 }; - assert_eq!((shared.learnt, shared.total), (learnt, expected_total)); - let second_summary = aggregate_scope( - &library, - &learning, - &scope(second.clone(), side), - &SrsSettings::default(), - ) - .unwrap() - .summary; - assert_eq!(second_summary.learnt, learnt); - assert_eq!( - first_summary.total, - first_summary.unseen + first_summary.learning + first_summary.learnt - ); - assert_eq!(first_summary.accuracy_correct, [1, 2, 2, 3, 3][cycle]); - assert_eq!(first_summary.accuracy_wrong, u64::from(action == "wrong")); - at = learning.item(&key).unwrap().next_review_at.unwrap(); - } - } -} - -#[test] -fn runtime_replay_cache_is_shared_but_never_persisted_or_stale_after_source_changes() { - let (mut library, id) = library("1. e4 e5 2. Nf3 Nc6 3. Bb5 *"); - let selected = scope(id.clone(), LearningSide::White); - let mut learning = LearningData::default(); - introduce_at(&mut learning, key_for(&library, &selected, "f1b5"), NOW); - let mut session = due_session("runtime-cache", &library, &learning, selected); - let initial = session - .presentation_with_learning(&library, &learning) - .unwrap(); - let (parses, replays, _) = session.runtime_work_counts(); - assert_eq!((parses, replays), (1, 1)); - let mut clone = session.clone(); - for _ in 0..8 { - assert_eq!( - clone - .presentation_with_learning(&library, &learning) - .unwrap(), - initial - ); - } - assert_eq!(clone.runtime_work_counts().0, 1); - assert_eq!(clone.runtime_work_counts().1, 1); - let json = serde_json::to_value(&session).unwrap(); - assert!(json.get("runtime").is_none()); - let mut restored: LearningSessionSnapshot = serde_json::from_value(json).unwrap(); - assert_eq!(restored, session); - assert_eq!(restored.runtime_work_counts(), (0, 0, 0)); - assert_eq!( - restored - .presentation_with_learning(&library, &learning) - .unwrap(), - initial - ); - assert_eq!(restored.runtime_work_counts().0, 1); - - // Public PGN can change without a revision API. Compare exact source bytes; - // a shared clone must not retain old positions after a source edit. - let old_library = library.clone(); - library - .repertoire_mut(&id) - .unwrap() - .pgn - .push_str(" {edited}"); - assert_eq!( - clone - .presentation_with_learning(&library, &learning) - .unwrap(), - initial - ); - assert_eq!(session.runtime_work_counts().0, 2); - assert_eq!( - session - .presentation_with_learning(&old_library, &learning) - .unwrap(), - initial - ); - assert_eq!(session.runtime_work_counts().0, 3); - library.repertoire_mut(&id).unwrap().pgn = - "[SetUp \"1\"]\n[FEN \"rnbqkbnr/pppppppp/8/8/8/8/PPPP1PPP/RNBQKBNR w KQkq - 0 1\"]\n\n*" - .into(); - assert!(matches!( - clone.presentation_with_learning(&library, &learning), - Err(LearningSessionError::InvalidTargetPath { .. }) - )); - assert_eq!(clone.runtime_work_counts().0, 4); - assert_eq!( - session - .presentation_with_learning(&old_library, &learning) - .unwrap(), - initial - ); -} - -#[test] -fn context_presentation_plans_once_per_call_instead_of_once_per_prefix_move() { - // A long legal path with repeated positions; the saved PGN occurrence must - // retain its full history, while planning work stays constant per call. - let pgn = format!("{} e4 *", "Nf3 Nf6 Ng1 Ng8 ".repeat(64)); - let (library, id) = library(&pgn); - let selected = scope(id, LearningSide::White); - let mut learning = LearningData::default(); - introduce_at(&mut learning, key_for(&library, &selected, "e2e4"), NOW); - let mut session = due_session("linear-context-plan", &library, &learning, selected); - assert_eq!(session.current_target().unwrap().path.len(), 257); - let before = session.runtime_work_counts(); - let presentation = session - .presentation_with_learning(&library, &learning) - .unwrap(); - assert_eq!(presentation.automatic_context.len(), 256); - let after = session.runtime_work_counts(); - assert_eq!((after.0, after.1), (before.0, before.1)); - // One phase synchronisation plus one presentation, independent of path length. - assert_eq!(after.2 - before.2, 2); - let mut clone = session.clone(); - for index in 0..8 { - let attempt = clone - .advance_context_with_learning( - &library, - &learning, - format!("cached-context-{index}"), - NOW, - ) - .unwrap(); - assert_eq!(attempt.event_type, TrainingEventType::AutoContext); - } - assert_eq!(clone.context_index, 8); - assert_eq!(clone.runtime_work_counts().0, 1); - assert_eq!(clone.runtime_work_counts().1, 1); - // Policy remains live; no cached plan may hide a newly required question. - clone.context_policy.consider_leadup_moves = true; - assert_eq!( - clone - .presentation_with_learning(&library, &learning) - .unwrap() - .phase, - LearningSessionPhase::AwaitingContextIndependent - ); -} diff --git a/crates/trainer/src/repertoire/srs.rs b/crates/trainer/src/repertoire/srs.rs deleted file mode 100644 index 71c7668..0000000 --- a/crates/trainer/src/repertoire/srs.rs +++ /dev/null @@ -1,199 +0,0 @@ -use serde::{Deserialize, Serialize}; - -use super::learning::{ - AttemptApplication, IndependentResult, LearningData, LearningError, LearningItem, - LearningItemKey, TrainingAttempt, TrainingEventType, WrongMoveStats, -}; - -pub const DEFAULT_GROWTH_FACTOR: f64 = 2.0; -pub const FIRST_CORRECT_DELAY_SECONDS: i64 = 24 * 60 * 60; -pub const MISTAKE_DELAY_SECONDS: i64 = 30; -pub const PREVIEW_DELAY_SECONDS: i64 = 60; -pub const SRS_MAX_INTERVAL_SECONDS: i64 = 1095 * 24 * 60 * 60; -pub const MIN_PRACTICAL_INTERVAL_SECONDS: i64 = 1; -pub const UNCERTAIN_MIN_GRACE_SECONDS: i64 = 7 * 24 * 60 * 60; -pub const UNCERTAIN_INTERVAL_DIVISOR: u32 = 4; - -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] -#[serde(default)] -pub struct SrsSettings { - pub growth_factor: f64, - pub first_correct_delay_seconds: i64, - pub mistake_delay_seconds: i64, - pub preview_delay_seconds: i64, - pub max_interval_seconds: i64, - /// Project-specific lower bound for elapsed-time growth, not a ChessTempo default. - pub min_practical_interval_seconds: i64, - pub uncertain_min_grace_seconds: i64, - pub uncertain_interval_divisor: u32, -} - -impl Default for SrsSettings { - fn default() -> Self { - Self { - growth_factor: DEFAULT_GROWTH_FACTOR, - first_correct_delay_seconds: FIRST_CORRECT_DELAY_SECONDS, - mistake_delay_seconds: MISTAKE_DELAY_SECONDS, - preview_delay_seconds: PREVIEW_DELAY_SECONDS, - max_interval_seconds: SRS_MAX_INTERVAL_SECONDS, - min_practical_interval_seconds: MIN_PRACTICAL_INTERVAL_SECONDS, - uncertain_min_grace_seconds: UNCERTAIN_MIN_GRACE_SECONDS, - uncertain_interval_divisor: UNCERTAIN_INTERVAL_DIVISOR, - } - } -} - -pub fn apply_independent_correct(item: &mut LearningItem, now: i64, settings: &SrsSettings) { - let delay = match (item.correct_streak, item.last_correct_at) { - (0, _) | (_, None) => settings.first_correct_delay_seconds.max(0), - (_, Some(last_correct_at)) => growth_delay(now.saturating_sub(last_correct_at), settings), - }; - - item.introduced = true; - item.correct_streak = item.correct_streak.saturating_add(1); - item.wrong_streak = 0; - item.correct_count = item.correct_count.saturating_add(1); - item.last_correct_at = Some(now); - item.last_review_at = Some(now); - item.previous_interval_seconds = Some(delay); - item.next_review_at = Some(now.saturating_add(delay)); - item.record_independent_outcome(IndependentResult::Correct, now); -} - -pub fn apply_independent_wrong( - item: &mut LearningItem, - played_move: &str, - now: i64, - settings: &SrsSettings, -) { - item.introduced = true; - item.correct_streak = 0; - item.wrong_streak = item.wrong_streak.saturating_add(1); - item.wrong_count = item.wrong_count.saturating_add(1); - item.last_correct_at = None; - item.last_review_at = Some(now); - item.next_review_at = Some(now.saturating_add(settings.mistake_delay_seconds.max(0))); - item.last_wrong_move_uci = Some(played_move.to_owned()); - item.last_wrong_at = Some(now); - let wrong = item - .wrong_move_histogram - .entry(played_move.to_owned()) - .or_insert(WrongMoveStats { - count: 0, - last_at: now, - }); - wrong.count = wrong.count.saturating_add(1); - wrong.last_at = now; - item.record_independent_outcome(IndependentResult::Wrong, now); -} - -/// Preview preserves streaks, independent counters and the last correct answer. -pub fn apply_preview(item: &mut LearningItem, now: i64, settings: &SrsSettings) { - item.introduced = true; - item.last_review_at = Some(now); - item.next_review_at = Some(now.saturating_add(settings.preview_delay_seconds.max(0))); -} - -pub fn apply_attempt( - item: &mut LearningItem, - attempt: &TrainingAttempt, - settings: &SrsSettings, -) -> Result<(), LearningError> { - validate_attempt(&item.key, attempt)?; - apply_validated_attempt(item, attempt, settings); - Ok(()) -} - -impl LearningData { - /// Applies and journals an event once per `(user_id, client_attempt_id)`. - pub fn apply_attempt( - &mut self, - attempt: TrainingAttempt, - settings: &SrsSettings, - ) -> Result { - if attempt.client_attempt_id.is_empty() { - return Err(LearningError::EmptyClientAttemptId); - } - if self.attempts.iter().any(|existing| { - existing.user_id == attempt.user_id - && existing.client_attempt_id == attempt.client_attempt_id - }) { - return Ok(AttemptApplication::Duplicate); - } - - let key = attempt.item_key(); - validate_attempt(&key, &attempt)?; - let item = self.ensure_item(key); - apply_validated_attempt(item, &attempt, settings); - self.attempts.push(attempt); - Ok(AttemptApplication::Applied) - } -} - -fn growth_delay(elapsed_seconds: i64, settings: &SrsSettings) -> i64 { - let min = settings.min_practical_interval_seconds.max(0); - let max = settings.max_interval_seconds.max(min); - let growth = if settings.growth_factor.is_finite() { - settings.growth_factor.max(0.0) - } else { - 0.0 - }; - let scaled = elapsed_seconds.max(0) as f64 * growth; - if scaled >= max as f64 { - max - } else if scaled <= min as f64 { - min - } else { - scaled as i64 - } -} - -fn validate_attempt(key: &LearningItemKey, attempt: &TrainingAttempt) -> Result<(), LearningError> { - if attempt.client_attempt_id.is_empty() { - return Err(LearningError::EmptyClientAttemptId); - } - if key != &attempt.item_key() { - return Err(LearningError::WrongLearningItem); - } - if attempt.event_type == TrainingEventType::IncorrectIndependent - && attempt - .actual_uci - .as_deref() - .is_none_or(|actual| actual.is_empty()) - { - return Err(LearningError::MissingActualMove); - } - Ok(()) -} - -fn apply_validated_attempt( - item: &mut LearningItem, - attempt: &TrainingAttempt, - settings: &SrsSettings, -) { - match attempt.event_type { - TrainingEventType::CorrectIndependent => { - apply_independent_correct(item, attempt.happened_at, settings); - } - TrainingEventType::IncorrectIndependent => { - apply_independent_wrong( - item, - attempt.actual_uci.as_deref().unwrap_or_default(), - attempt.happened_at, - settings, - ); - } - TrainingEventType::Previewed => { - apply_preview(item, attempt.happened_at, settings); - } - TrainingEventType::ReplayAfterError - | TrainingEventType::AutoContext - | TrainingEventType::IllegalMove => return, - } - - if attempt.event_type.is_independent() - && let Some(response_time_ms) = attempt.response_time_ms - { - item.independent_response_times_ms.push(response_time_ms); - } -} diff --git a/crates/trainer/src/repertoire/stats.rs b/crates/trainer/src/repertoire/stats.rs deleted file mode 100644 index 68ca588..0000000 --- a/crates/trainer/src/repertoire/stats.rs +++ /dev/null @@ -1,275 +0,0 @@ -use chess_core::shakmaty::Color; -use serde::{Deserialize, Serialize}; - -use super::model::RepertoireId; -use super::scope::TrainingScopeKey; - -pub const STATS_VERSION: u32 = 2; -/// Recent attempts kept per move in a v2 file. -const RECENT: usize = 10; - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub enum TrainingMode { - White, - Black, - Both, -} - -impl TrainingMode { - pub fn user_color(self) -> Option { - match self { - Self::White => Some(Color::White), - Self::Black => Some(Color::Black), - Self::Both => None, - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub enum QueueMode { - Practice, - SpacedRepetition, - ReviewInOrder, - LeastRecent, -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct MoveKey { - pub repertoire_id: RepertoireId, - pub mode: TrainingMode, - pub position_fen4: String, - pub expected_uci: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct AttemptRecord { - pub at: i64, - pub correct: bool, - pub hinted: bool, - /// The actual legal input, including a wrong move outside the repertoire. - pub actual_uci: String, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct MoveStats { - pub key: MoveKey, - pub attempts: u32, - pub correct: u32, - pub wrong: u32, - pub hints: u32, - /// Positive: clean correct answers in a row. Negative: wrong answers in a row. - pub streak: i32, - pub recent: Vec, - pub last_attempt: Option, - pub last_seen: Option, - pub due: Option, - /// Scheduled interval, independent of observations during non-scheduling reviews. - pub interval_seconds: Option, -} - -impl Default for MoveStats { - fn default() -> Self { - Self { - key: MoveKey { - repertoire_id: RepertoireId::legacy(""), - mode: TrainingMode::Both, - position_fen4: String::new(), - expected_uci: String::new(), - }, - attempts: 0, - correct: 0, - wrong: 0, - hints: 0, - streak: 0, - recent: Vec::new(), - last_attempt: None, - last_seen: None, - due: None, - interval_seconds: None, - } - } -} - -#[cfg(test)] -impl MoveStats { - pub fn new(key: MoveKey) -> Self { - Self { - key, - ..Self::default() - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct RunRecord { - pub at: i64, - pub mistakes: u32, - pub hints: u32, - pub hinted: bool, - pub path: Vec, - pub user_attempts: u32, - pub automatic_moves: u32, - #[serde(default)] - pub scope: TrainingScopeKey, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default)] -pub struct RunStats { - pub repertoire_id: RepertoireId, - pub mode: TrainingMode, - pub completions: u32, - pub last: Option, - pub recent: Vec, -} - -impl Default for RunStats { - fn default() -> Self { - Self { - repertoire_id: RepertoireId::legacy(""), - mode: TrainingMode::Both, - completions: 0, - last: None, - recent: Vec::new(), - } - } -} - -#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] -pub struct PathKey { - pub repertoire_id: RepertoireId, - pub scope: TrainingScopeKey, - pub path: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -pub struct PathStats { - pub key: PathKey, - pub completions: u32, - pub mistakes: u32, - pub hints: u32, - pub last_seen: Option, - pub last_completion: Option, - pub recent: Vec, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct ReviewCursor { - repertoire_id: RepertoireId, - mode: TrainingMode, - #[serde(default)] - scope: TrainingScopeKey, - next: usize, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct PathReviewCursor { - repertoire_id: RepertoireId, - scope: TrainingScopeKey, - next: usize, -} - -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -struct RandomPracticeCursor { - repertoire_id: RepertoireId, - mode: TrainingMode, - scope: TrainingScopeKey, - seed: u64, - position: usize, - count: usize, - #[serde(default)] - fingerprint: Option, -} - -#[derive(Clone, Debug, Serialize, Deserialize)] -#[serde(default)] -pub struct StatsData { - pub version: u32, - pub revision: u64, - /// Original legacy values, retained verbatim. They are not per-move attempts. - pub legacy_lines: serde_json::Map, - pub move_stats: Vec, - pub runs: Vec, - pub path_stats: Vec, - review_cursors: Vec, - path_review_cursors: Vec, - practice_path_cursors: Vec, - random_practice_cursors: Vec, -} - -impl Default for StatsData { - fn default() -> Self { - Self { - version: STATS_VERSION, - revision: 0, - legacy_lines: serde_json::Map::new(), - move_stats: Vec::new(), - runs: Vec::new(), - path_stats: Vec::new(), - review_cursors: Vec::new(), - path_review_cursors: Vec::new(), - practice_path_cursors: Vec::new(), - random_practice_cursors: Vec::new(), - } - } -} - -impl StatsData { - pub(crate) fn migrate_position_stats(&mut self) { - let mut merged: Vec = Vec::new(); - for mut entry in self.move_stats.drain(..) { - if entry.key.mode != TrainingMode::Both { - if entry.interval_seconds.is_none() { - entry.interval_seconds = match (entry.due, entry.last_seen) { - (Some(due), Some(last)) if due > last => Some(due.saturating_sub(last)), - _ => None, - }; - } - merged.push(entry); - continue; - } - entry.key.expected_uci.clear(); - entry.due = None; - entry.interval_seconds = None; - if let Some(old) = merged.iter_mut().find(|old| old.key == entry.key) { - old.attempts = old.attempts.saturating_add(entry.attempts); - old.correct = old.correct.saturating_add(entry.correct); - old.wrong = old.wrong.saturating_add(entry.wrong); - old.hints = old.hints.saturating_add(entry.hints); - if entry.last_attempt > old.last_attempt { - old.streak = entry.streak; - } - old.last_attempt = old.last_attempt.max(entry.last_attempt); - old.last_seen = old.last_seen.max(entry.last_seen); - old.recent.extend(entry.recent); - old.recent.sort_by_key(|attempt| attempt.at); - if old.recent.len() > RECENT { - old.recent.drain(..old.recent.len() - RECENT); - } - } else { - merged.push(entry); - } - } - self.move_stats = merged; - } - - pub(crate) fn normalize(&mut self) { - self.move_stats.sort_by(|a, b| a.key.cmp(&b.key)); - self.move_stats.dedup_by(|a, b| a.key == b.key); - self.runs - .sort_by(|a, b| (&a.repertoire_id, &a.mode).cmp(&(&b.repertoire_id, &b.mode))); - self.path_stats.sort_by(|a, b| a.key.cmp(&b.key)); - self.review_cursors.sort_by(|a, b| { - (&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope)) - }); - self.practice_path_cursors.sort_by(|a, b| { - (&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope)) - }); - self.random_practice_cursors.sort_by(|a, b| { - (&a.repertoire_id, &a.mode, &a.scope).cmp(&(&b.repertoire_id, &b.mode, &b.scope)) - }); - self.path_review_cursors - .sort_by(|a, b| (&a.repertoire_id, &a.scope).cmp(&(&b.repertoire_id, &b.scope))); - } -} diff --git a/crates/trainer/src/repertoire/store.rs b/crates/trainer/src/repertoire/store.rs deleted file mode 100644 index 35028b6..0000000 --- a/crates/trainer/src/repertoire/store.rs +++ /dev/null @@ -1,1136 +0,0 @@ -use std::collections::{BTreeSet, HashMap}; -use std::io; -use std::path::{Path, PathBuf}; - -use chess_core::pgn::store::write_atomic; -use serde::de::DeserializeOwned; -use serde::{Deserialize, Serialize}; - -use super::learning::{ - AttemptApplication, LearningData, LearningError, LearningItem, LearningItemKey, TrainingAttempt, -}; -use super::learning_analytics::{LearningSnapshot, LocalDatePolicy, same_snapshot_slot}; -use super::learning_graph::{LearningGraphError, StatsScope}; -use super::learning_session::{LearningSessionError, LearningSessionSnapshot}; -use super::model::{LIBRARY_VERSION, Library, RepertoireError}; -use super::scope::TrainingScopeKey; -use super::srs::SrsSettings; -use super::stats::{QueueMode, STATS_VERSION, StatsData, TrainingMode}; - -#[path = "migration.rs"] -mod migration; -pub use migration::MigrationReport; - -#[derive(Debug)] -pub enum StoreError { - Io { - path: PathBuf, - source: io::Error, - }, - Json { - path: PathBuf, - source: serde_json::Error, - }, - UnsupportedVersion { - kind: &'static str, - version: u32, - path: PathBuf, - }, - MissingVersion { - kind: &'static str, - path: PathBuf, - }, - DuplicateStats(PathBuf), - Conflict { - path: PathBuf, - expected: u64, - actual: u64, - }, - LegacyPath(PathBuf), - SessionConflict { - session_id: String, - expected: u64, - actual: u64, - }, - SessionMismatch { - attempt_session_id: String, - session_id: String, - }, - Repertoire(RepertoireError), - Learning(LearningError), - LearningGraph(LearningGraphError), - Session(LearningSessionError), -} - -impl std::fmt::Display for StoreError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Io { path, source } => write!(f, "I/O error at {}: {source}", path.display()), - Self::Json { path, source } => { - write!(f, "invalid JSON at {}: {source}", path.display()) - } - Self::UnsupportedVersion { - kind, - version, - path, - } => write!( - f, - "unsupported {kind} schema version {version} at {}", - path.display() - ), - Self::MissingVersion { kind, path } => { - write!(f, "{kind} at {} has no schema version", path.display()) - } - Self::DuplicateStats(path) => { - write!(f, "duplicate training keys in {}", path.display()) - } - Self::Conflict { - path, - expected, - actual, - } => write!( - f, - "concurrent modification of {}: loaded revision {expected}, disk revision {actual}; reload and retry", - path.display() - ), - Self::LegacyPath(path) => write!( - f, - "legacy training file must be different from the new statistics file: {}", - path.display() - ), - Self::SessionConflict { - session_id, - expected, - actual, - } => write!( - f, - "concurrent modification of learning session {session_id}: loaded revision {expected}, disk revision {actual}; reload and retry" - ), - Self::SessionMismatch { - attempt_session_id, - session_id, - } => write!( - f, - "training attempt belongs to session {attempt_session_id}, not {session_id}" - ), - Self::Repertoire(error) => error.fmt(f), - Self::Learning(error) => write!(f, "cannot apply training attempt: {error}"), - Self::LearningGraph(error) => write!(f, "cannot capture learning statistics: {error}"), - Self::Session(error) => write!(f, "invalid learning session: {error}"), - } - } -} - -impl std::error::Error for StoreError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Io { source, .. } => Some(source), - Self::Json { source, .. } => Some(source), - Self::Repertoire(error) => Some(error), - Self::Learning(error) => Some(error), - Self::LearningGraph(error) => Some(error), - Self::Session(error) => Some(error), - _ => None, - } - } -} - -impl From for StoreError { - fn from(error: RepertoireError) -> Self { - Self::Repertoire(error) - } -} - -impl From for StoreError { - fn from(error: LearningError) -> Self { - Self::Learning(error) - } -} - -impl From for StoreError { - fn from(error: LearningGraphError) -> Self { - Self::LearningGraph(error) - } -} - -impl From for StoreError { - fn from(error: LearningSessionError) -> Self { - Self::Session(error) - } -} - -fn io(path: &Path, source: io::Error) -> StoreError { - StoreError::Io { - path: path.to_owned(), - source, - } -} - -fn json(path: &Path, source: serde_json::Error) -> StoreError { - StoreError::Json { - path: path.to_owned(), - source, - } -} - -// Lock a stable sidecar: the data file itself is replaced by atomic rename. Keeping -// the lock file avoids unlink/open races and the OS releases its lock after a crash. -fn lock_store(path: &Path) -> Result { - let target = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned()); - if let Some(parent) = target.parent().filter(|p| !p.as_os_str().is_empty()) { - std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?; - } - let mut lock_name = target.file_name().unwrap_or_default().to_os_string(); - lock_name.push(".lock"); - let lock_path = target.with_file_name(lock_name); - let lock = std::fs::OpenOptions::new() - .create(true) - .truncate(false) - .write(true) - .read(true) - .open(&lock_path) - .map_err(|e| io(&lock_path, e))?; - lock.lock().map_err(|e| io(&lock_path, e))?; - Ok(lock) -} - -fn read_optional(path: &Path) -> Result>, StoreError> { - match std::fs::read(path) { - Ok(bytes) => Ok(Some(bytes)), - Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), - Err(error) => Err(io(path, error)), - } -} - -fn decode_versioned( - path: &Path, - bytes: &[u8], - kind: &'static str, - supported: u32, -) -> Result { - let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| json(path, e))?; - let version = value - .get("version") - .and_then(serde_json::Value::as_u64) - .ok_or_else(|| StoreError::MissingVersion { - kind, - path: path.to_owned(), - })?; - let version = u32::try_from(version).unwrap_or(u32::MAX); - if version != supported { - return Err(StoreError::UnsupportedVersion { - kind, - version, - path: path.to_owned(), - }); - } - serde_json::from_value(value).map_err(|e| json(path, e)) -} - -#[derive(Clone, Debug)] -pub struct LibraryStore { - path: PathBuf, -} - -impl LibraryStore { - pub fn new(path: impl Into) -> Self { - Self { path: path.into() } - } - - pub fn path(&self) -> &Path { - &self.path - } - - /// A missing new library is empty. Existing unreadable or unsupported data is an - /// error, never silently replaced by an empty library. - pub fn load(&self) -> Result { - let Some(bytes) = read_optional(&self.path)? else { - return Ok(Library::default()); - }; - let library: Library = - decode_versioned(&self.path, &bytes, "repertoire library", LIBRARY_VERSION)?; - library.validate()?; - Ok(library) - } - - /// Optimistic concurrency: a stale in-memory snapshot is rejected rather than - /// overwriting another process's additions. The caller reloads and reapplies its edit. - pub fn save(&self, library: &mut Library) -> Result<(), StoreError> { - library.validate()?; - let _lock = lock_store(&self.path)?; - let current = self.load()?; - if current.revision != library.revision { - return Err(StoreError::Conflict { - path: self.path.clone(), - expected: library.revision, - actual: current.revision, - }); - } - let previous = library.revision; - library.version = LIBRARY_VERSION; - library.revision = current.revision.saturating_add(1); - let bytes = serde_json::to_vec_pretty(library).map_err(|e| json(&self.path, e))?; - if let Err(error) = write_atomic(&self.path, &bytes) { - library.revision = previous; - return Err(io(&self.path, error)); - } - Ok(()) - } -} - -#[allow(dead_code)] -pub const LEARNING_STORE_VERSION: u32 = 3; - -#[allow(dead_code)] -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct LearningSession { - pub id: String, - pub mode: QueueMode, - pub side: TrainingMode, - pub scope: TrainingScopeKey, - pub settings: SrsSettings, -} - -#[allow(dead_code)] -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct LearningStoreData { - pub version: u32, - #[serde(default)] - pub revision: u64, - pub learning: LearningData, - #[serde(default)] - pub sessions: Vec, - #[serde(default)] - pub session_snapshots: Vec, - #[serde(default)] - pub snapshots: Vec, - /// Original v2 JSON, including unknown root and nested extension fields. - #[serde(default)] - pub legacy_practice: Option, - #[serde(flatten)] - pub extensions: std::collections::BTreeMap, -} - -impl Default for LearningStoreData { - fn default() -> Self { - Self { - version: LEARNING_STORE_VERSION, - revision: 0, - learning: LearningData::default(), - sessions: Vec::new(), - session_snapshots: Vec::new(), - snapshots: Vec::new(), - legacy_practice: None, - extensions: std::collections::BTreeMap::new(), - } - } -} - -impl LearningStoreData { - pub fn session_snapshot(&self, id: &str) -> Option<&LearningSessionSnapshot> { - self.session_snapshots - .iter() - .find(|snapshot| snapshot.id() == id) - } -} - -#[allow(dead_code)] -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PersistedAttempt { - pub application: AttemptApplication, - pub revision: u64, - pub learning: LearningData, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PersistedLearningReset { - pub revision: u64, - pub learning: LearningData, - pub reset_count: usize, -} - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct PersistedLearningSnapshot { - pub snapshot: LearningSnapshot, - pub revision: u64, - pub recorded: bool, -} - -#[derive(Clone, Debug, PartialEq)] -pub struct PersistedSessionAttempt { - pub application: AttemptApplication, - pub revision: u64, - pub learning: LearningData, - pub session: LearningSessionSnapshot, -} - -#[allow(dead_code)] -#[derive(Clone, Debug)] -pub struct LearningStore { - path: PathBuf, - legacy_path: Option, -} - -#[allow(dead_code)] -#[derive(Clone, Debug)] -enum LearningSource { - Missing, - V2(Vec), - V3(serde_json::Value), - LegacyLines, -} - -#[allow(dead_code)] -#[derive(Clone, Debug)] -struct LoadedLearning { - data: LearningStoreData, - report: MigrationReport, - source: LearningSource, -} - -#[allow(dead_code)] -impl LearningStore { - pub fn new(path: impl Into) -> Self { - Self { - path: path.into(), - legacy_path: None, - } - } - - /// The legacy line file is read only. All v3 writes target `path`. - pub fn with_legacy(path: impl Into, legacy_path: impl Into) -> Self { - Self { - path: path.into(), - legacy_path: Some(legacy_path.into()), - } - } - - pub fn path(&self) -> &Path { - &self.path - } - - pub fn legacy_path(&self) -> Option<&Path> { - self.legacy_path.as_deref() - } - - pub fn load(&self) -> Result { - self.load_with_report().map(|(data, _)| data) - } - - pub fn load_with_report(&self) -> Result<(LearningStoreData, MigrationReport), StoreError> { - let loaded = self.load_latest()?; - Ok((loaded.data, loaded.report)) - } - - /// Writes an existing v2 or legacy-line source as v3. An already current or missing - /// store is left untouched, which makes repeated migration idempotent. - pub fn migrate(&self) -> Result { - self.check_legacy_path()?; - let _lock = lock_store(&self.path)?; - let mut loaded = self.load_latest()?; - if matches!( - loaded.source, - LearningSource::Missing | LearningSource::V3(_) - ) { - return Ok(loaded.report); - } - let report = loaded.report; - self.write_latest(&mut loaded)?; - Ok(report) - } - - /// Reloads under the cross-process lock, then persists the event and its learning - /// effect in one atomic replacement. Duplicate delivery never rewrites the file. - pub fn apply_attempt( - &self, - attempt: TrainingAttempt, - settings: &SrsSettings, - ) -> Result { - self.check_legacy_path()?; - let _lock = lock_store(&self.path)?; - let mut loaded = self.load_latest()?; - let application = loaded.data.learning.apply_attempt(attempt, settings)?; - if application == AttemptApplication::Duplicate { - return Ok(PersistedAttempt { - application, - revision: loaded.data.revision, - learning: loaded.data.learning, - }); - } - self.write_latest(&mut loaded)?; - Ok(PersistedAttempt { - application, - revision: loaded.data.revision, - learning: loaded.data.learning, - }) - } - - pub fn record_snapshot( - &self, - library: &Library, - scope: &StatsScope, - settings: &SrsSettings, - timezone: LocalDatePolicy, - ) -> Result { - self.check_legacy_path()?; - let _lock = lock_store(&self.path)?; - let mut loaded = self.load_latest()?; - let snapshot = - LearningSnapshot::capture(library, &loaded.data.learning, scope, settings, timezone)?; - if let Some(existing) = loaded - .data - .snapshots - .iter() - .find(|existing| same_snapshot_slot(existing, &snapshot)) - { - return Ok(PersistedLearningSnapshot { - snapshot: existing.clone(), - revision: loaded.data.revision, - recorded: false, - }); - } - loaded.data.snapshots.push(snapshot.clone()); - self.write_latest(&mut loaded)?; - Ok(PersistedLearningSnapshot { - snapshot, - revision: loaded.data.revision, - recorded: true, - }) - } - - pub fn reset_learning( - &self, - keys: impl IntoIterator, - ) -> Result - where - K: std::borrow::Borrow, - { - self.check_legacy_path()?; - let keys: BTreeSet = - keys.into_iter().map(|key| key.borrow().clone()).collect(); - let _lock = lock_store(&self.path)?; - let mut loaded = self.load_latest()?; - let mut reset_count = 0; - for item in &mut loaded.data.learning.items { - if keys.contains(&item.key) { - *item = LearningItem::new(item.key.clone()); - reset_count += 1; - } - } - if reset_count > 0 { - self.write_latest(&mut loaded)?; - } - Ok(PersistedLearningReset { - revision: loaded.data.revision, - learning: loaded.data.learning, - reset_count, - }) - } - - /// Persists a queue-only lifecycle change without replacing learning history. - pub fn save_session(&self, session: &mut LearningSessionSnapshot) -> Result { - self.check_legacy_path()?; - session.validate_configuration()?; - let _lock = lock_store(&self.path)?; - let mut loaded = self.load_latest()?; - check_session_revision(&loaded.data, session)?; - let previous = session.revision; - session.revision = session.revision.saturating_add(1); - upsert_session(&mut loaded.data, session); - if let Err(error) = self.write_latest(&mut loaded) { - session.revision = previous; - return Err(error); - } - Ok(loaded.data.revision) - } - - pub fn reset_review_order( - &self, - session: &mut LearningSessionSnapshot, - ) -> Result { - let mut reset = session.clone(); - reset.reset_review_order()?; - let revision = self.save_session(&mut reset)?; - *session = reset; - Ok(revision) - } - - /// Applies one event and its session transition in the same atomic replacement. Both - /// are based on the latest store contents loaded under the cross-process lock. - pub fn apply_attempt_and_session( - &self, - attempt: TrainingAttempt, - session: &mut LearningSessionSnapshot, - ) -> Result { - self.apply_attempts_and_session(vec![attempt], session) - } - - /// Persists an already displayed context prefix in one atomic transaction. - /// Every event is retained, but the store is read and replaced only once. - /// A retry must contain the whole batch: partial duplicates are rejected. - pub fn apply_attempts_and_session( - &self, - attempts: Vec, - session: &mut LearningSessionSnapshot, - ) -> Result { - self.check_legacy_path()?; - let invalid = |message| StoreError::Session(LearningSessionError::InvalidSnapshot(message)); - if attempts.is_empty() { - return Err(invalid("an attempt batch must not be empty")); - } - let mut identities = BTreeSet::new(); - for attempt in &attempts { - if attempt.session_id != session.session.id { - return Err(StoreError::SessionMismatch { - attempt_session_id: attempt.session_id.clone(), - session_id: session.session.id.clone(), - }); - } - if !identities.insert((&attempt.user_id, &attempt.client_attempt_id)) { - return Err(invalid("an attempt batch contains duplicate event IDs")); - } - } - let _lock = lock_store(&self.path)?; - let mut loaded = self.load_latest()?; - let mut unseen = identities; - for existing in &loaded.data.learning.attempts { - unseen.remove(&(&existing.user_id, &existing.client_attempt_id)); - if unseen.is_empty() { - break; - } - } - let duplicate_count = attempts.len() - unseen.len(); - if duplicate_count == attempts.len() { - let persisted_session = loaded - .data - .session_snapshot(&session.session.id) - .cloned() - .unwrap_or_else(|| session.clone()); - return Ok(PersistedSessionAttempt { - application: AttemptApplication::Duplicate, - revision: loaded.data.revision, - learning: loaded.data.learning, - session: persisted_session, - }); - } - if duplicate_count != 0 { - return Err(invalid("an attempt batch is only partially persisted")); - } - - session.validate_configuration()?; - check_session_revision(&loaded.data, session)?; - for attempt in attempts { - loaded - .data - .learning - .apply_attempt(attempt, &session.session.settings)?; - } - let previous = session.revision; - session.revision = session.revision.saturating_add(1); - upsert_session(&mut loaded.data, session); - if let Err(error) = self.write_latest(&mut loaded) { - session.revision = previous; - return Err(error); - } - Ok(PersistedSessionAttempt { - application: AttemptApplication::Applied, - revision: loaded.data.revision, - learning: loaded.data.learning, - session: session.clone(), - }) - } - - fn check_legacy_path(&self) -> Result<(), StoreError> { - if self.legacy_path.as_ref() == Some(&self.path) { - Err(StoreError::LegacyPath(self.path.clone())) - } else { - Ok(()) - } - } - - fn load_latest(&self) -> Result { - if let Some(bytes) = read_optional(&self.path)? { - let value: serde_json::Value = - serde_json::from_slice(&bytes).map_err(|e| json(&self.path, e))?; - let version = value - .get("version") - .and_then(serde_json::Value::as_u64) - .ok_or_else(|| StoreError::MissingVersion { - kind: "repertoire learning", - path: self.path.clone(), - })?; - let version = u32::try_from(version).unwrap_or(u32::MAX); - return match version { - STATS_VERSION => { - let legacy_practice = value.clone(); - let stats: StatsData = - serde_json::from_value(value).map_err(|e| json(&self.path, e))?; - validate_stats(&self.path, &stats)?; - let (learning, report) = migration::migrate_v2(&stats); - Ok(LoadedLearning { - data: LearningStoreData { - revision: stats.revision, - learning, - legacy_practice: Some(legacy_practice), - ..LearningStoreData::default() - }, - report, - source: LearningSource::V2(bytes), - }) - } - LEARNING_STORE_VERSION => { - let schema_error = |message| { - json( - &self.path, - ::custom(message), - ) - }; - let learning = value - .get("learning") - .and_then(serde_json::Value::as_object) - .ok_or_else(|| schema_error("v3 learning must be an object"))?; - for field in ["items", "attempts"] { - if learning.get(field).is_some_and(|value| !value.is_array()) { - return Err(schema_error("v3 learning items/attempts must be arrays")); - } - } - if value - .get("legacy_practice") - .is_some_and(|value| !value.is_null() && !value.is_object()) - { - return Err(schema_error("v3 legacy_practice must be an object or null")); - } - let data: LearningStoreData = - serde_json::from_value(value.clone()).map_err(|e| json(&self.path, e))?; - Ok(LoadedLearning { - data, - report: MigrationReport::default(), - source: LearningSource::V3(value), - }) - } - _ => Err(StoreError::UnsupportedVersion { - kind: "repertoire learning", - version, - path: self.path.clone(), - }), - }; - } - - let Some(legacy_path) = self.legacy_path.as_deref() else { - return Ok(LoadedLearning { - data: LearningStoreData::default(), - report: MigrationReport::default(), - source: LearningSource::Missing, - }); - }; - let Some(bytes) = read_optional(legacy_path)? else { - return Ok(LoadedLearning { - data: LearningStoreData::default(), - report: MigrationReport::default(), - source: LearningSource::Missing, - }); - }; - let legacy_lines: serde_json::Map = - serde_json::from_slice(&bytes).map_err(|e| json(legacy_path, e))?; - let mut legacy = StatsData::default(); - legacy.legacy_lines = legacy_lines; - let legacy_practice = serde_json::to_value(legacy).map_err(|e| json(legacy_path, e))?; - Ok(LoadedLearning { - data: LearningStoreData { - legacy_practice: Some(legacy_practice), - ..LearningStoreData::default() - }, - report: MigrationReport::default(), - source: LearningSource::LegacyLines, - }) - } - - fn write_latest(&self, loaded: &mut LoadedLearning) -> Result<(), StoreError> { - if let LearningSource::V2(bytes) = &loaded.source { - self.backup_v2_once(bytes)?; - } - loaded.data.version = LEARNING_STORE_VERSION; - loaded.data.revision = loaded.data.revision.saturating_add(1); - let current = serde_json::to_value(&loaded.data).map_err(|e| json(&self.path, e))?; - let value = match &loaded.source { - LearningSource::V3(raw) => preserve_extensions(raw, current), - _ => current, - }; - let bytes = serde_json::to_vec_pretty(&value).map_err(|e| json(&self.path, e))?; - write_atomic(&self.path, &bytes).map_err(|e| io(&self.path, e)) - } - - fn backup_v2_once(&self, bytes: &[u8]) -> Result<(), StoreError> { - let backup = learning_backup_path(&self.path); - match std::fs::metadata(&backup) { - Ok(metadata) if metadata.is_file() => return Ok(()), - Ok(_) => { - return Err(io( - &backup, - io::Error::new(io::ErrorKind::AlreadyExists, "backup path is not a file"), - )); - } - Err(error) if error.kind() == io::ErrorKind::NotFound => {} - Err(error) => return Err(io(&backup, error)), - } - write_atomic(&backup, bytes).map_err(|e| io(&backup, e)) - } -} - -/// Known values come from current state; unmodelled object fields remain from raw JSON. -fn preserve_extensions(raw: &serde_json::Value, current: serde_json::Value) -> serde_json::Value { - if current.as_object().is_some_and(|object| object.len() == 3) - && learning_item_key_fields(¤t).is_some() - { - return current; - } - match (raw, current) { - (serde_json::Value::Object(raw), serde_json::Value::Object(current)) => { - let mut merged = raw.clone(); - for (field, value) in current { - let value = match raw.get(&field) { - Some(raw) => preserve_extensions(raw, value), - None => value, - }; - merged.insert(field, value); - } - serde_json::Value::Object(merged) - } - (serde_json::Value::Array(raw), serde_json::Value::Array(current)) => { - let current_len = current.len(); - // Match persisted records by identity once, rather than scanning the entire - // history for every event on every save. First match preserves legacy semantics. - let mut by_identity = HashMap::with_capacity(raw.len()); - for previous in raw { - if let Some(identity) = stable_json_identity(previous) { - by_identity.entry(identity).or_insert(previous); - } - } - let merged = current - .into_iter() - .enumerate() - .map(|(index, value)| { - let previous = match stable_json_identity(&value) { - Some(identity) => by_identity.get(&identity).copied(), - None if raw.len() == current_len => raw.get(index), - None => None, - }; - match previous { - Some(raw) => preserve_extensions(raw, value), - None => value, - } - }) - .collect(); - serde_json::Value::Array(merged) - } - (_, current) => current, - } -} - -fn stable_json_identity(value: &serde_json::Value) -> Option { - let object = value.as_object()?; - if let (Some(user_id), Some(client_attempt_id)) = ( - object.get("user_id").and_then(serde_json::Value::as_str), - object - .get("client_attempt_id") - .and_then(serde_json::Value::as_str), - ) { - return Some(json_identity(&["attempt", user_id, client_attempt_id])); - } - if let Some((user_id, position_fen4, expected_uci)) = learning_item_key_fields(value) { - return Some(json_identity(&[ - "key", - user_id, - position_fen4, - expected_uci, - ])); - } - if let Some(key) = object.get("key") - && let Some((user_id, position_fen4, expected_uci)) = learning_item_key_fields(key) - { - let repertoire_id = object - .get("repertoire_id") - .and_then(serde_json::Value::as_str) - .unwrap_or_default(); - return Some(json_identity(&[ - "nested-key", - user_id, - position_fen4, - expected_uci, - repertoire_id, - ])); - } - if let (Some(date), Some(scope)) = ( - object.get("date").and_then(serde_json::Value::as_str), - object.get("scope"), - ) { - let mut scope = scope.clone(); - if let Some(object) = scope.as_object_mut() { - object.retain(|field, _| { - matches!( - field.as_str(), - "repertoire_ids" - | "side" - | "max_depth" - | "only_active" - | "branch_root" - | "as_of" - | "learning_priority" - ) - }); - } - let scope = scope.to_string(); - return Some(json_identity(&["learning-snapshot", date, &scope])); - } - if let Some(id) = object - .get("session") - .and_then(|session| session.get("id")) - .and_then(serde_json::Value::as_str) - { - return Some(json_identity(&["snapshot", id])); - } - object - .get("id") - .and_then(serde_json::Value::as_str) - .map(|id| json_identity(&["id", id])) -} - -fn learning_item_key_fields(value: &serde_json::Value) -> Option<(&str, &str, &str)> { - let object = value.as_object()?; - if object.contains_key("client_attempt_id") { - return None; - } - Some(( - object.get("user_id")?.as_str()?, - object.get("position_fen4")?.as_str()?, - object.get("expected_uci")?.as_str()?, - )) -} - -fn json_identity(parts: &[&str]) -> String { - serde_json::Value::Array( - parts - .iter() - .map(|part| serde_json::Value::String((*part).to_owned())) - .collect(), - ) - .to_string() -} - -fn check_session_revision( - data: &LearningStoreData, - session: &LearningSessionSnapshot, -) -> Result<(), StoreError> { - let actual = data - .session_snapshot(&session.session.id) - .map_or(0, |persisted| persisted.revision); - if session.revision == actual { - Ok(()) - } else { - Err(StoreError::SessionConflict { - session_id: session.session.id.clone(), - expected: session.revision, - actual, - }) - } -} - -fn upsert_session(data: &mut LearningStoreData, session: &LearningSessionSnapshot) { - if let Some(existing) = data - .sessions - .iter_mut() - .find(|existing| existing.id == session.session.id) - { - *existing = session.session.clone(); - } else { - data.sessions.push(session.session.clone()); - } - if let Some(existing) = data - .session_snapshots - .iter_mut() - .find(|existing| existing.session.id == session.session.id) - { - *existing = session.clone(); - } else { - data.session_snapshots.push(session.clone()); - } -} - -fn learning_backup_path(path: &Path) -> PathBuf { - let mut name = path.file_name().unwrap_or_default().to_os_string(); - name.push(".before-learning-v3"); - path.with_file_name(name) -} - -#[derive(Clone, Debug)] -pub struct StatsStore { - path: PathBuf, - legacy_path: Option, -} - -impl StatsStore { - /// A store for the new versioned format. It does not implicitly read or replace the - /// legacy global `training.json`. - pub fn new(path: impl Into) -> Self { - Self { - path: path.into(), - legacy_path: None, - } - } - - /// A new file plus an optional legacy source. Saving always writes `path`; the legacy - /// source is copied once to `.before-repertoire-v2` and is never renamed or overwritten. - pub fn with_legacy(path: impl Into, legacy_path: impl Into) -> Self { - Self { - path: path.into(), - legacy_path: Some(legacy_path.into()), - } - } - - pub fn path(&self) -> &Path { - &self.path - } - - pub fn legacy_path(&self) -> Option<&Path> { - self.legacy_path.as_deref() - } - - pub fn load(&self) -> Result { - if let Some(bytes) = read_optional(&self.path)? { - let mut stats: StatsData = - decode_versioned(&self.path, &bytes, "repertoire statistics", STATS_VERSION)?; - validate_stats(&self.path, &stats)?; - stats.migrate_position_stats(); - return Ok(stats); - } - let Some(legacy_path) = self.legacy_path.as_deref() else { - return Ok(StatsData::default()); - }; - let Some(bytes) = read_optional(legacy_path)? else { - return Ok(StatsData::default()); - }; - let legacy_lines: serde_json::Map = - serde_json::from_slice(&bytes).map_err(|e| json(legacy_path, e))?; - let mut stats = StatsData::default(); - stats.legacy_lines = legacy_lines; - Ok(stats) - } - - pub fn save(&self, stats: &mut StatsData) -> Result<(), StoreError> { - if self.legacy_path.as_ref() == Some(&self.path) { - return Err(StoreError::LegacyPath(self.path.clone())); - } - validate_stats(&self.path, stats)?; - let _lock = lock_store(&self.path)?; - let current = self.load()?; - if current.revision != stats.revision { - return Err(StoreError::Conflict { - path: self.path.clone(), - expected: stats.revision, - actual: current.revision, - }); - } - self.backup_legacy_once()?; - let previous = stats.revision; - stats.version = STATS_VERSION; - stats.revision = current.revision.saturating_add(1); - stats.normalize(); - let bytes = serde_json::to_vec_pretty(stats).map_err(|e| json(&self.path, e))?; - if let Err(error) = write_atomic(&self.path, &bytes) { - stats.revision = previous; - return Err(io(&self.path, error)); - } - Ok(()) - } - - fn backup_legacy_once(&self) -> Result<(), StoreError> { - let Some(legacy) = self.legacy_path.as_deref() else { - return Ok(()); - }; - let Some(bytes) = read_optional(legacy)? else { - return Ok(()); - }; - let backup = legacy_backup_path(legacy); - if backup.exists() { - return Ok(()); - } - write_atomic(&backup, &bytes).map_err(|e| io(&backup, e)) - } -} - -fn legacy_backup_path(legacy: &Path) -> PathBuf { - let mut name = legacy.file_name().unwrap_or_default().to_os_string(); - name.push(".before-repertoire-v2"); - legacy.with_file_name(name) -} - -fn validate_stats(path: &Path, stats: &StatsData) -> Result<(), StoreError> { - let mut moves = BTreeSet::new(); - let mut runs = BTreeSet::new(); - let mut paths = BTreeSet::new(); - let valid = stats - .move_stats - .iter() - .all(|entry| moves.insert(&entry.key)) - && stats - .runs - .iter() - .all(|entry| runs.insert((&entry.repertoire_id, &entry.mode))) - && stats - .path_stats - .iter() - .all(|entry| paths.insert(&entry.key)); - if valid { - Ok(()) - } else { - Err(StoreError::DuplicateStats(path.to_owned())) - } -} - -#[cfg(test)] -mod lock_tests { - use super::*; - - #[test] - fn child_exits_while_holding_store_lock() { - let Some(path) = std::env::var_os("CP_TRAINER_LOCK_EXIT_TEST") else { - return; - }; - let _lock = lock_store(Path::new(&path)).unwrap(); - // process::exit skips Rust destructors, as does abrupt process termination. - std::process::exit(0); - } - - #[test] - fn store_lock_is_released_on_drop_and_process_exit() { - let path = - std::env::temp_dir().join(format!("cp-store-lock-exit-{}.json", std::process::id())); - let lock_path = path.with_file_name(format!( - "{}.lock", - path.file_name().unwrap().to_string_lossy() - )); - drop(lock_store(&path).unwrap()); - let file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open(&lock_path) - .unwrap(); - file.try_lock().unwrap(); - file.unlock().unwrap(); - let status = std::process::Command::new(std::env::current_exe().unwrap()) - .arg("--exact") - .arg("repertoire::store::lock_tests::child_exits_while_holding_store_lock") - .env("CP_TRAINER_LOCK_EXIT_TEST", &path) - .status() - .unwrap(); - assert!(status.success()); - assert!(lock_path.exists()); - file.try_lock().unwrap(); - file.unlock().unwrap(); - std::fs::remove_file(lock_path).unwrap(); - } -} - -#[cfg(test)] -#[path = "store_tests.rs"] -mod store_tests; diff --git a/crates/trainer/src/repertoire/store_tests.rs b/crates/trainer/src/repertoire/store_tests.rs deleted file mode 100644 index a3db3ba..0000000 --- a/crates/trainer/src/repertoire/store_tests.rs +++ /dev/null @@ -1,921 +0,0 @@ -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Barrier}; - -use super::*; -use crate::repertoire::learning::{LearningItemKey, TrainingEventType}; -use crate::repertoire::learning_graph::StatsScope; -use crate::repertoire::model::{LearningSide, RepertoireId}; -use crate::repertoire::stats::{MoveKey, MoveStats}; - -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-store-{}-{}-{name}", - std::process::id(), - sequence - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - Self(path) - } - - fn join(&self, name: &str) -> PathBuf { - self.0.join(name) - } -} - -impl Drop for TestDir { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.0); - } -} - -fn legacy_move(repertoire: &str, mode: TrainingMode, expected_uci: &str) -> MoveStats { - MoveStats::new(MoveKey { - repertoire_id: RepertoireId::legacy(repertoire), - mode, - position_fen4: "fen-shared".into(), - expected_uci: expected_uci.into(), - }) -} - -fn attempt(id: &str, happened_at: i64) -> TrainingAttempt { - TrainingAttempt { - user_id: "local".into(), - position_fen4: "fen-shared".into(), - client_attempt_id: id.into(), - session_id: "session-1".into(), - event_type: TrainingEventType::CorrectIndependent, - expected_uci: "e2e4".into(), - actual_uci: Some("e2e4".into()), - response_time_ms: Some(250), - happened_at, - } -} - -fn write_json(path: &Path, value: &impl Serialize) -> Vec { - let bytes = serde_json::to_vec_pretty(value).unwrap(); - std::fs::write(path, &bytes).unwrap(); - bytes -} - -fn read_json(path: &Path) -> serde_json::Value { - serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap() -} - -fn extension_marker() -> serde_json::Value { - serde_json::json!({"preserved": [1, {"nested": true}]}) -} - -const V3_EXTENSION_POINTERS: &[&str] = &[ - "/future_top_level_field", - "/learning/future_learning_field", - "/learning/items/0/future_item_field", - "/learning/attempts/0/future_attempt_field", - "/sessions/0/future_session_field", - "/session_snapshots/0/future_snapshot_field", - "/session_snapshots/0/session/future_nested_session_field", - "/session_snapshots/0/session/settings/future_settings_field", - "/session_snapshots/0/stats_scope/future_scope_field", - "/session_snapshots/0/queue/0/future_target_field", -]; - -fn assert_v3_extensions(value: &serde_json::Value) { - for pointer in V3_EXTENSION_POINTERS { - assert_eq!( - value.pointer(pointer), - Some(&extension_marker()), - "{pointer}" - ); - } -} - -fn extension_fixture() -> (LearningStoreData, Library) { - let mut library = Library::default(); - let repertoire_id = library - .create("Test", &chess_core::parse_str("1. e4 *").game) - .unwrap(); - let scope = StatsScope::for_repertoire(repertoire_id, LearningSide::White, 0); - let key = crate::repertoire::learning_graph::active_learning_memberships(&library, &scope) - .unwrap() - .into_iter() - .find(|membership| membership.key.expected_uci == "e2e4") - .unwrap() - .key; - let mut learning = LearningData::default(); - let item = learning.ensure_item(key); - item.introduced = true; - item.next_review_at = Some(0); - learning.attempts.push(attempt("existing", 0)); - let snapshot = LearningSessionSnapshot::new( - "session-1", - &library, - &learning, - scope, - SrsSettings::default(), - ) - .unwrap(); - assert_eq!(snapshot.queue.len(), 1); - let data = LearningStoreData { - learning, - sessions: vec![snapshot.session.clone()], - session_snapshots: vec![snapshot], - ..LearningStoreData::default() - }; - (data, library) -} - -fn inject_v3_extensions(value: &mut serde_json::Value) { - value["future_top_level_field"] = extension_marker(); - value["learning"]["future_learning_field"] = extension_marker(); - value["learning"]["items"][0]["future_item_field"] = extension_marker(); - value["learning"]["items"][0]["key"]["future_key_extension"] = serde_json::json!(true); - value["learning"]["attempts"][0]["future_attempt_field"] = extension_marker(); - value["sessions"][0]["future_session_field"] = extension_marker(); - value["session_snapshots"][0]["future_snapshot_field"] = extension_marker(); - value["session_snapshots"][0]["session"]["future_nested_session_field"] = extension_marker(); - value["session_snapshots"][0]["session"]["settings"]["future_settings_field"] = - extension_marker(); - value["session_snapshots"][0]["stats_scope"]["future_scope_field"] = extension_marker(); - value["session_snapshots"][0]["queue"][0]["future_target_field"] = extension_marker(); -} - -#[cfg(unix)] -fn file_inode(path: &Path) -> u64 { - use std::os::unix::fs::MetadataExt as _; - std::fs::metadata(path).unwrap().ino() -} - -#[test] -fn at_23_duplicate_attempt_has_one_effect_and_one_file_replacement() { - let dir = TestDir::new("duplicate"); - let path = dir.join("repertoire-training.json"); - let store = LearningStore::new(&path); - let first_attempt = attempt("attempt-1", 1_000); - - let first = store - .apply_attempt(first_attempt.clone(), &SrsSettings::default()) - .unwrap(); - assert_eq!(first.application, AttemptApplication::Applied); - assert_eq!(first.revision, 1); - assert_eq!(first.learning.attempts.len(), 1); - let key = LearningItemKey::local("fen-shared", "e2e4"); - assert_eq!(first.learning.item(&key).unwrap().correct_streak, 1); - assert_eq!(first.learning.item(&key).unwrap().correct_count, 1); - let bytes_after_first = std::fs::read(&path).unwrap(); - #[cfg(unix)] - let inode_after_first = file_inode(&path); - - let duplicate = store - .apply_attempt(first_attempt, &SrsSettings::default()) - .unwrap(); - assert_eq!(duplicate.application, AttemptApplication::Duplicate); - assert_eq!(duplicate.revision, first.revision); - assert_eq!(duplicate.learning, first.learning); - assert_eq!(std::fs::read(&path).unwrap(), bytes_after_first); - #[cfg(unix)] - assert_eq!(file_inode(&path), inode_after_first); - - let different = store - .apply_attempt(attempt("attempt-2", 2_000), &SrsSettings::default()) - .unwrap(); - assert_eq!(different.application, AttemptApplication::Applied); - assert_eq!(different.revision, 2); - assert_eq!(different.learning.attempts.len(), 2); - assert_eq!(different.learning.item(&key).unwrap().correct_streak, 2); - assert_eq!(different.learning.item(&key).unwrap().correct_count, 2); -} - -#[test] -fn attempt_ids_are_scoped_to_user_and_different_ids_are_not_suppressed() { - let dir = TestDir::new("attempt-scope"); - let store = LearningStore::new(dir.join("repertoire-training.json")); - let mut other_user = attempt("shared-client-id", 10); - other_user.user_id = "other-profile".into(); - assert_eq!( - store - .apply_attempt(other_user, &SrsSettings::default()) - .unwrap() - .application, - AttemptApplication::Applied - ); - let local = store - .apply_attempt(attempt("shared-client-id", 11), &SrsSettings::default()) - .unwrap(); - assert_eq!(local.application, AttemptApplication::Applied); - assert_eq!(local.learning.attempts.len(), 2); - assert_eq!(local.learning.items.len(), 2); -} - -#[test] -fn two_stores_reload_latest_revision_instead_of_overwriting_stale_state() { - let dir = TestDir::new("two-stores"); - let path = dir.join("repertoire-training.json"); - let first = LearningStore::new(&path); - let second = LearningStore::new(&path); - let stale_first = first.load().unwrap(); - let stale_second = second.load().unwrap(); - assert_eq!(stale_first.revision, stale_second.revision); - - let barrier = Arc::new(Barrier::new(3)); - let writers = [ - (first.clone(), "from-first"), - (second.clone(), "from-second"), - ] - .map(|(store, id)| { - let barrier = Arc::clone(&barrier); - std::thread::spawn(move || { - barrier.wait(); - store.apply_attempt(attempt(id, 100), &SrsSettings::default()) - }) - }); - barrier.wait(); - let mut revisions = writers - .into_iter() - .map(|writer| writer.join().unwrap().unwrap().revision) - .collect::>(); - revisions.sort_unstable(); - assert_eq!(revisions, [1, 2]); - - let third = first - .apply_attempt(attempt("after-both", 200), &SrsSettings::default()) - .unwrap(); - assert_eq!(third.revision, 3); - assert_eq!(third.learning.attempts.len(), 3); - let persisted = second.load().unwrap(); - assert_eq!(persisted.revision, 3); - assert_eq!(persisted.learning.attempts.len(), 3); - assert!(stale_first.learning.attempts.is_empty()); - assert!(stale_second.learning.attempts.is_empty()); -} - -#[test] -fn process_attempt_writer_helper() { - let (Some(path), Some(id)) = ( - std::env::var_os("CP_LEARNING_STORE_CHILD_PATH"), - std::env::var_os("CP_LEARNING_STORE_CHILD_ID"), - ) else { - return; - }; - let id = id.to_string_lossy().into_owned(); - let result = LearningStore::new(PathBuf::from(path)) - .apply_attempt(attempt(&id, 100), &SrsSettings::default()) - .unwrap(); - assert_eq!(result.application, AttemptApplication::Applied); - std::process::exit(0); -} - -#[test] -fn two_processes_and_stale_parent_snapshot_keep_every_attempt() { - let dir = TestDir::new("two-processes"); - let path = dir.join("repertoire-training.json"); - let parent = LearningStore::new(&path); - assert_eq!(parent.load().unwrap().revision, 0); - let executable = std::env::current_exe().unwrap(); - let mut children = ["process-a", "process-b"] - .into_iter() - .map(|id| { - std::process::Command::new(&executable) - .arg("--exact") - .arg("repertoire::store::store_tests::process_attempt_writer_helper") - .env("CP_LEARNING_STORE_CHILD_PATH", &path) - .env("CP_LEARNING_STORE_CHILD_ID", id) - .stdout(std::process::Stdio::null()) - .spawn() - .unwrap() - }) - .collect::>(); - for child in &mut children { - assert!(child.wait().unwrap().success()); - } - - let after_children = parent.load().unwrap(); - assert_eq!(after_children.revision, 2); - assert_eq!(after_children.learning.attempts.len(), 2); - let after_stale_parent = parent - .apply_attempt(attempt("stale-parent", 200), &SrsSettings::default()) - .unwrap(); - assert_eq!(after_stale_parent.revision, 3); - assert_eq!(after_stale_parent.learning.attempts.len(), 3); -} - -#[test] -fn v2_to_v3_is_idempotent_and_backup_is_created_only_once() { - let dir = TestDir::new("migration-idempotent"); - let path = dir.join("repertoire-training.json"); - let mut stats = StatsData::default(); - stats.revision = 4; - stats.legacy_lines.insert( - "old-line".into(), - serde_json::json!({"runs": 3, "unknown": 7}), - ); - let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); - entry.attempts = 5; - entry.correct = 4; - entry.wrong = 1; - entry.streak = 2; - entry.last_seen = Some(100); - entry.due = Some(500); - entry.interval_seconds = Some(400); - stats.move_stats.push(entry); - let original = write_json(&path, &stats); - let store = LearningStore::new(&path); - - let (loaded, report) = store.load_with_report().unwrap(); - assert_eq!(loaded.version, LEARNING_STORE_VERSION); - assert_eq!(loaded.revision, 4); - assert_eq!(loaded.learning.items.len(), 1); - assert_eq!( - serde_json::to_value(&loaded.legacy_practice).unwrap(), - serde_json::to_value(&stats).unwrap() - ); - assert_eq!(report, MigrationReport::default()); - assert_eq!(std::fs::read(&path).unwrap(), original); - - let first_report = store.migrate().unwrap(); - assert_eq!(first_report, MigrationReport::default()); - let backup_path = dir.join("repertoire-training.json.before-learning-v3"); - assert_eq!(std::fs::read(&backup_path).unwrap(), original); - let migrated = store.load().unwrap(); - assert_eq!(migrated.version, 3); - assert_eq!(migrated.revision, 5); - assert_eq!( - serde_json::to_value(&migrated.legacy_practice).unwrap(), - serde_json::to_value(&stats).unwrap() - ); - let first_v3 = std::fs::read(&path).unwrap(); - - assert_eq!(store.migrate().unwrap(), MigrationReport::default()); - assert_eq!(std::fs::read(&path).unwrap(), first_v3); - assert_eq!(std::fs::read(&backup_path).unwrap(), original); - - store - .apply_attempt(attempt("new-after-migration", 600), &SrsSettings::default()) - .unwrap(); - assert_eq!(store.load().unwrap().revision, 6); - assert_eq!(std::fs::read(&backup_path).unwrap(), original); - assert_eq!( - store.load_with_report().unwrap().1, - MigrationReport::default() - ); -} - -#[test] -fn missing_legacy_interval_is_reconstructed_from_due_and_last_seen() { - let dir = TestDir::new("legacy-interval-reconstruction"); - let path = dir.join("repertoire-training.json"); - let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); - entry.attempts = 1; - entry.last_seen = Some(100); - entry.due = Some(500); - entry.interval_seconds = None; - let mut stats = StatsData::default(); - stats.move_stats.push(entry); - write_json(&path, &stats); - - let (loaded, _) = LearningStore::new(path).load_with_report().unwrap(); - let item = loaded - .learning - .item(&LearningItemKey::local("fen-shared", "e2e4")) - .unwrap(); - assert_eq!(item.next_review_at, Some(500)); - assert_eq!(item.previous_interval_seconds, Some(400)); -} - -#[test] -fn overdue_legacy_interval_is_not_reconstructed_as_a_duration() { - let dir = TestDir::new("legacy-overdue-interval"); - let path = dir.join("repertoire-training.json"); - for (due, last_seen) in [(100, 500), (100, 100)] { - let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); - entry.attempts = 1; - entry.last_seen = Some(last_seen); - entry.due = Some(due); - entry.interval_seconds = None; - let mut stats = StatsData::default(); - stats.move_stats.push(entry); - write_json(&path, &stats); - - let (loaded, _) = LearningStore::new(&path).load_with_report().unwrap(); - let item = loaded - .learning - .item(&LearningItemKey::local("fen-shared", "e2e4")) - .unwrap(); - assert_eq!(item.previous_interval_seconds, None); - } -} - -#[test] -fn unusable_backup_path_blocks_migration_without_replacing_v2() { - let dir = TestDir::new("backup-error"); - let path = dir.join("repertoire-training.json"); - let original = write_json(&path, &StatsData::default()); - let backup = dir.join("repertoire-training.json.before-learning-v3"); - std::fs::create_dir(&backup).unwrap(); - let store = LearningStore::new(&path); - - assert!(matches!(store.migrate(), Err(StoreError::Io { .. }))); - assert_eq!(std::fs::read(&path).unwrap(), original); - assert!(matches!( - store.apply_attempt(attempt("not-persisted", 100), &SrsSettings::default()), - Err(StoreError::Io { .. }) - )); - assert_eq!(std::fs::read(&path).unwrap(), original); -} - -#[test] -fn collision_merge_uses_latest_streak_earliest_due_and_is_deterministic() { - let dir = TestDir::new("collision"); - let mut older = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); - older.attempts = 7; - older.correct = 6; - older.wrong = 1; - older.streak = 2; - older.last_seen = Some(100); - older.due = Some(500); - older.interval_seconds = Some(50); - let mut latest = legacy_move("repertoire-b", TrainingMode::Black, "e2e4"); - latest.attempts = 3; - latest.correct = 1; - latest.wrong = 2; - latest.streak = -3; - latest.last_seen = Some(200); - latest.due = Some(300); - latest.interval_seconds = Some(40); - - let mut stats = StatsData::default(); - stats.move_stats = vec![older.clone(), latest.clone()]; - let mut reversed = StatsData::default(); - reversed.move_stats = vec![latest, older]; - let first_path = dir.join("first.json"); - let second_path = dir.join("second.json"); - write_json(&first_path, &stats); - write_json(&second_path, &reversed); - - let (data, report) = LearningStore::new(first_path).load_with_report().unwrap(); - let (reversed_data, reversed_report) = - LearningStore::new(second_path).load_with_report().unwrap(); - assert_eq!(data.learning, reversed_data.learning); - assert_eq!(report, reversed_report); - assert_eq!(report.merged, 1); - assert_eq!(report.conflicts, 1); - assert_eq!(report.skipped_both, 0); - assert_eq!( - serde_json::to_value(&data.legacy_practice).unwrap(), - serde_json::to_value(&stats).unwrap() - ); - - assert_eq!(data.learning.items.len(), 1); - let item = &data.learning.items[0]; - assert_eq!(item.key, LearningItemKey::local("fen-shared", "e2e4")); - assert_eq!(item.correct_streak, 0); - assert_eq!(item.wrong_streak, 3); - assert_eq!(item.last_review_at, Some(200)); - assert_eq!(item.next_review_at, Some(300)); - assert_eq!(item.previous_interval_seconds, Some(40)); - assert!(item.introduced); - assert_eq!(item.correct_count, 0); - assert_eq!(item.wrong_count, 0); - assert_eq!(item.last_correct_at, None); - assert_eq!(item.accuracy_percent(), None); -} - -#[test] -fn both_without_uci_is_skipped_and_old_attempts_do_not_create_accuracy() { - let dir = TestDir::new("conservative-migration"); - let mut skipped = legacy_move("repertoire-a", TrainingMode::Both, ""); - skipped.attempts = 20; - skipped.correct = 15; - skipped.wrong = 5; - skipped.streak = 4; - skipped.due = Some(100); - let mut scheduled_only = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); - scheduled_only.due = Some(200); - scheduled_only.interval_seconds = Some(100); - let mut attempted = legacy_move("repertoire-b", TrainingMode::Black, "d2d4"); - attempted.attempts = 8; - attempted.correct = 7; - attempted.wrong = 1; - attempted.streak = 2; - let mut stats = StatsData::default(); - stats.move_stats = vec![skipped, scheduled_only, attempted]; - let path = dir.join("stats.json"); - write_json(&path, &stats); - - let (data, report) = LearningStore::new(path).load_with_report().unwrap(); - assert_eq!(report.skipped_both, 1); - assert_eq!(report.merged, 0); - assert_eq!(report.conflicts, 0); - assert_eq!(data.learning.items.len(), 2); - assert_eq!( - data.legacy_practice.unwrap()["move_stats"] - .as_array() - .unwrap() - .len(), - 3 - ); - let scheduled = data - .learning - .item(&LearningItemKey::local("fen-shared", "e2e4")) - .unwrap(); - assert!(scheduled.introduced); - assert_eq!(scheduled.next_review_at, Some(200)); - assert_eq!(scheduled.previous_interval_seconds, Some(100)); - let attempted = data - .learning - .item(&LearningItemKey::local("fen-shared", "d2d4")) - .unwrap(); - assert!(attempted.introduced); - assert_eq!(attempted.correct_streak, 2); - assert_eq!(attempted.independent_attempt_count(), 0); - assert_eq!(attempted.accuracy_percent(), None); - assert_eq!(attempted.last_correct_at, None); -} - -#[test] -fn legacy_lines_are_retained_and_training_json_is_never_changed() { - let dir = TestDir::new("legacy-lines"); - let legacy_path = dir.join("training.json"); - let legacy_bytes = serde_json::to_vec_pretty(&serde_json::json!({ - "line-a": {"runs": 4, "unknown": [1, 2, 3]}, - "line-b": {"runs": 2, "best": 1} - })) - .unwrap(); - std::fs::write(&legacy_path, &legacy_bytes).unwrap(); - let path = dir.join("repertoire-training.json"); - let store = LearningStore::with_legacy(&path, &legacy_path); - - let loaded = store.load().unwrap(); - let legacy = loaded.legacy_practice.as_ref().unwrap(); - assert_eq!(legacy["legacy_lines"].as_object().unwrap().len(), 2); - assert_eq!( - legacy["legacy_lines"]["line-a"]["unknown"], - serde_json::json!([1, 2, 3]) - ); - store.migrate().unwrap(); - assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); - store - .apply_attempt(attempt("new-event", 1_000), &SrsSettings::default()) - .unwrap(); - assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); - let persisted = store.load().unwrap(); - assert_eq!( - persisted.legacy_practice.unwrap()["legacy_lines"], - legacy["legacy_lines"] - ); - - let old_reader = StatsStore::with_legacy(dir.join("old-reader.json"), &legacy_path); - assert_eq!(old_reader.load().unwrap().legacy_lines.len(), 2); - assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); -} - -#[test] -fn v3_session_snapshot_survives_attempt_persistence() { - let dir = TestDir::new("sessions"); - let path = dir.join("repertoire-training.json"); - let mut data = LearningStoreData { - revision: 7, - ..LearningStoreData::default() - }; - let session = LearningSession { - id: "session-1".into(), - mode: QueueMode::SpacedRepetition, - side: TrainingMode::White, - scope: TrainingScopeKey::default(), - settings: SrsSettings { - growth_factor: 2.25, - ..SrsSettings::default() - }, - }; - data.sessions.push(session.clone()); - write_json(&path, &data); - - let store = LearningStore::new(&path); - let loaded = store.load().unwrap(); - assert_eq!(loaded.sessions.len(), 1); - assert_eq!(loaded.sessions.first(), Some(&session)); - let applied = store - .apply_attempt(attempt("session-event", 100), &SrsSettings::default()) - .unwrap(); - assert_eq!(applied.revision, 8); - assert_eq!(store.load().unwrap().sessions, [session]); -} - -#[test] -fn v3_unknown_fields_survive_plain_and_session_attempt_roundtrips() { - let dir = TestDir::new("v3-extensions"); - let path = dir.join("repertoire-training.json"); - let (data, library) = extension_fixture(); - let mut raw = serde_json::to_value(data).unwrap(); - inject_v3_extensions(&mut raw); - let key_shaped = |object: &mut serde_json::Value| { - object["user_id"] = serde_json::json!("local"); - object["position_fen4"] = serde_json::json!("fen-shared"); - object["expected_uci"] = serde_json::json!("e2e4"); - }; - key_shaped(&mut raw); - key_shaped(&mut raw["learning"]); - let original = write_json(&path, &raw); - let store = LearningStore::new(&path); - assert_eq!(store.load().unwrap().revision, 0); - assert_eq!(std::fs::read(&path).unwrap(), original); - - store - .apply_attempt(attempt("plain-event", 100), &SrsSettings::default()) - .unwrap(); - let saved = read_json(&path); - assert_eq!(saved["revision"], serde_json::json!(1)); - assert_eq!(saved["learning"]["attempts"].as_array().unwrap().len(), 2); - assert_v3_extensions(&saved); - assert!( - saved["learning"]["items"][0]["key"] - .get("future_key_extension") - .is_none() - ); - - let loaded = store.load().unwrap(); - assert_eq!(loaded.revision, 1); - assert_eq!( - loaded.extensions["future_top_level_field"], - extension_marker() - ); - assert_eq!( - loaded.learning.extensions["future_learning_field"], - extension_marker() - ); - let mut session = loaded.session_snapshot("session-1").cloned().unwrap(); - let session_attempt = session - .play_uci(&library, "e2e4", "session-event", 200, Some(250)) - .unwrap(); - let persisted = store - .apply_attempt_and_session(session_attempt, &mut session) - .unwrap(); - assert_eq!(persisted.application, AttemptApplication::Applied); - assert_eq!(persisted.revision, 2); - assert_eq!(persisted.session.revision, 1); - - let saved = read_json(&path); - assert_eq!(saved["revision"], serde_json::json!(2)); - assert_eq!(saved["learning"]["attempts"].as_array().unwrap().len(), 3); - assert_eq!( - saved["session_snapshots"][0]["revision"], - serde_json::json!(1) - ); - assert_v3_extensions(&saved); -} - -#[test] -fn v2_unknown_root_and_nested_fields_survive_migration_and_later_writes() { - let dir = TestDir::new("v2-raw-extensions"); - let path = dir.join("repertoire-training.json"); - let mut stats = StatsData::default(); - stats.revision = 2; - stats - .legacy_lines - .insert("old-line".into(), serde_json::json!({"runs": 3})); - let mut entry = legacy_move("repertoire-a", TrainingMode::White, "e2e4"); - entry.attempts = 1; - entry.correct = 1; - entry.last_seen = Some(100); - entry.due = Some(500); - entry.interval_seconds = Some(400); - stats.move_stats.push(entry); - let mut raw = serde_json::to_value(&stats).unwrap(); - raw["future_v2_root"] = extension_marker(); - raw["move_stats"][0]["future_move_stats_field"] = extension_marker(); - raw["move_stats"][0]["key"]["future_move_key_field"] = extension_marker(); - raw["move_stats"][0]["recent"] = serde_json::json!([{ - "at": 100, - "correct": true, - "hinted": false, - "actual_uci": "e2e4", - "future_recent_field": extension_marker() - }]); - raw["legacy_lines"]["old-line"]["future_line_field"] = extension_marker(); - let original = write_json(&path, &raw); - let store = LearningStore::new(&path); - let extension_pointers = [ - "/legacy_practice/future_v2_root", - "/legacy_practice/move_stats/0/future_move_stats_field", - "/legacy_practice/move_stats/0/key/future_move_key_field", - "/legacy_practice/move_stats/0/recent/0/future_recent_field", - "/legacy_practice/legacy_lines/old-line/future_line_field", - ]; - - let (loaded, _) = store.load_with_report().unwrap(); - assert_eq!(loaded.learning.items.len(), 1); - assert_eq!( - loaded.legacy_practice.as_ref().unwrap()["future_v2_root"], - extension_marker() - ); - store.migrate().unwrap(); - let backup = dir.join("repertoire-training.json.before-learning-v3"); - assert_eq!(std::fs::read(backup).unwrap(), original); - let saved = read_json(&path); - assert_eq!(saved["revision"], serde_json::json!(3)); - for pointer in extension_pointers { - assert_eq!( - saved.pointer(pointer), - Some(&extension_marker()), - "{pointer}" - ); - } - - store - .apply_attempt(attempt("after-raw-migration", 600), &SrsSettings::default()) - .unwrap(); - let saved = read_json(&path); - assert_eq!(saved["revision"], serde_json::json!(4)); - for pointer in extension_pointers { - assert_eq!( - saved.pointer(pointer), - Some(&extension_marker()), - "{pointer}" - ); - } -} - -#[test] -fn unreadable_missing_and_unsupported_versions_are_errors_not_empty_data() { - let dir = TestDir::new("read-errors"); - let path = dir.join("repertoire-training.json"); - let store = LearningStore::new(&path); - - std::fs::write(&path, b"{broken").unwrap(); - assert!(matches!(store.load(), Err(StoreError::Json { .. }))); - assert!(matches!(store.migrate(), Err(StoreError::Json { .. }))); - assert_eq!(std::fs::read(&path).unwrap(), b"{broken"); - - std::fs::write(&path, br#"{"learning":{"items":[],"attempts":[]}}"#).unwrap(); - assert!(matches!( - store.load(), - Err(StoreError::MissingVersion { .. }) - )); - - std::fs::write( - &path, - br#"{"version":4,"learning":{"items":[],"attempts":[]}}"#, - ) - .unwrap(); - assert!(matches!( - store.load(), - Err(StoreError::UnsupportedVersion { version: 4, .. }) - )); - assert!(matches!( - store.apply_attempt(attempt("must-not-write", 1), &SrsSettings::default()), - Err(StoreError::UnsupportedVersion { version: 4, .. }) - )); - - std::fs::write(&path, br#"{"version":3,"learning":[]}"#).unwrap(); - let result = store.load(); - assert!( - matches!(&result, Err(StoreError::Json { .. })), - "unexpected result: {result:?}" - ); -} - -#[test] -fn extension_merge_tracks_reordered_identities_and_keeps_first_duplicate() { - let raw = serde_json::json!([ - {"user_id":"u", "client_attempt_id":"a", "known":0, "plugin":{"first":true}}, - {"user_id":"u", "client_attempt_id":"b", "known":0, "plugin":{"second":true}}, - {"user_id":"u", "client_attempt_id":"a", "known":0, "plugin":{"wrong":true}} - ]); - let current = serde_json::json!([ - {"user_id":"u", "client_attempt_id":"b", "known":2}, - {"user_id":"u", "client_attempt_id":"a", "known":1}, - {"user_id":"u", "client_attempt_id":"c", "known":3} - ]); - let merged = preserve_extensions(&raw, current); - assert_eq!( - merged, - serde_json::json!([ - {"user_id":"u", "client_attempt_id":"b", "known":2, "plugin":{"second":true}}, - {"user_id":"u", "client_attempt_id":"a", "known":1, "plugin":{"first":true}}, - {"user_id":"u", "client_attempt_id":"c", "known":3} - ]) - ); -} - -#[test] -fn context_batch_is_atomic_retryable_and_preserves_every_event() { - let dir = TestDir::new("context-batch"); - let store = LearningStore::new(dir.join("learning.json")); - let mut library = Library::default(); - let id = library - .create( - "Context", - &chess_core::parse_str("1. e4 e5 2. Nf3 Nc6 3. Bb5 *").game, - ) - .unwrap(); - let scope = StatsScope::for_repertoire(id, LearningSide::White, 100); - let mut learning = LearningData::default(); - let key = crate::repertoire::active_learning_memberships(&library, &scope) - .unwrap() - .into_iter() - .find(|m| m.key.expected_uci == "f1b5") - .unwrap() - .key; - let item = learning.ensure_item(key); - item.introduced = true; - item.next_review_at = Some(0); - let mut session = LearningSessionSnapshot::new( - "context-batch", - &library, - &learning, - scope, - SrsSettings::default(), - ) - .unwrap(); - store.save_session(&mut session).unwrap(); - let start = store.load().unwrap(); - let original = std::fs::read(store.path()).unwrap(); - let mut events = Vec::new(); - for i in 0..4 { - events.push( - session - .advance_context_with_learning(&library, &learning, format!("context-{i}"), 100) - .unwrap(), - ); - } - assert_eq!(session.context_index, 4); - let retry = session.clone(); - assert!( - store - .apply_attempts_and_session(vec![], &mut session) - .is_err() - ); - let mut invalid = events.clone(); - invalid[3].client_attempt_id.clear(); - assert!( - store - .apply_attempts_and_session(invalid, &mut session) - .is_err() - ); - assert_eq!(std::fs::read(store.path()).unwrap(), original); - assert_eq!(session, retry); - assert!( - store - .apply_attempts_and_session(vec![events[0].clone(), events[0].clone()], &mut session) - .is_err() - ); - assert_eq!(std::fs::read(store.path()).unwrap(), original); - - let saved = store - .apply_attempts_and_session(events.clone(), &mut session) - .unwrap(); - assert_eq!(saved.application, AttemptApplication::Applied); - assert_eq!( - saved.revision, - start.revision + 1, - "one transaction for the whole prefix" - ); - assert_eq!(saved.session.revision, retry.revision + 1); - assert_eq!(saved.learning.attempts, events); - assert!( - saved - .learning - .items - .iter() - .all(|item| item.correct_streak == 0) - ); - let bytes = std::fs::read(store.path()).unwrap(); - let mut stale = retry.clone(); - let duplicate = store - .apply_attempts_and_session(events.clone(), &mut stale) - .unwrap(); - assert_eq!(duplicate.application, AttemptApplication::Duplicate); - assert_eq!(duplicate.session, saved.session); - assert_eq!(std::fs::read(store.path()).unwrap(), bytes); - - let mut partial = events.clone(); - partial[3].client_attempt_id = "new-id".into(); - assert!( - store - .apply_attempts_and_session(partial, &mut session) - .is_err() - ); - assert_eq!(std::fs::read(store.path()).unwrap(), bytes); - let mut concurrent = events.clone(); - for event in &mut concurrent { - event.client_attempt_id.push_str("-concurrent"); - } - assert!(matches!( - store.apply_attempts_and_session(concurrent, &mut stale), - Err(StoreError::SessionConflict { .. }) - )); - assert_eq!(std::fs::read(store.path()).unwrap(), bytes); - let loaded = store.load().unwrap(); - loaded - .session_snapshot("context-batch") - .unwrap() - .validate(&library) - .unwrap(); - assert_eq!(loaded.learning.attempts, events); -} diff --git a/crates/trainer/src/repertoire/tests.rs b/crates/trainer/src/repertoire/tests.rs deleted file mode 100644 index 2e2516e..0000000 --- a/crates/trainer/src/repertoire/tests.rs +++ /dev/null @@ -1,408 +0,0 @@ -use std::path::PathBuf; -use std::sync::atomic::{AtomicU64, Ordering}; - -use chess_core::shakmaty::{Chess, Move, Position}; -use chess_core::{Game, MoveKind, NodeId, StartPosition}; -use serde_json::json; - -use super::*; - -static TEST_DIR: AtomicU64 = AtomicU64::new(1); - -fn game(pgn: &str) -> Game { - chess_core::parse_str(pgn).game -} - -fn play(game: &Game, line: &[&str]) -> Vec { - let mut position = game.start().position().clone(); - line.iter() - .map(|text| { - let mv = text - .parse::() - .unwrap() - .to_move(&position) - .unwrap(); - position.play_unchecked(mv); - mv - }) - .collect() -} - -fn temp_dir(name: &str) -> PathBuf { - let sequence = TEST_DIR.fetch_add(1, Ordering::Relaxed); - let path = std::env::temp_dir().join(format!( - "cp-repertoire-{}-{sequence}-{name}", - std::process::id() - )); - let _ = std::fs::remove_dir_all(&path); - std::fs::create_dir_all(&path).unwrap(); - path -} - -#[test] -fn prefix_branch_dedup_and_annotations_merge_without_touching_source() { - let source = game("1. e4 {old} $1 c5 2. Nf3 d6 3. Bb5+ (3. d4 cxd4 4. Nxd4 (4. Qxd4)) *"); - let original = source.to_pgn(); - let canonical = source.canonical_tree(); - let mut library = Library::default(); - let id = library.create_empty("Sicilian").unwrap(); - - let prefix_end = source.mainline()[3]; - let report = library.add_prefix(&id, &source, prefix_end).unwrap(); - assert_eq!(report.added_nodes, 4); - let snapshot = library.repertoire(&id).unwrap().game(); - assert_eq!(snapshot.mainline().len(), 4); - assert_eq!( - snapshot.game_move(snapshot.mainline()[2]).unwrap().san, - "Nf3" - ); - assert!(!snapshot.to_pgn().contains("Bb5")); - assert!(!snapshot.to_pgn().contains("cxd4")); - - let annotated = game("1. e4 {new} $2 c5 2. Nf3 Nc6 3. d4 *"); - library.add_game(&id, &annotated).unwrap(); - library.add_game(&id, &annotated).unwrap(); - library.add_game(&id, &source).unwrap(); - let merged = library.repertoire(&id).unwrap().game(); - let e4 = merged.main_child(NodeId::ROOT).unwrap(); - assert_eq!(merged.node(e4).unwrap().comments_after(), ["old", "new"]); - assert_eq!( - merged - .node(e4) - .unwrap() - .nags() - .iter() - .map(|n| n.0) - .collect::>(), - [1, 2] - ); - let moves = play(&merged, &["e2e4", "c7c5", "g1f3"]); - let c5 = merged.find_child(e4, moves[1]).unwrap(); - let nf3 = merged.find_child(c5, moves[2]).unwrap(); - assert_eq!(merged.children(nf3).len(), 2); - assert_eq!( - library - .repertoire(&id) - .unwrap() - .game() - .attached_nodes() - .len(), - 12 - ); - - let before = library.repertoire(&id).unwrap().pgn.clone(); - let repeat = library.add_game(&id, &source).unwrap(); - assert_eq!(repeat.added_nodes, 0); - assert_eq!(library.repertoire(&id).unwrap().pgn, before); - assert_eq!(source.to_pgn(), original); - assert_eq!(source.canonical_tree(), canonical); -} - -#[test] -fn different_starts_are_rejected_and_fullmove_zero_is_preserved() { - let fen_game = - game("[SetUp \"1\"]\n[FEN \"4k3/8/8/8/8/8/4P3/4K2R b - - 0 0\"]\n\n1... Ke7 2. e4 *"); - let mut library = Library::default(); - let id = library.create("Black to move", &fen_game).unwrap(); - assert_eq!( - library - .repertoire(&id) - .unwrap() - .game() - .start() - .original_fen(), - Some("4k3/8/8/8/8/8/4P3/4K2R b - - 0 0") - ); - let before = library.repertoire(&id).unwrap().pgn.clone(); - assert!(matches!( - library.add_game(&id, &game("1. e4 *")), - Err(RepertoireError::DifferentStart { .. }) - )); - assert_eq!(library.repertoire(&id).unwrap().pgn, before); -} - -#[test] -fn null_and_unparsed_segments_survive_but_are_not_candidates() { - let source = game("1. e4 -- (1... e5) 2. d4 *"); - let mut library = Library::default(); - let id = library.create("Teaching", &game("1. e4 e5 *")).unwrap(); - library.add_game(&id, &source).unwrap(); - let stored = library.repertoire(&id).unwrap(); - assert!(stored.pgn.contains("--")); - let tree = RepertoireTree::new(stored); - let stored_game = tree.game(); - let e4 = stored_game.main_child(NodeId::ROOT).unwrap(); - let null = stored_game - .children(e4) - .iter() - .copied() - .find(|node| { - stored_game - .game_move(*node) - .is_some_and(|mv| mv.kind == MoveKind::Null) - }) - .unwrap(); - assert!(tree.candidates(null).is_empty()); - assert!(tree.candidates(e4).iter().any(|c| c.uci == "e7e5")); - assert!(tree.candidates(e4).iter().all(|c| c.uci != "0000")); - - let illegal = game("1. e4 e5 2. e5 *"); - assert!(illegal.canonical_tree().contains("U[")); - let mut illegal_library = Library::default(); - let illegal_id = illegal_library.create("Raw", &illegal).unwrap(); - let roundtrip = illegal_library.repertoire(&illegal_id).unwrap().game(); - assert_eq!(roundtrip.canonical_tree(), illegal.canonical_tree()); - assert!( - illegal_library - .add_game(&illegal_id, &game("1. e4 e5 2. Nf3 *")) - .is_ok() - ); - let mut target = Library::default(); - let target_id = target.create("Target", &game("1. e4 e5 *")).unwrap(); - let target_before = target.repertoire(&target_id).unwrap().pgn.clone(); - assert!(target.add_game(&target_id, &illegal).is_err()); - assert_eq!(target.repertoire(&target_id).unwrap().pgn, target_before); - - let mut empty = Library::default(); - let empty_id = empty.create_empty("Empty").unwrap(); - empty.add_game(&empty_id, &illegal).unwrap(); - assert_eq!( - empty.repertoire(&empty_id).unwrap().game().canonical_tree(), - illegal.canonical_tree() - ); - - let mut prefixes = Library::default(); - let prefix_id = prefixes.create("Prefix", &game("1. e4 *")).unwrap(); - let null_node = source.mainline()[1]; - prefixes.add_prefix(&prefix_id, &source, null_node).unwrap(); - let prefix_pgn = &prefixes.repertoire(&prefix_id).unwrap().pgn; - assert!(prefix_pgn.contains("--")); - assert!(!prefix_pgn.contains("d4")); -} - -#[test] -fn transpositions_share_candidates_but_keep_both_pgn_paths() { - 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 stored = library.repertoire(&id).unwrap(); - let tree = RepertoireTree::new(stored); - let game = tree.game(); - let first_path = ["d2d4", "d7d5", "g1f3", "g8f6"]; - let second_path = ["g1f3", "d7d5", "d2d4", "g8f6"]; - let first = tree.node_at_path(&first_path.map(str::to_owned)).unwrap(); - let second = tree.node_at_path(&second_path.map(str::to_owned)).unwrap(); - assert_ne!(first, second); - assert_eq!(tree.position_key(first), tree.position_key(second)); - assert!(tree.transpositions(first).contains(&second)); - assert!(tree.candidates(second).iter().any(|c| c.uci == "g2g3")); - let pgn = stored.pgn.clone(); - assert!(pgn.contains("d4")); - assert!(pgn.contains("Nf3")); - assert_eq!(game.attached_nodes().len(), 10); -} - -#[test] -fn fen4_ignores_counters_but_distinguishes_side_castling_and_legal_ep() { - let position = |fen: &str| StartPosition::from_fen(fen).unwrap().position().clone(); - let a = position("4k3/8/8/8/8/8/4P3/4K2R w K - 0 1"); - let counters = position("4k3/8/8/8/8/8/4P3/4K2R w K - 37 91"); - let black = position("4k3/8/8/8/8/8/4P3/4K2R b K - 0 1"); - let no_rights = position("4k3/8/8/8/8/8/4P3/4K2R w - - 0 1"); - assert_eq!(fen4(&a), fen4(&counters)); - assert_ne!(fen4(&a), fen4(&black)); - assert_ne!(fen4(&a), fen4(&no_rights)); - - let legal_ep = position("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 2"); - let no_ep = position("4k3/8/8/3pP3/8/8/8/4K3 w - - 0 2"); - let illegal_ep = position("4k3/8/8/3p4/8/8/8/4K3 w - d6 0 2"); - let illegal_no_ep = position("4k3/8/8/3p4/8/8/8/4K3 w - - 0 2"); - assert_ne!(fen4(&legal_ep), fen4(&no_ep)); - assert_eq!(fen4(&illegal_ep), fen4(&illegal_no_ep)); -} - -#[test] -fn library_crud_depth_and_disable_are_persistent_data() { - let mut library = Library::default(); - let id = library.create(" Name ", &game("1. e4 e5 *")).unwrap(); - assert_eq!(library.repertoire(&id).unwrap().name, "Name"); - assert_eq!(library.repertoire(&id).unwrap().max_plies, 20); - library.rename(&id, "Renamed").unwrap(); - assert!(library.rename(&id, " ").is_err()); - let repertoire = library.repertoire_mut(&id).unwrap(); - repertoire.set_max_plies(1); - repertoire - .set_prefix_disabled(&["e2e4".into()], true) - .unwrap(); - repertoire - .set_prefix_disabled(&["e2e4".into()], true) - .unwrap(); - assert_eq!(repertoire.disabled_prefixes.len(), 1); - assert!( - RepertoireTree::new(repertoire) - .candidates(NodeId::ROOT) - .is_empty() - ); - assert_eq!(library.delete(&id).unwrap().name, "Renamed"); - assert!(library.repertoire(&id).is_none()); -} - -#[test] -fn prefix_ignores_unparsed_tail_after_the_selected_node() { - let source = game("1. e4 e4 2. d4 *"); - assert_eq!(source.mainline().len(), 1); - assert!(!source.mainline().is_empty()); - let mut library = Library::default(); - let id = library.create("Target", &game("1. e4 c5 *")).unwrap(); - let before = library.repertoire(&id).unwrap().pgn.clone(); - - let report = library - .add_prefix(&id, &source, source.mainline()[0]) - .unwrap(); - - assert_eq!(report.added_nodes, 0); - assert_eq!(library.repertoire(&id).unwrap().pgn, before); -} - -#[test] -fn library_store_roundtrip_errors_and_conflicts_are_visible() { - let dir = temp_dir("library-store"); - let path = dir.join("repertoires.json"); - let store = LibraryStore::new(&path); - let mut first = store.load().unwrap(); - let id = first.create("One", &game("1. e4 *")).unwrap(); - store.save(&mut first).unwrap(); - assert_eq!(first.revision, 1); - assert_eq!(store.load().unwrap().repertoire(&id).unwrap().name, "One"); - - let mut stale = Library::default(); - stale.create("Stale", &game("1. d4 *")).unwrap(); - assert!(matches!( - store.save(&mut stale), - Err(StoreError::Conflict { .. }) - )); - let disk = store.load().unwrap(); - assert_eq!(disk.repertoires.len(), 1); - assert_eq!(disk.repertoires[0].name, "One"); - - std::fs::write(&path, b"{broken").unwrap(); - assert!(store.load().is_err()); - std::fs::write( - &path, - serde_json::to_vec(&json!({"version": 99, "repertoires": []})).unwrap(), - ) - .unwrap(); - assert!(matches!( - store.load(), - Err(StoreError::UnsupportedVersion { .. }) - )); - - let blocker = dir.join("not-a-directory"); - std::fs::write(&blocker, b"file").unwrap(); - let blocked = LibraryStore::new(blocker.join("library.json")); - let mut library = Library::default(); - assert!(blocked.save(&mut library).is_err()); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn legacy_roundtrip_backup_migration_and_stats_conflict_preserve_data() { - let dir = temp_dir("legacy-store"); - let legacy_path = dir.join("training.json"); - let new_path = dir.join("repertoire-training.json"); - let start = crate::line_key(&Chess::default(), &play(&Game::new(), &["e2e4", "c7c5"])); - let other = crate::line_key(&Chess::default(), &play(&Game::new(), &["e2e4", "e7e5"])); - let legacy_bytes = serde_json::to_vec_pretty(&json!({ - (start.clone()): {"runs": 4, "last": 2, "best": 0, "clean_streak": 0, "recent": [[2, false]], "last_date": "2026-10-01", "unknown": 7}, - (other): {"runs": 2, "last": 0, "best": 0, "clean_streak": 2, "recent": [], "last_date": "2026-10-02"}, - "future-key": {"arbitrary": [1, 2, 3]} - })) - .unwrap(); - std::fs::write(&legacy_path, &legacy_bytes).unwrap(); - let store = StatsStore::with_legacy(&new_path, &legacy_path); - let mut stats = store.load().unwrap(); - assert_eq!(stats.legacy_lines.len(), 3); - assert!(stats.move_stats.is_empty()); - assert_eq!(stats.legacy_lines[&start]["runs"], 4); - assert_eq!(stats.legacy_lines[&start]["unknown"], 7); - - let mut library = Library::default(); - let report = library.migrate_legacy_lines(&stats.legacy_lines); - assert_eq!(report.repertoires, 1); - assert_eq!(report.lines, 2); - assert_eq!(report.skipped, ["future-key"]); - let after_first = library.repertoires[0].pgn.clone(); - let id = library.repertoires[0].id.clone(); - library.migrate_legacy_lines(&stats.legacy_lines); - assert_eq!(library.repertoires.len(), 1); - assert_eq!(library.repertoires[0].id, id); - assert_eq!(library.repertoires[0].pgn, after_first); - - let mut stale = stats.clone(); - store.save(&mut stats).unwrap(); - assert_eq!(std::fs::read(&legacy_path).unwrap(), legacy_bytes); - let backup = dir.join("training.json.before-repertoire-v2"); - assert_eq!(std::fs::read(backup).unwrap(), legacy_bytes); - assert!(matches!( - store.save(&mut stale), - Err(StoreError::Conflict { .. }) - )); - let reopened = store.load().unwrap(); - assert_eq!(reopened.legacy_lines, stats.legacy_lines); - assert!(reopened.move_stats.is_empty()); - - std::fs::write(&legacy_path, b"{bad").unwrap(); - let missing_new = StatsStore::with_legacy(dir.join("other.json"), &legacy_path); - assert!(missing_new.load().is_err()); - assert_eq!(std::fs::read(&legacy_path).unwrap(), b"{bad"); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -fn stats_store_write_failure_does_not_replace_legacy_or_report_success() { - let dir = temp_dir("write-error"); - let legacy = dir.join("training.json"); - std::fs::write(&legacy, b"{}").unwrap(); - let blocker = dir.join("blocked"); - std::fs::write(&blocker, b"file").unwrap(); - let store = StatsStore::with_legacy(blocker.join("stats.json"), &legacy); - let mut stats = StatsData::default(); - assert!(store.save(&mut stats).is_err()); - assert_eq!(std::fs::read(&legacy).unwrap(), b"{}"); - let _ = std::fs::remove_dir_all(dir); -} - -#[test] -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"; - std::fs::write(&source_path, bytes).unwrap(); - let source = game("1. e4 c5 2. Nf3 d6 3. Bb5+ *"); - let mut library = Library::default(); - let id = library.create_empty("Snapshot").unwrap(); - let at = source.mainline()[3]; - library.add_prefix(&id, &source, at).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 deleted file mode 100644 index ffeab12..0000000 --- a/crates/trainer/src/repertoire/tree.rs +++ /dev/null @@ -1,306 +0,0 @@ -use std::collections::{BTreeMap, BTreeSet}; - -use chess_core::shakmaty::fen::Fen; -use chess_core::shakmaty::{CastlingMode, Chess, EnPassantMode, Position}; -use chess_core::{Game, MoveKind, NodeId}; - -use super::model::Repertoire; -use super::scope::TrainingScope; - -/// The position identity used by opening training: board, side, castling rights and -/// legal en passant. Halfmove and fullmove counters deliberately do not participate. -pub fn fen4(position: &Chess) -> String { - Fen::from_position(position, EnPassantMode::Legal) - .to_string() - .split(' ') - .take(4) - .collect::>() - .join(" ") -} - -#[derive(Clone, Debug)] -pub struct Candidate { - pub uci: String, -} - -#[derive(Clone, Debug)] -struct IndexedNode { - fen4: String, - path: Option>, -} - -/// A PGN tree plus derived position/transposition information. Node IDs are used only -/// while this value is alive and are never persisted in statistics or settings. -#[derive(Clone, Debug)] -pub struct RepertoireTree { - game: Game, - max_plies: u32, - disabled_prefixes: Vec>, - indexed: BTreeMap, - positions: BTreeMap>, -} - -impl RepertoireTree { - pub fn new(repertoire: &Repertoire) -> Self { - Self::from_game( - repertoire.game(), - repertoire.max_plies, - repertoire.disabled_prefixes.clone(), - ) - } - - pub fn from_game(game: Game, max_plies: u32, disabled_prefixes: Vec>) -> Self { - let mut indexed = BTreeMap::new(); - let mut positions: BTreeMap> = BTreeMap::new(); - for id in game.attached_nodes() { - let Some(position) = game.position(id) else { - continue; - }; - let key = fen4(position); - let path = normal_path(&game, id); - positions.entry(key.clone()).or_default().push(id); - indexed.insert(id, IndexedNode { fen4: key, path }); - } - Self { - game, - max_plies, - disabled_prefixes, - indexed, - positions, - } - } - - pub fn game(&self) -> &Game { - &self.game - } - - pub fn root(&self) -> NodeId { - self.game.root() - } - - pub fn position(&self, at: NodeId) -> Option<&Chess> { - self.game.position(at) - } - - pub fn position_key(&self, at: NodeId) -> Option<&str> { - self.indexed.get(&at).map(|n| n.fen4.as_str()) - } - - pub fn path(&self, at: NodeId) -> Option<&[String]> { - self.indexed.get(&at)?.path.as_deref() - } - - pub fn transpositions(&self, at: NodeId) -> &[NodeId] { - self.position_key(at) - .and_then(|key| self.positions.get(key)) - .map(Vec::as_slice) - .unwrap_or(&[]) - } - - pub fn is_trainable_path(&self, at: NodeId) -> bool { - let Some(node) = self.game.node(at) else { - return false; - }; - let Some(path) = self.path(at) else { - return false; - }; - node.ply() <= self.max_plies && !self.disabled(path) - } - - /// Enabled children of the current path and all its FEN4 transpositions. A direct - /// child is preferred so ordinary paths stay on their own PGN branch; otherwise the - /// first PGN path is the canonical continuation. Null and unparsed-after-null paths - /// never contribute candidates. - pub fn candidates(&self, at: NodeId) -> Vec { - self.candidates_impl(at, None) - } - - fn candidates_impl(&self, at: NodeId, scope: Option<&TrainingScope>) -> Vec { - if !self.is_trainable_path(at) - || self - .game - .node(at) - .is_none_or(|node| node.ply() >= self.max_plies) - { - return Vec::new(); - } - let mut nodes = Vec::new(); - nodes.push(at); - nodes.extend( - self.transpositions(at) - .iter() - .copied() - .filter(|node| *node != at), - ); - let mut seen = BTreeSet::new(); - let mut out = Vec::new(); - for parent in nodes { - let Some(parent_node) = self.game.node(parent) else { - continue; - }; - if !self.is_trainable_path(parent) - || parent_node.ply() >= self.max_plies - || !self.scope_allows_parent(parent, scope) - { - continue; - } - for child in self.game.children(parent) { - let Some(game_move) = self.game.game_move(*child) else { - continue; - }; - let MoveKind::Normal(mv) = game_move.kind else { - continue; - }; - if !self.is_trainable_path(*child) || !self.scope_allows_child(*child, scope) { - continue; - } - let uci = mv.to_uci(CastlingMode::Standard).to_string(); - if seen.insert(uci.clone()) { - out.push(Candidate { uci }); - } - } - } - out - } - - pub fn candidate(&self, at: NodeId, uci: &str) -> Option { - self.candidates(at) - .into_iter() - .find(|candidate| candidate.uci == uci) - } - - /// 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 { - let mut current = self.root(); - let mut position = self.game.position(current)?.clone(); - for uci in path { - let mv = uci - .parse::() - .ok()? - .to_move(&position) - .ok()?; - current = self.game.find_child(current, mv)?; - position.play_unchecked(mv); - } - self.is_trainable_path(current).then_some(current) - } - - pub fn scope_anchor(&self, scope: &TrainingScope) -> Result { - if let Some(end) = &scope.end_prefix - && (end.len() < scope.prefix.len() || !end.starts_with(&scope.prefix)) - { - return Err("scope end must extend the selected prefix".into()); - } - let anchor = if scope.prefix.is_empty() { - self.root() - } else { - self.node_at_path(scope.parent_prefix()) - .ok_or_else(|| "scope parent is missing, disabled, or beyond depth".to_owned())? - }; - if let Some(selected) = scope.prefix.last() - && self.candidate(anchor, selected).is_none() - { - return Err("scope move is missing, disabled, or beyond depth".into()); - } - if let Some(end) = &scope.end_prefix - && self.node_at_path(end).is_none() - { - return Err("scope end is missing, disabled, or beyond depth".into()); - } - Ok(anchor) - } - - /// Streams the routes explicitly present in PGN, without importing continuations - /// from other paths that reach the same position. - pub fn visit_source_paths( - &self, - scope: &TrainingScope, - mut visit: impl FnMut(&[String]) -> std::ops::ControlFlow<()>, - ) -> Result<(), String> { - let anchor = self.scope_anchor(scope)?; - let _ = self.visit_source(anchor, scope, &mut Vec::new(), &mut visit); - Ok(()) - } - - fn visit_source( - &self, - at: NodeId, - scope: &TrainingScope, - current: &mut Vec, - visit: &mut impl FnMut(&[String]) -> std::ops::ControlFlow<()>, - ) -> std::ops::ControlFlow<()> { - let mut continued = false; - if scope.parent_prefix().len() + current.len() < self.max_plies as usize { - for child in self.game.children(at) { - let Some(game_move) = self.game.game_move(*child) else { - continue; - }; - let MoveKind::Normal(mv) = game_move.kind else { - continue; - }; - if !self.is_trainable_path(*child) || !self.scope_allows_child(*child, Some(scope)) - { - continue; - } - continued = true; - current.push(mv.to_uci(CastlingMode::Standard).to_string()); - let result = self.visit_source(*child, scope, current, visit); - current.pop(); - result?; - } - } - if current.is_empty() || continued { - std::ops::ControlFlow::Continue(()) - } else { - visit(current) - } - } - - fn scope_allows_parent(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool { - let Some(scope) = scope else { - return true; - }; - let Some(path) = self.path(at) else { - return false; - }; - path == scope.parent_prefix() || self.path_in_scope(path, scope) - } - - fn scope_allows_child(&self, at: NodeId, scope: Option<&TrainingScope>) -> bool { - let Some(scope) = scope else { - return true; - }; - self.path(at) - .is_some_and(|path| self.path_in_scope(path, scope)) - } - - fn path_in_scope(&self, path: &[String], scope: &TrainingScope) -> bool { - if !path.starts_with(&scope.prefix) { - return false; - } - scope - .end_prefix - .as_ref() - .is_none_or(|end| path.len() <= end.len()) - } - - fn disabled(&self, path: &[String]) -> bool { - self.disabled_prefixes - .iter() - .any(|prefix| path.starts_with(prefix)) - } -} - -fn normal_path(game: &Game, at: NodeId) -> Option> { - let mut path = Vec::new(); - for node in game.path(at).into_iter().skip(1) { - match game.game_move(node).map(|m| m.kind) { - Some(MoveKind::Normal(mv)) => { - path.push(mv.to_uci(CastlingMode::Standard).to_string()); - } - Some(MoveKind::Null) | None => return None, - } - } - Some(path) -} diff --git a/crates/uci/Cargo.toml b/crates/uci/Cargo.toml index edf7801..9c9253f 100644 --- a/crates/uci/Cargo.toml +++ b/crates/uci/Cargo.toml @@ -4,20 +4,13 @@ version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true -description = "UCI chess engine supervisor: a process, or a Web Worker in a browser (no UI dependencies)" +description = "UCI chess engine process supervisor (no UI dependencies)" [dependencies] thiserror.workspace = true -web-time.workspace = true - -# The engine as a Web Worker in a browser. -[target.'cfg(target_family = "wasm")'.dependencies] -wasm-bindgen = "0.2.129" -js-sys = "0.3" -web-sys = { version = "0.3", features = ["Worker", "MessageEvent", "ErrorEvent"] } [target.'cfg(unix)'.dependencies] -# nice(2) for EngineConfig::nice, prctl(2) for kill_with_parent (std has neither). +# nice(2) for EngineConfig::nice (std has no way to lower a child's priority). libc = "0.2" # Test helper: deterministic fake UCI engine used by tests/ via CARGO_BIN_EXE_fake_uci. @@ -26,9 +19,3 @@ name = "fake_uci" path = "src/bin/fake_uci.rs" test = false doc = false - -# tests/worker.rs: the worker transport in a browser (docs/dev/web.md). -[target.'cfg(target_family = "wasm")'.dev-dependencies] -wasm-bindgen-test = "0.3" -wasm-bindgen-futures = "0.4" -web-sys = { version = "0.3", features = ["Window", "Blob", "BlobPropertyBag", "Url"] } diff --git a/crates/uci/src/bin/fake_uci.rs b/crates/uci/src/bin/fake_uci.rs index 9eed3e5..c862097 100644 --- a/crates/uci/src/bin/fake_uci.rs +++ b/crates/uci/src/bin/fake_uci.rs @@ -24,16 +24,6 @@ //! --exit-after-go N on the N-th `go`, print one info and exit(1) //! --mate multipv 1 = mate 3, multipv 2 = mate -2 //! --ignore-quit ignore `quit` (must be killed) -//! --hash-memory scores depend on the position and on the searches made -//! since the last `ucinewgame` (as a hash kept between them) -//! --searchmoves honour `go ... searchmoves M...`: M's first move is the -//! best move, scored 30 cp lower (a worse move) -//! --shallow N MOVE `go nodes n` with n < N (no `searchmoves`): MOVE is the -//! best move (a shallow search choosing another move) -//! --ignore-nodes `go nodes N` searches until `stop` (as Rodent does) -//! --answer MARKER TAIL `go` in the position of MARKER answers at once with -//! `info depth 10 multipv 1 score TAIL` and the bestmove of -//! the first move after `pv` in TAIL (repeatable) //! //! Protocol violations by the GUI (`position`/`go`/`setoption`/`ucinewgame` //! during a search) are reported as `info string ERROR ...`. @@ -61,11 +51,6 @@ struct Cfg { exit_after_go: Option, mate: bool, ignore_quit: bool, - hash_memory: bool, - searchmoves: bool, - shallow: Option<(u64, String)>, - answers: Vec<(String, String)>, - ignore_nodes: bool, } fn parse_args() -> Cfg { @@ -94,18 +79,6 @@ fn parse_args() -> Cfg { "--exit-after-go" => c.exit_after_go = Some(num(args.next()) as u32), "--mate" => c.mate = true, "--ignore-quit" => c.ignore_quit = true, - "--hash-memory" => c.hash_memory = true, - "--searchmoves" => c.searchmoves = true, - "--shallow" => { - let n = num(args.next()); - c.shallow = args.next().map(|m| (n, m)); - } - "--ignore-nodes" => c.ignore_nodes = true, - "--answer" => { - if let (Some(m), Some(t)) = (args.next(), args.next()) { - c.answers.push((m, t)); - } - } other => { eprintln!("fake_uci: unknown flag {other}"); std::process::exit(2); @@ -119,8 +92,6 @@ struct Search { marker: String, depth: u32, max_depth: Option, - /// Added to every score (`--hash-memory`). - bias: i32, } fn out(line: &str) { @@ -129,14 +100,14 @@ fn out(line: &str) { let _ = o.flush(); } -fn info_lines(cfg: &Cfg, marker: &str, depth: u32, multipv: u32, bias: i32) { +fn info_lines(cfg: &Cfg, marker: &str, depth: u32, multipv: u32) { for k in 1..=multipv { let score = if cfg.mate && k == 1 { "mate 3".to_string() } else if cfg.mate && k == 2 { "mate -2".to_string() } else { - format!("cp {}", 50 - 10 * k as i32 + bias) + format!("cp {}", 50 - 10 * k as i32) }; out(&format!( "info depth {depth} seldepth {} multipv {k} score {score} nodes {} nps 100000 \ @@ -188,8 +159,6 @@ fn main() { let mut marker = "startpos".to_string(); let mut search: Option = None; let mut gos = 0u32; - // Searches since the last `ucinewgame` (`--hash-memory`). - let mut since_new_game = 0i32; let mut hung = false; let interval = Duration::from_millis(cfg.info_interval.max(1)); @@ -210,7 +179,7 @@ fn main() { // Search tick. if let Some(s) = search.as_mut() { s.depth += 1; - info_lines(&cfg, &s.marker, s.depth, multipv, s.bias); + info_lines(&cfg, &s.marker, s.depth, multipv); if s.max_depth.is_some_and(|m| s.depth >= m) { out(&format!("bestmove {} ponder e7e5", bm(&s.marker))); search = None; @@ -273,7 +242,6 @@ fn main() { if search.is_some() { out("info string ERROR ucinewgame during search"); } - since_new_game = 0; } Some("position") => { if search.is_some() { @@ -292,18 +260,8 @@ fn main() { out("info string ERROR go during search"); } gos += 1; - if let Some((_, tail)) = cfg.answers.iter().find(|(m, _)| *m == marker) { - out(&format!("info depth 10 multipv 1 score {tail}")); - let best = tail - .split_whitespace() - .skip_while(|&t| t != "pv") - .nth(1) - .unwrap_or("0000"); - out(&format!("bestmove {best}")); - continue; - } if cfg.exit_after_go == Some(gos) { - info_lines(&cfg, &marker, 1, multipv, 0); + info_lines(&cfg, &marker, 1, multipv); std::process::exit(1); } let max_depth = toks @@ -312,39 +270,11 @@ fn main() { .and_then(|p| toks.get(p + 1)) .and_then(|v| v.parse().ok()) // `go nodes N`: a short search that ends by itself, like a real one. - .or_else(|| (toks.contains(&"nodes") && !cfg.ignore_nodes).then_some(3)); - since_new_game += 1; - let mut bias = if cfg.hash_memory { - let of_position = marker.bytes().map(i32::from).sum::() % 97; - of_position + 1000 * since_new_game - } else { - 0 - }; - let among = toks - .iter() - .position(|&t| t == "searchmoves") - .and_then(|p| toks.get(p + 1)); - let nodes: Option = toks - .iter() - .position(|&t| t == "nodes") - .and_then(|p| toks.get(p + 1)) - .and_then(|v| v.parse().ok()); - let mut shown = marker.clone(); - match (among, &cfg.shallow) { - (Some(m), _) if cfg.searchmoves => { - shown = (*m).to_owned(); - bias -= 30; - } - (None, Some((below, best))) if nodes.is_some_and(|n| n < *below) => { - shown = best.clone(); - } - _ => {} - } + .or_else(|| toks.contains(&"nodes").then_some(3)); search = Some(Search { - marker: shown, + marker: marker.clone(), depth: 0, max_depth, - bias, }); } Some("stop") => { @@ -354,12 +284,12 @@ fn main() { continue; } for i in 0..cfg.stale_after_stop { - info_lines(&cfg, &s.marker, s.depth + 1 + i, multipv, s.bias); + info_lines(&cfg, &s.marker, s.depth + 1 + i, multipv); } std::thread::sleep(Duration::from_millis(cfg.bestmove_delay)); out(&format!("bestmove {} ponder e7e5", bm(&s.marker))); for i in 0..cfg.info_after_bestmove { - info_lines(&cfg, &s.marker, s.depth + 100 + i, multipv, s.bias); + info_lines(&cfg, &s.marker, s.depth + 100 + i, multipv); } } Some("quit") if !cfg.ignore_quit => return, diff --git a/crates/uci/src/process.rs b/crates/uci/src/engine.rs similarity index 53% rename from crates/uci/src/process.rs rename to crates/uci/src/engine.rs index 76912a6..6a4b726 100644 --- a/crates/uci/src/process.rs +++ b/crates/uci/src/engine.rs @@ -1,6 +1,4 @@ -//! The engine as a child process: started without a shell, its stdout and stderr -//! read by two threads, the protocol ([`crate::protocol`]) driven by a supervisor -//! thread that waits for input with the session's deadline. +//! Engine process, handshake and the supervisor thread. use std::collections::VecDeque; use std::ffi::{OsStr, OsString}; @@ -14,14 +12,62 @@ use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use crate::error::EngineError; -use crate::events::{EngineEvent, TerminationReason, Waker}; -use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line}; -use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; +use crate::parse::{EngineLine, parse_line}; +use crate::types::{ + EngineInfo, EnginePosition, OptionKind, SearchId, SearchInfo, SearchLimits, Timeouts, +}; + +/// Callback invoked (from the supervisor thread) after every new event; the +/// UI passes `ctx.request_repaint()` here. +pub type Waker = Box; /// Maximum stored length of one output line; longer lines are truncated. const MAX_LINE_BYTES: usize = 64 * 1024; /// Number of stderr lines kept for diagnostics. const STDERR_TAIL_LINES: usize = 256; +/// Maximum number of `Warning` events emitted per engine (flood protection). +const MAX_WARNINGS: usize = 100; + +/// Event delivered to the UI. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum EngineEvent { + /// `position` + `go` for this id were sent to the engine. + SearchStarted { search_id: SearchId }, + /// The request was replaced by a newer one (or cancelled by `stop`) + /// before it was sent to the engine; no events will follow for this id. + Superseded { search_id: SearchId }, + /// Search output. Only lines with a score or a PV are forwarded. + Info { + search_id: SearchId, + info: SearchInfo, + }, + /// Final `bestmove` of a started search. Exactly one per `SearchStarted` + /// unless the engine terminates first. + BestMove { + search_id: SearchId, + best: Option, + ponder: Option, + }, + /// `info string`, attributed to the running search if any. + InfoString { + search_id: Option, + text: String, + }, + /// Malformed or unexpected engine output; the line was skipped. + Warning(String), + /// The supervisor has stopped; the handle is no longer usable. + Terminated(TerminationReason), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TerminationReason { + /// `quit()` or drop of the handle. + Quit { status: Option }, + /// The process exited on its own (crash, EOF on stdout, write failure). + Exited { status: Option }, + /// The engine did not answer `stop` or `isready` in time and was killed. + Hung { waiting_for: &'static str }, +} /// Spawn configuration. #[derive(Debug, Clone)] @@ -38,10 +84,6 @@ pub struct EngineConfig { /// Variables added to the engine's environment (Rodent IV on Android finds its /// personalities and books by `RODENT4HOME`). pub env: Vec<(OsString, OsString)>, - /// Linux and Android: the engine is killed when the thread that started it ends - /// (`PR_SET_PDEATHSIG`), and so when the program ends, even in the middle of the - /// handshake. For engines whose starting thread lives as long as they should. - pub kill_with_parent: bool, } impl EngineConfig { @@ -53,7 +95,6 @@ impl EngineConfig { timeouts: Timeouts::default(), nice: 0, env: Vec::new(), - kill_with_parent: false, } } } @@ -87,11 +128,23 @@ impl Engine { enum Input { Cmd(Cmd), - Quit, Stdout(String), StdoutClosed, } +enum Cmd { + Search { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, + }, + Stop, + /// A complete `setoption ...` / `ucinewgame` line, applied while idle. + Setup(String), + Quit, +} + /// Handle owned by the UI. Dropping it quits (and if needed kills) the engine. pub struct EngineHandle { info: EngineInfo, @@ -180,7 +233,16 @@ impl EngineHandle { limits: SearchLimits, among: Vec, ) -> Result<(), EngineError> { - self.send(Cmd::search(position, search_id, limits, among)?) + position.validate()?; + if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) { + return Err(EngineError::InvalidInput(format!("not a move: {bad:?}"))); + } + self.send(Cmd::Search { + position, + id: search_id, + limits, + among, + }) } /// Stops the running search (its `BestMove` still arrives) and cancels a @@ -194,7 +256,51 @@ impl EngineHandle { /// search boundary (UCI forbids `setoption` during a search) — to see the /// effect on the current analysis, call [`Self::analyze`] again. pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { - self.send(Cmd::Setup(option_line(&self.info, name, value)?)) + let opt = self + .info + .option(name) + .ok_or_else(|| EngineError::UnknownOption(name.to_string()))?; + let bad = |reason: String| EngineError::InvalidOptionValue { + name: opt.name.clone(), + reason, + }; + if let Some(v) = value + && v.chars().any(char::is_control) + { + return Err(bad("control characters in value".into())); + } + let value = match (&opt.kind, value) { + (OptionKind::Button, None) => None, + (OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())), + (_, None) => return Err(bad("value required".into())), + (OptionKind::Check { .. }, Some(v)) => match v { + "true" | "false" => Some(v.to_string()), + _ => return Err(bad(format!("expected true/false, got {v:?}"))), + }, + (OptionKind::Spin { min, max, .. }, Some(v)) => { + let n: i64 = v + .trim() + .parse() + .map_err(|_| bad(format!("not an integer: {v:?}")))?; + if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { + return Err(bad(format!("{n} outside {min:?}..={max:?}"))); + } + Some(n.to_string()) + } + (OptionKind::Combo { vars, .. }, Some(v)) => { + let var = vars + .iter() + .find(|x| x.eq_ignore_ascii_case(v)) + .ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?; + Some(var.clone()) + } + (OptionKind::String { .. }, Some(v)) => Some(v.to_string()), + }; + let line = match value { + Some(v) => format!("setoption name {} value {}", opt.name, v), + None => format!("setoption name {}", opt.name), + }; + self.send(Cmd::Setup(line)) } pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { @@ -231,7 +337,7 @@ impl EngineHandle { fn shutdown(&mut self) -> Option { if let Some(join) = self.supervisor.take() { - let _ = self.tx.send(Input::Quit); + let _ = self.tx.send(Input::Cmd(Cmd::Quit)); // The supervisor bounds its own shutdown by stop+quit timeouts; // the margin covers scheduling. If it is still stuck (e.g. a // blocked write), kill the process from here. @@ -312,23 +418,14 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result Result done, + let mut warnings = Vec::new(); + let handshake = handshake(&mut stdin, &rx, &cfg.timeouts, &mut warnings); + let info = match handshake { + Ok(info) => info, Err(mut e) => { let _ = child.kill(); let status = child.wait().ok(); @@ -419,18 +518,19 @@ fn spawn_impl(cfg: EngineConfig, waker: Waker) -> Result(); let mut sup = Supervisor { - pipes: Pipes { - stdin, - events: ev_tx, - waker, - }, - session: Session::new(cfg.timeouts), + stdin, child: Arc::clone(&child), + events: ev_tx, + waker, alive: Arc::clone(&alive), timeouts: cfg.timeouts, + state: State::Idle, + pending: None, + pending_setup: Vec::new(), + warnings: 0, }; for w in warnings { - sup.session.warn(w, &mut sup.pipes); + sup.warn(w); } let supervisor = thread::Builder::new() .name(format!("uci-supervisor-{pid}")) @@ -462,13 +562,12 @@ fn write_line(stdin: &mut ChildStdin, line: &str) -> std::io::Result<()> { stdin.flush() } -/// The handshake over the pipes: every line read goes to [`Handshake`], until it is -/// complete or its deadline passes. fn handshake( stdin: &mut ChildStdin, rx: &Receiver, t: &Timeouts, -) -> Result<(EngineInfo, Vec), EngineError> { + warnings: &mut Vec, +) -> Result { let exited = || EngineError::ProcessExited { status: None, stderr: Vec::new(), @@ -480,20 +579,68 @@ fn handshake( EngineError::Io(e) } }; - let mut hs = Handshake::new(t, Instant::now()); - write_line(stdin, Handshake::FIRST_LINE).map_err(io)?; + write_line(stdin, "uci").map_err(io)?; + let mut info = EngineInfo::default(); + let mut seen_uci = false; + let mut output = Vec::new(); + let deadline = Instant::now() + t.uciok; loop { - let wait = hs.deadline().saturating_duration_since(Instant::now()); - let line = match rx.recv_timeout(wait) { + let line = match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { Ok(Input::Stdout(l)) => l, Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), - Ok(Input::Cmd(_) | Input::Quit) => continue, - Err(RecvTimeoutError::Timeout) => return Err(hs.timed_out()), + Ok(Input::Cmd(_)) => continue, + Err(RecvTimeoutError::Timeout) => { + return Err(if seen_uci { + EngineError::HandshakeTimeout { + waiting_for: "uciok", + } + } else { + EngineError::NotUci { output } + }); + } }; - match hs.on_line(line, Instant::now()) { - HandshakeStep::Continue => {} - HandshakeStep::Write(l) => write_line(stdin, l).map_err(io)?, - HandshakeStep::Done(info, warnings) => return Ok((info, warnings)), + if output.len() < 20 { + output.push(line.clone()); + } + match parse_line(&line) { + Ok(EngineLine::IdName(n)) => { + seen_uci = true; + info.name = Some(n); + } + Ok(EngineLine::IdAuthor(a)) => { + seen_uci = true; + info.author = Some(a); + } + Ok(EngineLine::Option(o)) => { + seen_uci = true; + info.options.push(o); + } + Ok(EngineLine::UciOk) => break, + Ok(_) => {} + Err(e) => { + if line.starts_with("option") { + seen_uci = true; + } + warnings.push(format!("handshake: {e}")); + } + } + } + write_line(stdin, "isready").map_err(io)?; + let deadline = Instant::now() + t.readyok; + loop { + match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(Input::Stdout(l)) => { + if matches!(parse_line(&l), Ok(EngineLine::ReadyOk)) { + return Ok(info); + } + } + Ok(Input::StdoutClosed) | Err(RecvTimeoutError::Disconnected) => return Err(exited()), + Ok(Input::Cmd(_)) => {} + Err(RecvTimeoutError::Timeout) => { + return Err(EngineError::HandshakeTimeout { + waiting_for: "readyok", + }); + } } } } @@ -541,50 +688,109 @@ fn read_lines(mut r: BufReader, mut f: impl FnMut(String) -> bool) { } } -/// The process side of the session: the engine's stdin and the events' channel. -struct Pipes { - stdin: ChildStdin, - events: Sender, - waker: Waker, +/// Supervisor state. Invariant: `position`/`go` is only written in +/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a +/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` +/// belongs to the current search, and `info` read while `Idle`/`Syncing` is +/// stale and dropped. +#[derive(Debug, Clone, Copy)] +enum State { + /// No search running, nothing pending. + Idle, + /// `isready` sent before starting the pending search; waiting `readyok`. + Syncing { + deadline: Instant, + }, + Searching { + id: SearchId, + }, + /// `stop` sent; waiting for the final `bestmove` of `id`. + Stopping { + id: SearchId, + deadline: Instant, + }, } -impl Link for Pipes { - fn write(&mut self, line: &str) -> Result<(), Gone> { - write_line(&mut self.stdin, line).map_err(|_| Gone) - } - - fn emit(&mut self, ev: EngineEvent) { - if self.events.send(ev).is_ok() { - (self.waker)(); +impl State { + fn deadline(self) -> Option { + match self { + State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), + _ => None, } } } +struct PendingSearch { + position: EnginePosition, + id: SearchId, + limits: SearchLimits, + among: Vec, +} + struct Supervisor { - pipes: Pipes, - session: Session, + stdin: ChildStdin, child: Arc>, + events: Sender, + waker: Waker, alive: Arc, timeouts: Timeouts, + state: State, + pending: Option, + pending_setup: Vec, + warnings: usize, +} + +/// Why the loop must end. +enum Exit { + ProcessGone, + Hung(&'static str), } impl Supervisor { + fn emit(&self, ev: EngineEvent) { + if self.events.send(ev).is_ok() { + (self.waker)(); + } + } + + fn warn(&mut self, msg: String) { + self.warnings += 1; + if self.warnings < MAX_WARNINGS { + self.emit(EngineEvent::Warning(msg)); + } else if self.warnings == MAX_WARNINGS { + self.emit(EngineEvent::Warning( + "too many warnings; further warnings suppressed".into(), + )); + } + } + + fn write(&mut self, line: &str) -> Result<(), Exit> { + write_line(&mut self.stdin, line).map_err(|_| Exit::ProcessGone) + } + fn run(mut self, rx: Receiver) { let result = loop { - let msg = match self.session.deadline() { + let msg = match self.state.deadline() { Some(d) => rx.recv_timeout(d.saturating_duration_since(Instant::now())), None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected), }; - let now = Instant::now(); let step = match msg { - Ok(Input::Quit) | Err(RecvTimeoutError::Disconnected) => { + Ok(Input::Cmd(Cmd::Quit)) | Err(RecvTimeoutError::Disconnected) => { self.quit(); return; } - Ok(Input::Cmd(cmd)) => self.session.on_cmd(cmd, now, &mut self.pipes), - Ok(Input::Stdout(line)) => self.session.on_line(&line, now, &mut self.pipes), - Ok(Input::StdoutClosed) => Err(Exit::Gone), - Err(RecvTimeoutError::Timeout) => self.session.on_time(now), + Ok(Input::Cmd(cmd)) => self.on_cmd(cmd), + Ok(Input::Stdout(line)) => self.on_line(&line), + Ok(Input::StdoutClosed) => Err(Exit::ProcessGone), + Err(RecvTimeoutError::Timeout) => match self.state { + State::Syncing { deadline } if Instant::now() >= deadline => { + Err(Exit::Hung("readyok")) + } + State::Stopping { deadline, .. } if Instant::now() >= deadline => { + Err(Exit::Hung("bestmove")) + } + _ => Ok(()), + }, }; if let Err(e) = step { break e; @@ -598,11 +804,11 @@ impl Supervisor { let _ = child.wait(); TerminationReason::Hung { waiting_for } } - Exit::Gone => TerminationReason::Exited { + Exit::ProcessGone => TerminationReason::Exited { status: self.reap(Duration::from_millis(500)), }, }; - self.pipes.emit(EngineEvent::Terminated(reason)); + self.emit(EngineEvent::Terminated(reason)); } /// Waits up to `grace` for the process to exit, then kills it. Always reaps. @@ -626,9 +832,150 @@ impl Supervisor { fn quit(&mut self) { self.alive.store(false, Ordering::Release); - self.session.quit(&mut self.pipes); + if matches!(self.state, State::Searching { .. }) { + let _ = self.write("stop"); + } + let _ = self.write("quit"); let status = self.reap(self.timeouts.quit); - self.pipes - .emit(EngineEvent::Terminated(TerminationReason::Quit { status })); + self.emit(EngineEvent::Terminated(TerminationReason::Quit { status })); + } + + fn on_cmd(&mut self, cmd: Cmd) -> Result<(), Exit> { + match cmd { + Cmd::Search { + position, + id, + limits, + among, + } => { + if let Some(old) = self.pending.replace(PendingSearch { + position, + id, + limits, + among, + }) { + self.emit(EngineEvent::Superseded { search_id: old.id }); + } + match self.state { + State::Idle => self.begin_sync()?, + State::Searching { id } => self.send_stop(id)?, + State::Syncing { .. } | State::Stopping { .. } => {} + } + } + Cmd::Stop => { + if let Some(old) = self.pending.take() { + self.emit(EngineEvent::Superseded { search_id: old.id }); + } + if let State::Searching { id } = self.state { + self.send_stop(id)?; + } + } + Cmd::Setup(line) => match self.state { + // The engine is not searching: safe to send right away; the + // `isready` before the next `go` fences it. + State::Idle | State::Syncing { .. } => self.write(&line)?, + State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), + }, + Cmd::Quit => unreachable!("handled in run"), + } + Ok(()) + } + + fn send_stop(&mut self, id: SearchId) -> Result<(), Exit> { + self.write("stop")?; + self.state = State::Stopping { + id, + deadline: Instant::now() + self.timeouts.stop, + }; + Ok(()) + } + + /// Engine is idle: flush queued setup, then `isready` if a search waits. + fn begin_sync(&mut self) -> Result<(), Exit> { + for line in std::mem::take(&mut self.pending_setup) { + self.write(&line)?; + } + if self.pending.is_some() { + self.write("isready")?; + self.state = State::Syncing { + deadline: Instant::now() + self.timeouts.readyok, + }; + } else { + self.state = State::Idle; + } + Ok(()) + } + + fn current_search(&self) -> Option { + match self.state { + State::Searching { id } | State::Stopping { id, .. } => Some(id), + _ => None, + } + } + + fn on_line(&mut self, line: &str) -> Result<(), Exit> { + let parsed = match parse_line(line) { + Ok(p) => p, + Err(e) => { + self.warn(e.to_string()); + return Ok(()); + } + }; + match parsed { + EngineLine::Info(info) => { + if let Some(id) = self.current_search() + && (info.score.is_some() || !info.pv.is_empty()) + { + self.emit(EngineEvent::Info { + search_id: id, + info, + }); + } + // Otherwise: stale output of a finished search, dropped. + } + EngineLine::InfoString(text) => { + let search_id = self.current_search(); + self.emit(EngineEvent::InfoString { search_id, text }); + } + EngineLine::BestMove { best, ponder } => match self.current_search() { + Some(id) => { + self.emit(EngineEvent::BestMove { + search_id: id, + best, + ponder, + }); + self.state = State::Idle; + self.begin_sync()?; + } + None => self.warn(format!("unexpected bestmove ignored: {line:?}")), + }, + EngineLine::ReadyOk => { + if let State::Syncing { .. } = self.state { + match self.pending.take() { + Some(p) => { + self.write(&p.position.to_command())?; + let mut go = p.limits.to_command(); + if !p.among.is_empty() { + go += " searchmoves "; + go += &p.among.join(" "); + } + self.write(&go)?; + self.state = State::Searching { id: p.id }; + self.emit(EngineEvent::SearchStarted { search_id: p.id }); + } + None => self.state = State::Idle, + } + } + } + EngineLine::Empty => {} + EngineLine::UciOk + | EngineLine::IdName(_) + | EngineLine::IdAuthor(_) + | EngineLine::Option(_) + | EngineLine::Unknown(_) => { + self.warn(format!("unexpected engine output: {line:?}")); + } + } + Ok(()) } } diff --git a/crates/uci/src/events.rs b/crates/uci/src/events.rs deleted file mode 100644 index 16a1460..0000000 --- a/crates/uci/src/events.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! What a running engine tells the UI, whatever carries it. - -use crate::types::{SearchId, SearchInfo}; - -/// Callback invoked after every new event (from the transport's thread on a -/// computer); the UI passes `ctx.request_repaint()` here. -pub type Waker = Box; - -/// Event delivered to the UI. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum EngineEvent { - /// `position` + `go` for this id were sent to the engine. - SearchStarted { search_id: SearchId }, - /// The request was replaced by a newer one (or cancelled by `stop`) - /// before it was sent to the engine; no events will follow for this id. - Superseded { search_id: SearchId }, - /// Search output. Only lines with a score or a PV are forwarded. - Info { - search_id: SearchId, - info: SearchInfo, - }, - /// Final `bestmove` of a started search. Exactly one per `SearchStarted` - /// unless the engine terminates first. - BestMove { - search_id: SearchId, - best: Option, - ponder: Option, - }, - /// `info string`, attributed to the running search if any. - InfoString { - search_id: Option, - text: String, - }, - /// Malformed or unexpected engine output; the line was skipped. - Warning(String), - /// The supervisor has stopped; the handle is no longer usable. - Terminated(TerminationReason), -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum TerminationReason { - /// `quit()` or drop of the handle. - Quit { - status: Option, - }, - /// The engine exited on its own (crash, end of its output, write failure). - Exited { - status: Option, - }, - /// The engine did not answer `stop` or `isready` in time and was killed. - Hung { waiting_for: &'static str }, -} diff --git a/crates/uci/src/lib.rs b/crates/uci/src/lib.rs index db125eb..b8c8a06 100644 --- a/crates/uci/src/lib.rs +++ b/crates/uci/src/lib.rs @@ -1,13 +1,10 @@ -//! UCI engine supervisor. +//! UCI engine process supervisor. //! -//! The protocol is a state machine without I/O ([`protocol`]); a transport drives -//! it. On a computer the engine is a child process started without a shell: -//! stdout and stderr are read by two dedicated threads, a supervisor thread -//! feeds the machine. The UI talks to it through the non-blocking -//! [`EngineHandle`] and polls [`EngineEvent`]s every frame; the [`Waker`] -//! callback is invoked after each new event. WebAssembly in a browser has no -//! processes: there the engine is a Web Worker, its handle the same, its start -//! not blocking ([`Engine::start_worker`]). +//! The engine runs as a separate child process started without a shell. +//! stdout and stderr are read by two dedicated threads; a supervisor thread +//! owns the protocol state machine. The UI talks to it through the +//! non-blocking [`EngineHandle`] and polls [`EngineEvent`]s every frame; the +//! [`Waker`] callback is invoked after each new event. //! //! Search boundary: UCI has no request ids. A new `position`/`go` is written //! only after the previous search ended with `bestmove` and a subsequent @@ -17,23 +14,14 @@ //! [`EngineEvent::Superseded`]. No dependency on egui or chess-core: //! positions are strings (FEN / UCI moves). +mod engine; mod error; -mod events; pub mod parse; -#[cfg(not(target_family = "wasm"))] -mod process; -mod protocol; mod types; -#[cfg(target_family = "wasm")] -mod worker; +pub use engine::{Engine, EngineConfig, EngineEvent, EngineHandle, TerminationReason, Waker}; pub use error::EngineError; -pub use events::{EngineEvent, TerminationReason, Waker}; -#[cfg(not(target_family = "wasm"))] -pub use process::{Engine, EngineConfig, EngineHandle}; pub use types::{ EngineInfo, EngineOption, EnginePosition, EngineScore, OptionKind, PositionBase, Score, ScoreBound, SearchId, SearchInfo, SearchLimits, Side, Timeouts, WhiteEval, WhiteScore, }; -#[cfg(target_family = "wasm")] -pub use worker::{Engine, EngineHandle, Starting, WorkerConfig}; diff --git a/crates/uci/src/protocol.rs b/crates/uci/src/protocol.rs deleted file mode 100644 index a48af09..0000000 --- a/crates/uci/src/protocol.rs +++ /dev/null @@ -1,619 +0,0 @@ -//! The UCI protocol as a state machine without I/O: the handshake and the session -//! after it. A transport (a child process on a computer, a Web Worker in a browser) -//! feeds it the engine's lines, the user's commands and the time, and carries out -//! what it asks: lines to write, events to deliver. Waiting is the transport's -//! business — the machine never blocks, it only names its next deadline. - -use web_time::Instant; - -use crate::error::EngineError; -use crate::events::EngineEvent; -use crate::parse::{EngineLine, parse_line}; -use crate::types::{EngineInfo, EnginePosition, OptionKind, SearchId, SearchLimits, Timeouts}; - -/// Maximum number of `Warning` events emitted per engine (flood protection). -const MAX_WARNINGS: usize = 100; - -/// A command from the handle to the session. -pub(crate) enum Cmd { - Search { - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, - }, - Stop, - /// A complete `setoption ...` / `ucinewgame` line, applied while idle. - Setup(String), -} - -impl Cmd { - /// A search request, checked: a valid position, UCI moves to search among. - pub(crate) fn search( - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, - ) -> Result { - position.validate()?; - if let Some(bad) = among.iter().find(|m| !crate::types::is_uci_move(m)) { - return Err(EngineError::InvalidInput(format!("not a move: {bad:?}"))); - } - Ok(Cmd::Search { - position, - id, - limits, - among, - }) - } -} - -/// The `setoption` line for `name` = `value` (`None` for buttons), checked against -/// the options the engine declared. -pub(crate) fn option_line( - info: &EngineInfo, - name: &str, - value: Option<&str>, -) -> Result { - let opt = info - .option(name) - .ok_or_else(|| EngineError::UnknownOption(name.to_string()))?; - let bad = |reason: String| EngineError::InvalidOptionValue { - name: opt.name.clone(), - reason, - }; - if let Some(v) = value - && v.chars().any(char::is_control) - { - return Err(bad("control characters in value".into())); - } - let value = match (&opt.kind, value) { - (OptionKind::Button, None) => None, - (OptionKind::Button, Some(_)) => return Err(bad("button takes no value".into())), - (_, None) => return Err(bad("value required".into())), - (OptionKind::Check { .. }, Some(v)) => match v { - "true" | "false" => Some(v.to_string()), - _ => return Err(bad(format!("expected true/false, got {v:?}"))), - }, - (OptionKind::Spin { min, max, .. }, Some(v)) => { - let n: i64 = v - .trim() - .parse() - .map_err(|_| bad(format!("not an integer: {v:?}")))?; - if min.is_some_and(|m| n < m) || max.is_some_and(|m| n > m) { - return Err(bad(format!("{n} outside {min:?}..={max:?}"))); - } - Some(n.to_string()) - } - (OptionKind::Combo { vars, .. }, Some(v)) => { - let var = vars - .iter() - .find(|x| x.eq_ignore_ascii_case(v)) - .ok_or_else(|| bad(format!("{v:?} is not one of {vars:?}")))?; - Some(var.clone()) - } - (OptionKind::String { .. }, Some(v)) => Some(v.to_string()), - }; - let line = match value { - Some(v) => format!("setoption name {} value {}", opt.name, v), - None => format!("setoption name {}", opt.name), - }; - Ok(line) -} - -/// The engine could not be written to: it is gone. -#[derive(Debug)] -pub(crate) struct Gone; - -/// What the session does to the outside world. -pub(crate) trait Link { - /// Writes one line (without its `\n`) to the engine. - fn write(&mut self, line: &str) -> Result<(), Gone>; - /// Delivers an event to the handle (and wakes the UI). - fn emit(&mut self, ev: EngineEvent); -} - -/// The step of the handshake: `uci` → `uciok`, then `isready` → `readyok`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Phase { - Uci, - Ready, -} - -/// `uci`/`uciok` and `isready`/`readyok`: the engine's name, author and options. -pub(crate) struct Handshake { - phase: Phase, - deadline: Instant, - readyok: std::time::Duration, - info: EngineInfo, - seen_uci: bool, - /// First lines of output, for [`EngineError::NotUci`]. - output: Vec, - /// Malformed lines, reported once the session runs. - warnings: Vec, -} - -/// How a line moved the handshake on. -pub(crate) enum HandshakeStep { - /// Keep feeding lines. - Continue, - /// Write this line, then keep feeding lines. - Write(&'static str), - /// Complete: the engine is ready for the session. - Done(EngineInfo, Vec), -} - -impl Handshake { - /// Starts the handshake at `now`; the caller writes [`Self::FIRST_LINE`]. - pub(crate) fn new(t: &Timeouts, now: Instant) -> Self { - Handshake { - phase: Phase::Uci, - deadline: now + t.uciok, - readyok: t.readyok, - info: EngineInfo::default(), - seen_uci: false, - output: Vec::new(), - warnings: Vec::new(), - } - } - - pub(crate) const FIRST_LINE: &'static str = "uci"; - - pub(crate) fn deadline(&self) -> Instant { - self.deadline - } - - /// One line of the engine's output, read at `now`. - pub(crate) fn on_line(&mut self, line: String, now: Instant) -> HandshakeStep { - match self.phase { - Phase::Uci => { - if self.output.len() < 20 { - self.output.push(line.clone()); - } - match parse_line(&line) { - Ok(EngineLine::IdName(n)) => { - self.seen_uci = true; - self.info.name = Some(n); - } - Ok(EngineLine::IdAuthor(a)) => { - self.seen_uci = true; - self.info.author = Some(a); - } - Ok(EngineLine::Option(o)) => { - self.seen_uci = true; - self.info.options.push(o); - } - Ok(EngineLine::UciOk) => { - self.phase = Phase::Ready; - self.deadline = now + self.readyok; - return HandshakeStep::Write("isready"); - } - Ok(_) => {} - Err(e) => { - if line.starts_with("option") { - self.seen_uci = true; - } - self.warnings.push(format!("handshake: {e}")); - } - } - HandshakeStep::Continue - } - Phase::Ready => { - if matches!(parse_line(&line), Ok(EngineLine::ReadyOk)) { - HandshakeStep::Done( - std::mem::take(&mut self.info), - std::mem::take(&mut self.warnings), - ) - } else { - HandshakeStep::Continue - } - } - } - } - - /// The error once [`Self::deadline`] has passed. - pub(crate) fn timed_out(self) -> EngineError { - match self.phase { - Phase::Uci if self.seen_uci => EngineError::HandshakeTimeout { - waiting_for: "uciok", - }, - Phase::Uci => EngineError::NotUci { - output: self.output, - }, - Phase::Ready => EngineError::HandshakeTimeout { - waiting_for: "readyok", - }, - } - } -} - -/// Session state. Invariant: `position`/`go` is only written in -/// `Syncing → Searching`, i.e. after the previous search's `bestmove` *and* a -/// fresh `readyok`; therefore every `info` read while `Searching`/`Stopping` -/// belongs to the current search, and `info` read while `Idle`/`Syncing` is -/// stale and dropped. -#[derive(Debug, Clone, Copy)] -enum State { - /// No search running, nothing pending. - Idle, - /// `isready` sent before starting the pending search; waiting `readyok`. - Syncing { - deadline: Instant, - }, - Searching { - id: SearchId, - }, - /// `stop` sent; waiting for the final `bestmove` of `id`. - Stopping { - id: SearchId, - deadline: Instant, - }, -} - -struct PendingSearch { - position: EnginePosition, - id: SearchId, - limits: SearchLimits, - among: Vec, -} - -/// Why the session must end. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Exit { - /// The engine stopped reading or writing. - Gone, - /// The engine did not answer this in time; the transport kills it. - Hung(&'static str), -} - -impl From for Exit { - fn from(_: Gone) -> Self { - Exit::Gone - } -} - -/// The session after the handshake: searches, their boundaries, setup lines. -pub(crate) struct Session { - timeouts: Timeouts, - state: State, - pending: Option, - pending_setup: Vec, - warnings: usize, -} - -impl Session { - pub(crate) fn new(timeouts: Timeouts) -> Self { - Session { - timeouts, - state: State::Idle, - pending: None, - pending_setup: Vec::new(), - warnings: 0, - } - } - - /// When [`Self::on_time`] must be called next (`None`: nothing to wait for). - pub(crate) fn deadline(&self) -> Option { - match self.state { - State::Syncing { deadline } | State::Stopping { deadline, .. } => Some(deadline), - _ => None, - } - } - - /// The time is `now`: an engine past its deadline is hung. - pub(crate) fn on_time(&mut self, now: Instant) -> Result<(), Exit> { - match self.state { - State::Syncing { deadline } if now >= deadline => Err(Exit::Hung("readyok")), - State::Stopping { deadline, .. } if now >= deadline => Err(Exit::Hung("bestmove")), - _ => Ok(()), - } - } - - pub(crate) fn warn(&mut self, msg: String, link: &mut impl Link) { - self.warnings += 1; - if self.warnings < MAX_WARNINGS { - link.emit(EngineEvent::Warning(msg)); - } else if self.warnings == MAX_WARNINGS { - link.emit(EngineEvent::Warning( - "too many warnings; further warnings suppressed".into(), - )); - } - } - - /// The last words before `quit`: a running search is stopped. - pub(crate) fn quit(&mut self, link: &mut impl Link) { - if matches!(self.state, State::Searching { .. }) { - let _ = link.write("stop"); - } - let _ = link.write("quit"); - } - - pub(crate) fn on_cmd( - &mut self, - cmd: Cmd, - now: Instant, - link: &mut impl Link, - ) -> Result<(), Exit> { - match cmd { - Cmd::Search { - position, - id, - limits, - among, - } => { - if let Some(old) = self.pending.replace(PendingSearch { - position, - id, - limits, - among, - }) { - link.emit(EngineEvent::Superseded { search_id: old.id }); - } - match self.state { - State::Idle => self.begin_sync(now, link)?, - State::Searching { id } => self.send_stop(id, now, link)?, - State::Syncing { .. } | State::Stopping { .. } => {} - } - } - Cmd::Stop => { - if let Some(old) = self.pending.take() { - link.emit(EngineEvent::Superseded { search_id: old.id }); - } - if let State::Searching { id } = self.state { - self.send_stop(id, now, link)?; - } - } - Cmd::Setup(line) => match self.state { - // The engine is not searching: safe to send right away; the - // `isready` before the next `go` fences it. - State::Idle | State::Syncing { .. } => link.write(&line)?, - State::Searching { .. } | State::Stopping { .. } => self.pending_setup.push(line), - }, - } - Ok(()) - } - - fn send_stop(&mut self, id: SearchId, now: Instant, link: &mut impl Link) -> Result<(), Exit> { - link.write("stop")?; - self.state = State::Stopping { - id, - deadline: now + self.timeouts.stop, - }; - Ok(()) - } - - /// Engine is idle: flush queued setup, then `isready` if a search waits. - fn begin_sync(&mut self, now: Instant, link: &mut impl Link) -> Result<(), Exit> { - for line in std::mem::take(&mut self.pending_setup) { - link.write(&line)?; - } - if self.pending.is_some() { - link.write("isready")?; - self.state = State::Syncing { - deadline: now + self.timeouts.readyok, - }; - } else { - self.state = State::Idle; - } - Ok(()) - } - - fn current_search(&self) -> Option { - match self.state { - State::Searching { id } | State::Stopping { id, .. } => Some(id), - _ => None, - } - } - - /// One line of the engine's output, read at `now`. - pub(crate) fn on_line( - &mut self, - line: &str, - now: Instant, - link: &mut impl Link, - ) -> Result<(), Exit> { - let parsed = match parse_line(line) { - Ok(p) => p, - Err(e) => { - self.warn(e.to_string(), link); - return Ok(()); - } - }; - match parsed { - EngineLine::Info(info) => { - if let Some(id) = self.current_search() - && (info.score.is_some() || !info.pv.is_empty()) - { - link.emit(EngineEvent::Info { - search_id: id, - info, - }); - } - // Otherwise: stale output of a finished search, dropped. - } - EngineLine::InfoString(text) => { - let search_id = self.current_search(); - link.emit(EngineEvent::InfoString { search_id, text }); - } - EngineLine::BestMove { best, ponder } => match self.current_search() { - Some(id) => { - link.emit(EngineEvent::BestMove { - search_id: id, - best, - ponder, - }); - self.state = State::Idle; - self.begin_sync(now, link)?; - } - None => self.warn(format!("unexpected bestmove ignored: {line:?}"), link), - }, - EngineLine::ReadyOk => { - if let State::Syncing { .. } = self.state { - match self.pending.take() { - Some(p) => { - link.write(&p.position.to_command())?; - let mut go = p.limits.to_command(); - if !p.among.is_empty() { - go += " searchmoves "; - go += &p.among.join(" "); - } - link.write(&go)?; - self.state = State::Searching { id: p.id }; - link.emit(EngineEvent::SearchStarted { search_id: p.id }); - } - None => self.state = State::Idle, - } - } - } - EngineLine::Empty => {} - EngineLine::UciOk - | EngineLine::IdName(_) - | EngineLine::IdAuthor(_) - | EngineLine::Option(_) - | EngineLine::Unknown(_) => { - self.warn(format!("unexpected engine output: {line:?}"), link); - } - } - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::time::Duration; - - /// A link that records what the session did. - #[derive(Default)] - struct Record { - written: Vec, - events: Vec, - broken: bool, - } - - impl Link for Record { - fn write(&mut self, line: &str) -> Result<(), Gone> { - if self.broken { - return Err(Gone); - } - self.written.push(line.to_owned()); - Ok(()) - } - fn emit(&mut self, ev: EngineEvent) { - self.events.push(ev); - } - } - - fn search(id: u64) -> Cmd { - Cmd::Search { - position: EnginePosition::startpos(Vec::::new()), - id: SearchId(id), - limits: SearchLimits::Infinite, - among: Vec::new(), - } - } - - #[test] - fn handshake_collects_info_and_asks_ready() { - let t0 = Instant::now(); - let mut h = Handshake::new(&Timeouts::default(), t0); - assert!(matches!( - h.on_line("id name Fake".into(), t0), - HandshakeStep::Continue - )); - assert!(matches!( - h.on_line( - "option name Hash type spin default 16 min 1 max 1024".into(), - t0 - ), - HandshakeStep::Continue - )); - let later = t0 + Duration::from_secs(1); - assert!(matches!( - h.on_line("uciok".into(), later), - HandshakeStep::Write("isready") - )); - assert_eq!(h.deadline(), later + Timeouts::default().readyok); - // Output before `readyok` is not taken for the engine's description. - assert!(matches!( - h.on_line("id name Other".into(), later), - HandshakeStep::Continue - )); - match h.on_line("readyok".into(), later) { - HandshakeStep::Done(info, warnings) => { - assert_eq!(info.name.as_deref(), Some("Fake")); - assert_eq!(info.options.len(), 1); - assert!(warnings.is_empty()); - } - _ => panic!("handshake not done"), - } - } - - #[test] - fn handshake_timeouts_name_what_was_missing() { - let t0 = Instant::now(); - let silent = Handshake::new(&Timeouts::default(), t0); - assert!(matches!(silent.timed_out(), EngineError::NotUci { .. })); - let mut uci = Handshake::new(&Timeouts::default(), t0); - let _ = uci.on_line("id name Fake".into(), t0); - assert!(matches!( - uci.timed_out(), - EngineError::HandshakeTimeout { - waiting_for: "uciok" - } - )); - let mut ready = Handshake::new(&Timeouts::default(), t0); - let _ = ready.on_line("uciok".into(), t0); - assert!(matches!( - ready.timed_out(), - EngineError::HandshakeTimeout { - waiting_for: "readyok" - } - )); - } - - #[test] - fn a_search_waits_for_readyok_and_stale_info_is_dropped() { - let now = Instant::now(); - let mut s = Session::new(Timeouts::default()); - let mut link = Record::default(); - s.on_cmd(search(1), now, &mut link).unwrap(); - assert_eq!(link.written, ["isready"]); - // Info before the search starts belongs to nobody. - s.on_line("info depth 1 score cp 5 pv e2e4", now, &mut link) - .unwrap(); - assert!(link.events.is_empty()); - s.on_line("readyok", now, &mut link).unwrap(); - assert_eq!(link.written[1], "position startpos"); - assert_eq!(link.written[2], "go infinite"); - assert_eq!( - link.events, - [EngineEvent::SearchStarted { - search_id: SearchId(1) - }] - ); - // A newer request stops the running search; the old `bestmove` ends it. - s.on_cmd(search(2), now, &mut link).unwrap(); - assert_eq!(link.written[3], "stop"); - s.on_line("bestmove e2e4", now, &mut link).unwrap(); - assert_eq!(link.written[4], "isready"); - s.on_line("readyok", now, &mut link).unwrap(); - assert!(link.events.contains(&EngineEvent::SearchStarted { - search_id: SearchId(2) - })); - } - - #[test] - fn deadlines_and_a_broken_link_end_the_session() { - let now = Instant::now(); - let mut s = Session::new(Timeouts::default()); - let mut link = Record::default(); - assert_eq!(s.deadline(), None); - s.on_cmd(search(1), now, &mut link).unwrap(); - let d = s.deadline().expect("waiting for readyok"); - assert_eq!(s.on_time(now), Ok(())); - assert_eq!(s.on_time(d), Err(Exit::Hung("readyok"))); - link.broken = true; - assert_eq!(s.on_line("readyok", now, &mut link), Err(Exit::Gone)); - } -} diff --git a/crates/uci/src/types.rs b/crates/uci/src/types.rs index 7b57cca..148354f 100644 --- a/crates/uci/src/types.rs +++ b/crates/uci/src/types.rs @@ -253,8 +253,7 @@ impl EnginePosition { Ok(()) } - /// The `position …` line for this position. - pub fn to_command(&self) -> String { + pub(crate) fn to_command(&self) -> String { let mut s = match &self.base { PositionBase::StartPos => "position startpos".to_string(), PositionBase::Fen(fen) => format!("position fen {}", fen.trim()), @@ -291,8 +290,7 @@ pub enum SearchLimits { } impl SearchLimits { - /// The `go …` line for these limits. - pub fn to_command(self) -> String { + pub(crate) fn to_command(self) -> String { match self { SearchLimits::Infinite => "go infinite".into(), SearchLimits::Depth(d) => format!("go depth {d}"), diff --git a/crates/uci/src/worker.rs b/crates/uci/src/worker.rs deleted file mode 100644 index 3ce9cc7..0000000 --- a/crates/uci/src/worker.rs +++ /dev/null @@ -1,434 +0,0 @@ -//! The engine as a Web Worker (WebAssembly in a browser, which has no processes): -//! the engine's script runs in the worker, a line of UCI is one message each way, -//! and the protocol ([`crate::protocol`]) is driven by the worker's messages and by -//! timers set for its deadlines. Everything happens on the page's thread, so nothing -//! here blocks: the handshake is finished by the worker's messages and its outcome -//! taken by [`Starting::poll`]. - -use std::cell::RefCell; -use std::collections::VecDeque; -use std::rc::{Rc, Weak}; - -use wasm_bindgen::JsCast; -use wasm_bindgen::prelude::*; -use web_time::Instant; - -use crate::error::EngineError; -use crate::events::{EngineEvent, TerminationReason, Waker}; -use crate::protocol::{Cmd, Exit, Gone, Handshake, HandshakeStep, Link, Session, option_line}; -use crate::types::{EngineInfo, EnginePosition, SearchId, SearchLimits, Timeouts}; - -#[wasm_bindgen] -extern "C" { - // The global timer functions: a page's and a worker's alike. - #[wasm_bindgen(js_name = setTimeout)] - fn set_timeout(f: &js_sys::Function, ms: f64) -> JsValue; - #[wasm_bindgen(js_name = clearTimeout)] - fn clear_timeout(id: &JsValue); -} - -/// How to start an engine in a worker. -#[derive(Debug, Clone)] -pub struct WorkerConfig { - /// The URL of the engine's worker script. - pub script: String, - pub timeouts: Timeouts, -} - -impl WorkerConfig { - pub fn new(script: impl Into) -> Self { - WorkerConfig { - script: script.into(), - timeouts: Timeouts::default(), - } - } -} - -/// The worker side of the session: the worker itself and the events' queue. -struct Port { - worker: web_sys::Worker, - events: VecDeque, - waker: Waker, -} - -impl Link for Port { - fn write(&mut self, line: &str) -> Result<(), Gone> { - self.worker - .post_message(&JsValue::from_str(line)) - .map_err(|_| Gone) - } - - fn emit(&mut self, ev: EngineEvent) { - self.events.push_back(ev); - (self.waker)(); - } -} - -enum Phase { - Handshake(Handshake), - Running(Session), - Ended, -} - -struct Inner { - port: Port, - phase: Phase, - timeouts: Timeouts, - /// The outcome of the handshake until [`Starting::poll`] takes it. - started: Option>, - /// The timer of the protocol's next deadline. - timer: Option, - /// The worker's handlers and the timer's callback, alive as long as the engine. - callbacks: Vec>, - on_timer: Option>, -} - -impl Inner { - fn deadline(&self) -> Option { - match &self.phase { - Phase::Handshake(h) => Some(h.deadline()), - Phase::Running(s) => s.deadline(), - Phase::Ended => None, - } - } - - /// Sets the timer for the protocol's next deadline (clearing the old one). - fn arm(&mut self) { - if let Some(id) = self.timer.take() { - clear_timeout(&id); - } - let (Some(at), Some(f)) = (self.deadline(), &self.on_timer) else { - return; - }; - let ms = at.saturating_duration_since(Instant::now()).as_secs_f64() * 1000.0; - // A millisecond late rather than early: the deadline must have passed. - self.timer = Some(set_timeout(f.as_ref().unchecked_ref(), ms.ceil() + 1.0)); - } - - fn on_line(&mut self, line: String) { - let now = Instant::now(); - match &mut self.phase { - Phase::Handshake(h) => match h.on_line(line, now) { - HandshakeStep::Continue => {} - HandshakeStep::Write(l) => { - if self.port.write(l).is_err() { - self.fail_start(gone(Vec::new())); - } - } - HandshakeStep::Done(info, warnings) => { - let mut session = Session::new(self.timeouts); - for w in warnings { - session.warn(w, &mut self.port); - } - self.phase = Phase::Running(session); - self.started = Some(Ok(info)); - (self.port.waker)(); - } - }, - Phase::Running(s) => { - if let Err(e) = s.on_line(&line, now, &mut self.port) { - self.end(e); - } - } - Phase::Ended => {} - } - self.arm(); - } - - fn on_cmd(&mut self, cmd: Cmd) -> Result<(), EngineError> { - let Phase::Running(s) = &mut self.phase else { - return Err(EngineError::NotRunning); - }; - if let Err(e) = s.on_cmd(cmd, Instant::now(), &mut self.port) { - self.end(e); - } - self.arm(); - Ok(()) - } - - fn on_timer(&mut self) { - self.timer = None; - let now = Instant::now(); - match &mut self.phase { - Phase::Handshake(h) if now >= h.deadline() => { - let Phase::Handshake(h) = std::mem::replace(&mut self.phase, Phase::Ended) else { - unreachable!("matched above"); - }; - self.port.worker.terminate(); - self.started = Some(Err(h.timed_out())); - (self.port.waker)(); - } - Phase::Running(s) => { - if let Err(e) = s.on_time(now) { - self.end(e); - } - } - Phase::Handshake(_) | Phase::Ended => {} - } - self.arm(); - } - - /// The worker reported an error: its script did not load or the engine failed. - fn on_error(&mut self, message: String) { - match self.phase { - Phase::Handshake(_) => self.fail_start(gone(vec![message])), - Phase::Running(_) => self.end(Exit::Gone), - Phase::Ended => {} - } - self.arm(); - } - - fn fail_start(&mut self, e: EngineError) { - self.port.worker.terminate(); - self.phase = Phase::Ended; - self.started = Some(Err(e)); - (self.port.waker)(); - } - - /// The session ended on its own; the worker is stopped. - fn end(&mut self, exit: Exit) { - self.port.worker.terminate(); - self.phase = Phase::Ended; - let reason = match exit { - Exit::Hung(waiting_for) => TerminationReason::Hung { waiting_for }, - Exit::Gone => TerminationReason::Exited { status: None }, - }; - self.port.emit(EngineEvent::Terminated(reason)); - } - - fn quit(&mut self) { - if let Phase::Running(s) = &mut self.phase { - s.quit(&mut self.port); - self.port.worker.terminate(); - self.phase = Phase::Ended; - self.port - .emit(EngineEvent::Terminated(TerminationReason::Quit { - status: None, - })); - } else { - self.port.worker.terminate(); - self.phase = Phase::Ended; - } - self.arm(); - self.port.worker.set_onmessage(None); - self.port.worker.set_onerror(None); - } -} - -fn gone(stderr: Vec) -> EngineError { - EngineError::ProcessExited { - status: None, - stderr, - } -} - -/// An engine whose handshake is under way. -pub struct Starting { - inner: Option>>, -} - -impl Starting { - /// The engine once its handshake is over (`None`: not yet). After a result it - /// keeps returning `None`. - pub fn poll(&mut self) -> Option> { - let started = self.inner.as_ref()?.borrow_mut().started.take()?; - let inner = self.inner.take()?; - Some(started.map(|info| EngineHandle { info, inner })) - } -} - -impl Drop for Starting { - fn drop(&mut self) { - if let Some(inner) = self.inner.take() { - inner.borrow_mut().quit(); - } - } -} - -/// Namespace for starting engines. -pub struct Engine; - -impl Engine { - /// Starts the engine of `cfg.script` in a new worker, and its handshake. The - /// worker's events wake the UI through `waker`; [`Starting::poll`] gives the - /// engine once it answered `readyok`. - pub fn start_worker(cfg: WorkerConfig, waker: Waker) -> Result { - start(cfg, waker) - } -} - -fn start(cfg: WorkerConfig, waker: Waker) -> Result { - let script_error = |e: JsValue| { - EngineError::Spawn(std::io::Error::other( - e.as_string() - .unwrap_or_else(|| format!("cannot start the worker {}", cfg.script)), - )) - }; - let worker = web_sys::Worker::new(&cfg.script).map_err(script_error)?; - let inner = Rc::new(RefCell::new(Inner { - port: Port { - worker: worker.clone(), - events: VecDeque::new(), - waker, - }, - phase: Phase::Handshake(Handshake::new(&cfg.timeouts, Instant::now())), - timeouts: cfg.timeouts, - started: None, - timer: None, - callbacks: Vec::new(), - on_timer: None, - })); - let weak = Rc::downgrade(&inner); - let with = move |f: &dyn Fn(&mut Inner)| { - if let Some(inner) = Weak::upgrade(&weak) { - f(&mut inner.borrow_mut()); - } - }; - let on_message = { - let with = with.clone(); - Closure::::new(move |ev: JsValue| { - let data = ev.unchecked_into::().data(); - // A message is a line; some builds join several with `\n`. - let text = data.as_string().unwrap_or_default(); - with(&|inner| { - for line in text.lines() { - inner.on_line(line.to_owned()); - } - }); - }) - }; - let on_error = { - let with = with.clone(); - Closure::::new(move |ev: JsValue| { - let message = ev - .dyn_ref::() - .map(web_sys::ErrorEvent::message) - .unwrap_or_else(|| "the engine's worker failed".into()); - with(&|inner| inner.on_error(message.clone())); - }) - }; - let on_timer = Closure::::new(move || with(&|inner| inner.on_timer())); - worker.set_onmessage(Some(on_message.as_ref().unchecked_ref())); - worker.set_onerror(Some(on_error.as_ref().unchecked_ref())); - { - let mut i = inner.borrow_mut(); - i.callbacks = vec![on_message, on_error]; - i.on_timer = Some(on_timer); - if i.port.write(Handshake::FIRST_LINE).is_err() { - i.fail_start(gone(Vec::new())); - } - i.arm(); - } - Ok(Starting { inner: Some(inner) }) -} - -/// Handle owned by the UI. Dropping it quits the engine (its worker is stopped). -pub struct EngineHandle { - info: EngineInfo, - inner: Rc>, -} - -impl std::fmt::Debug for EngineHandle { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("EngineHandle") - .field("name", &self.info.name) - .field("alive", &self.is_running()) - .finish() - } -} - -impl EngineHandle { - /// `id name/author` and declared options from the handshake. - pub fn info(&self) -> &EngineInfo { - &self.info - } - - /// `false` after the engine terminated (quit, crash, hung). - pub fn is_running(&self) -> bool { - matches!(self.inner.borrow().phase, Phase::Running(_)) - } - - /// Non-blocking poll for the next event (call every frame). - pub fn try_recv(&self) -> Option { - self.inner.borrow_mut().port.events.pop_front() - } - - /// Drains all currently queued events. - pub fn drain_events(&self) -> impl Iterator + '_ { - std::iter::from_fn(|| self.try_recv()) - } - - /// Infinite analysis (`go infinite`) of `position` under `search_id`. - pub fn analyze( - &self, - position: EnginePosition, - search_id: SearchId, - ) -> Result<(), EngineError> { - self.search(position, search_id, SearchLimits::Infinite) - } - - /// Requests a search: a running search is stopped first and only the latest - /// request is started. - pub fn search( - &self, - position: EnginePosition, - search_id: SearchId, - limits: SearchLimits, - ) -> Result<(), EngineError> { - self.search_among(position, search_id, limits, Vec::new()) - } - - /// A search among these moves only (UCI moves of `position`); empty: all. - pub fn search_among( - &self, - position: EnginePosition, - search_id: SearchId, - limits: SearchLimits, - among: Vec, - ) -> Result<(), EngineError> { - let cmd = Cmd::search(position, search_id, limits, among)?; - self.inner.borrow_mut().on_cmd(cmd) - } - - /// Stops the running search (its `BestMove` still arrives) and cancels a - /// queued one. - pub fn stop(&self) -> Result<(), EngineError> { - self.inner.borrow_mut().on_cmd(Cmd::Stop) - } - - /// `setoption`, checked against the declared options; applied at the next - /// search boundary when a search runs. - pub fn set_option(&self, name: &str, value: Option<&str>) -> Result<(), EngineError> { - let line = option_line(&self.info, name, value)?; - self.inner.borrow_mut().on_cmd(Cmd::Setup(line)) - } - - pub fn set_multipv(&self, lines: u32) -> Result<(), EngineError> { - self.set_option("MultiPV", Some(&lines.to_string())) - } - - pub fn set_threads(&self, threads: u32) -> Result<(), EngineError> { - self.set_option("Threads", Some(&threads.to_string())) - } - - pub fn set_hash_mb(&self, mb: u32) -> Result<(), EngineError> { - self.set_option("Hash", Some(&mb.to_string())) - } - - /// `ucinewgame` (applied at the next idle point, followed by `isready`). - pub fn new_game(&self) -> Result<(), EngineError> { - self.inner - .borrow_mut() - .on_cmd(Cmd::Setup("ucinewgame".into())) - } - - /// Sends `stop`/`quit` and stops the worker at once (a worker needs no grace - /// time: nothing of it outlives `terminate`). - pub fn quit(self) {} -} - -impl Drop for EngineHandle { - fn drop(&mut self) { - self.inner.borrow_mut().quit(); - } -} diff --git a/crates/uci/tests/fake_engine.rs b/crates/uci/tests/fake_engine.rs index fd39dd8..e843780 100644 --- a/crates/uci/tests/fake_engine.rs +++ b/crates/uci/tests/fake_engine.rs @@ -1,6 +1,4 @@ //! Supervisor tests against the deterministic fake engine (src/bin/fake_uci.rs). -// The process transport. -#![cfg(not(target_family = "wasm"))] use std::collections::{HashMap, HashSet}; use std::path::Path; @@ -700,52 +698,3 @@ fn an_engine_gets_the_variables_given() { assert!(environ.split(|&b| b == 0).any(|v| v.starts_with(b"PATH="))); engine.quit(); } - -/// The state letter of process `pid` (`/proc//stat`), `None` when it is gone. -#[cfg(target_os = "linux")] -fn proc_state(pid: u32) -> Option { - let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; - stat.rsplit_once(") ")?.1.chars().next() -} - -/// `kill_with_parent`: the engine dies with the thread that started it (the program -/// quitting while a handshake hangs); without it, it lives on. -#[cfg(target_os = "linux")] -#[test] -fn an_engine_can_die_with_its_starting_thread() { - let start = |kill: bool| { - std::thread::spawn(move || { - let mut c = config(&[]); - c.kill_with_parent = kill; - let handle = Engine::spawn_with(c, Box::new(|| {})).expect("spawn fake engine"); - let pid = handle.pid(); - // Never quit: as if the program ended under it. - std::mem::forget(handle); - pid - }) - .join() - .expect("the thread") - }; - let gone = |pid: u32| { - let deadline = Instant::now() + Duration::from_secs(5); - loop { - match proc_state(pid) { - None | Some('Z') | Some('X') => return true, - _ if Instant::now() > deadline => return false, - _ => std::thread::sleep(Duration::from_millis(20)), - } - } - }; - let killed = start(true); - assert!(gone(killed), "the engine outlived its thread"); - let kept = start(false); - std::thread::sleep(Duration::from_millis(300)); - assert!( - matches!(proc_state(kept), Some('S' | 'R')), - "{:?}", - proc_state(kept) - ); - unsafe { - libc::kill(kept as i32, libc::SIGKILL); - } -} diff --git a/crates/uci/tests/stockfish.rs b/crates/uci/tests/stockfish.rs index 6c334a1..ba5e068 100644 --- a/crates/uci/tests/stockfish.rs +++ b/crates/uci/tests/stockfish.rs @@ -1,8 +1,6 @@ //! Integration test with a real Stockfish binary. Ignored by default. //! //! Run: UCI_STOCKFISH=/path/to/stockfish cargo test -p uci --test stockfish -- --ignored -// The process transport. -#![cfg(not(target_family = "wasm"))] use std::collections::BTreeMap; use std::time::{Duration, Instant}; diff --git a/crates/uci/tests/worker.rs b/crates/uci/tests/worker.rs deleted file mode 100644 index 078acff..0000000 --- a/crates/uci/tests/worker.rs +++ /dev/null @@ -1,287 +0,0 @@ -//! The worker transport against a fake engine written in JavaScript, in a browser -//! (`docs/dev/web.md`, «Проверки»: wasm-bindgen-test-runner with headless Firefox). -//! -//! The fake engine answers like `src/bin/fake_uci.rs` in the points that matter -//! here: the first PV move of a search is the marker of its position (the first -//! FEN field), info lines come every few milliseconds until `stop`, and flags make -//! it hang, crash or stay silent. -#![cfg(target_family = "wasm")] - -use std::sync::Arc; -use std::sync::atomic::{AtomicU32, Ordering}; -use std::time::Duration; - -use uci::{ - Engine, EngineError, EngineEvent, EngineHandle, EnginePosition, SearchId, SearchLimits, - Starting, TerminationReason, Timeouts, WorkerConfig, -}; -use wasm_bindgen::prelude::*; -use wasm_bindgen_test::*; - -wasm_bindgen_test_configure!(run_in_browser); - -const FAKE: &str = r#" -let searching = null, timer = null, marker = 'startpos', n = 0; -const send = (l) => postMessage(l); -function stopSearch() { - if (searching === null) return; - clearInterval(timer); timer = null; - const m = searching; searching = null; - if (FLAGS.hangOnStop) return; - send('info depth 9 score cp 1 pv ' + m); - send('bestmove ' + m); -} -onmessage = (e) => { - const line = String(e.data), w = line.split(' '); - switch (w[0]) { - case 'uci': - if (FLAGS.silent) return; - send('id name Fake Worker'); send('id author Test Suite'); - send('option name MultiPV type spin default 1 min 1 max 10'); - send('option name Hash type spin default 16 min 1 max 1024'); - if (!FLAGS.noUciok) send('uciok'); - break; - case 'isready': if (!FLAGS.noReadyok) send('readyok'); break; - case 'position': - if (w[1] === 'fen') marker = w[2]; - else { const i = w.indexOf('moves'); marker = i > 0 && w.length > i + 1 ? w[w.length - 1] : 'startpos'; } - break; - case 'go': - if (FLAGS.crashOnGo) throw new Error('fake engine crashed'); - searching = marker; n = 0; - if (w[1] === 'nodes') { send('info depth 1 score cp 3 nodes ' + w[2] + ' pv ' + marker); stopSearch(); break; } - timer = setInterval(() => { n++; send('info depth ' + n + ' score cp ' + n + ' pv ' + searching); }, 5); - break; - case 'stop': stopSearch(); break; - case 'quit': close(); break; - } -}; -"#; - -/// A worker script of the fake engine with these flags (a `blob:` URL). -fn fake(flags: &str) -> String { - let source = format!("const FLAGS = {{{flags}}};\n{FAKE}"); - let parts = js_sys::Array::of1(&JsValue::from_str(&source)); - let opts = web_sys::BlobPropertyBag::new(); - opts.set_type("text/javascript"); - let blob = web_sys::Blob::new_with_str_sequence_and_options(&parts, &opts).unwrap(); - web_sys::Url::create_object_url_with_blob(&blob).unwrap() -} - -fn timeouts() -> Timeouts { - Timeouts { - uciok: Duration::from_millis(1500), - readyok: Duration::from_millis(1500), - stop: Duration::from_millis(500), - quit: Duration::from_millis(500), - } -} - -async fn sleep(ms: i32) { - let promise = js_sys::Promise::new(&mut |resolve, _| { - web_sys::window() - .unwrap() - .set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms) - .unwrap(); - }); - wasm_bindgen_futures::JsFuture::from(promise).await.unwrap(); -} - -/// Starts the fake engine and waits for its handshake; also counts the waker's calls. -async fn start(flags: &str) -> (Result, u32) { - let woke = Arc::new(AtomicU32::new(0)); - let w = Arc::clone(&woke); - let mut config = WorkerConfig::new(fake(flags)); - config.timeouts = timeouts(); - let mut starting: Starting = Engine::start_worker( - config, - Box::new(move || { - w.fetch_add(1, Ordering::Relaxed); - }), - ) - .expect("worker created"); - for _ in 0..400 { - if let Some(r) = starting.poll() { - return (r, woke.load(Ordering::Relaxed)); - } - sleep(10).await; - } - panic!("the handshake neither ended nor timed out"); -} - -/// Events until `pred` holds for one (inclusive), or `ms` pass. -async fn until(h: &EngineHandle, ms: u32, pred: impl Fn(&EngineEvent) -> bool) -> Vec { - let mut out = Vec::new(); - for _ in 0..ms / 5 { - while let Some(ev) = h.try_recv() { - let hit = pred(&ev); - out.push(ev); - if hit { - return out; - } - } - sleep(5).await; - } - panic!("no expected event in {ms} ms: {out:?}"); -} - -fn fen(marker: &str) -> EnginePosition { - EnginePosition::fen(format!("{marker} w - - 0 1"), Vec::::new()) -} - -#[wasm_bindgen_test] -async fn handshake_then_analysis_and_stop() { - let (h, woke) = start("").await; - let h = h.expect("started"); - assert_eq!(h.info().name.as_deref(), Some("Fake Worker")); - assert_eq!(h.info().options.len(), 2); - assert!(woke > 0, "the waker was not called"); - h.set_multipv(2).unwrap(); - assert!(matches!( - h.set_multipv(11), - Err(EngineError::InvalidOptionValue { .. }) - )); - h.analyze(fen("m1"), SearchId(1)).unwrap(); - let evs = until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; - assert!(evs.contains(&EngineEvent::SearchStarted { - search_id: SearchId(1) - })); - h.stop().unwrap(); - let evs = until(&h, 2000, |e| matches!(e, EngineEvent::BestMove { .. })).await; - match evs.last() { - Some(EngineEvent::BestMove { - search_id, best, .. - }) => { - assert_eq!(*search_id, SearchId(1)); - assert_eq!(best.as_deref(), Some("m1")); - } - other => panic!("{other:?}"), - } - assert!(h.is_running()); -} - -#[wasm_bindgen_test] -async fn rapid_requests_start_only_the_latest_and_never_mix_output() { - let (h, _) = start("").await; - let h = h.expect("started"); - h.analyze(fen("a"), SearchId(1)).unwrap(); - until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; - for (id, m) in [(2, "b"), (3, "c"), (4, "d")] { - h.analyze(fen(m), SearchId(id)).unwrap(); - } - let evs = until(&h, 3000, |e| { - matches!( - e, - EngineEvent::Info { - search_id: SearchId(4), - .. - } - ) - }) - .await; - for id in [2, 3] { - assert!(evs.contains(&EngineEvent::Superseded { - search_id: SearchId(id) - })); - assert!(!evs.contains(&EngineEvent::SearchStarted { - search_id: SearchId(id) - })); - } - for e in &evs { - if let EngineEvent::Info { search_id, info } = e { - let want = if *search_id == SearchId(1) { "a" } else { "d" }; - assert_eq!(info.pv.first().map(String::as_str), Some(want), "{e:?}"); - } - } - // A node-limited search ends by itself. - h.search(fen("n"), SearchId(5), SearchLimits::Nodes(1000)) - .unwrap(); - let evs = until(&h, 2000, |e| { - matches!( - e, - EngineEvent::BestMove { - search_id: SearchId(5), - .. - } - ) - }) - .await; - assert!(matches!(evs.last(), Some(EngineEvent::BestMove { best: Some(b), .. }) if b == "n")); -} - -#[wasm_bindgen_test] -async fn an_engine_hung_on_stop_is_terminated() { - let (h, _) = start("hangOnStop: true").await; - let h = h.expect("started"); - h.analyze(fen("h"), SearchId(1)).unwrap(); - until(&h, 2000, |e| matches!(e, EngineEvent::Info { .. })).await; - h.stop().unwrap(); - let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await; - assert_eq!( - evs.last(), - Some(&EngineEvent::Terminated(TerminationReason::Hung { - waiting_for: "bestmove" - })) - ); - assert!(!h.is_running()); - assert!(matches!(h.stop(), Err(EngineError::NotRunning))); -} - -#[wasm_bindgen_test] -async fn a_crash_ends_the_session() { - let (h, _) = start("crashOnGo: true").await; - let h = h.expect("started"); - h.analyze(fen("x"), SearchId(1)).unwrap(); - let evs = until(&h, 3000, |e| matches!(e, EngineEvent::Terminated(_))).await; - assert_eq!( - evs.last(), - Some(&EngineEvent::Terminated(TerminationReason::Exited { - status: None - })) - ); -} - -#[wasm_bindgen_test] -async fn handshake_failures_are_named() { - let (silent, _) = start("silent: true").await; - assert!( - matches!(silent, Err(EngineError::NotUci { .. })), - "{silent:?}" - ); - let (no_uciok, _) = start("noUciok: true").await; - assert!( - matches!( - no_uciok, - Err(EngineError::HandshakeTimeout { - waiting_for: "uciok" - }) - ), - "{no_uciok:?}" - ); - let (no_readyok, _) = start("noReadyok: true").await; - assert!( - matches!( - no_readyok, - Err(EngineError::HandshakeTimeout { - waiting_for: "readyok" - }) - ), - "{no_readyok:?}" - ); - // A script that does not load. - let mut config = WorkerConfig::new("/no-such-engine.js"); - config.timeouts = timeouts(); - let mut starting = Engine::start_worker(config, Box::new(|| {})).expect("worker created"); - let mut result = None; - for _ in 0..400 { - result = starting.poll(); - if result.is_some() { - break; - } - sleep(10).await; - } - assert!( - matches!(result, Some(Err(EngineError::ProcessExited { .. }))), - "{result:?}" - ); -} diff --git a/docs/agent-team.md b/docs/agent-team.md index 27bc065..82872cf 100644 --- a/docs/agent-team.md +++ b/docs/agent-team.md @@ -40,13 +40,3 @@ opencode api get '/api/agent?location[directory]=/home/vrubel/services/chessBase - https://opencode.ai/v2/docs/agents - https://opencode.ai/v2/docs/config - https://opencode.ai/v2/docs/api - -## Добавлено 2026-11-01 — запуск в Kimi Code CLI - -Разработка продолжается в Kimi Code CLI. OpenCode в окружении сейчас не установлен (`opencode` отсутствует в PATH), поэтому повторная проверка регистрации профилей через API не выполнялась; файлы остаются на месте и пригодны для возврата в OpenCode. - -Профили `.opencode/agents/*.md` остаются каноническими определениями ролей для обеих сред; их содержимое нейтрально к среде исполнения (упоминания OpenCode в профиле оркестратора относятся только к запуску внутри OpenCode). В Kimi Code профили не регистрируются: оркестратор (основная сессия) передаёт роль субагенту через задание со ссылкой на файл профиля. Соответствие ролей типам субагентов (`coder`, `plan`, `explore`) и правила делегирования зафиксированы в `AGENTS.md`, раздел «Команда». - -Следы Claude Code: каталог `.claude/` профилей агентов не содержит — там только `settings.local.json` (разрешения) и ворктри `.claude/worktrees/agent-a635674bcaa3af196` с сессии агента. Командные профили хранятся исключительно в `.opencode/agents/`; дублировать их под `.claude/` или `.kimi/` не нужно. - -2026-11-01 профили ролей усилены по требованию владельца: единые правила доказательности (факт/гипотеза/предложение), обязательный формат отчёта, жёсткие предметные инварианты и ворота качества в профилях разработчика и тестировщика. diff --git a/docs/architecture.md b/docs/architecture.md index 7c47908..406528e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,118 +1,118 @@ -# Архитектура ChessPenguin +# Архитектурное предложение -Статус: описание реализованной системы для выпуска **2.5.2**, обновлено 2026-11-30. Тренажёр дебютов включён в настольное приложение с пометкой α. -Первоначальный документ с этим именем — архитектурное предложение этапа исследования -(2026-10-17) — сохранён в `docs/research/architecture-proposal-2026-10-17.md`. +Дата: 2026-10-17. Статус: **рекомендация для согласования**, приложение ещё не реализовано. -ChessPenguin — локальная шахматная база и анализ: PGN и ChessBase (`.cbh`/`.cbv`, архивы -zip/7z), просмотр и ввод партий с вариантами и комментариями, анализ UCI-движками, -обзор партии, подготовка к сопернику, игра с компьютером (Maia, Rodent), онлайн-партии -Lichess/Chess.com. Платформы: Linux (основная), Windows, macOS, Android; веб-версия — -этап 2 на ветке `web-app` (`docs/dev/web.md`, задача 22). +## Краткое решение -## Состав workspace +Предлагаем **нативное Linux-приложение на Rust + egui/eframe + wgpu**, по стеку PhotoCraft, с независимым шахматным ядром, PGN-документом и управлением внешними UCI-движками. Для первой версии — одно окно, библиотека и рабочее пространство партии, один активный движок с несколькими линиями анализа. -Cargo workspace, edition 2024, rust-version 1.97, GPL-3.0-or-later. -Ключевые зависимости: shakmaty 0.30 (правила, SAN/FEN), egui/eframe 0.36 (wgpu, -Wayland/X11, AccessKit), encoding_rs, serde. Полный список — `Cargo.toml` + `Cargo.lock`. +Пользователь уже подтвердил открытый исходный код, учебные базы на сотни/тысячи партий и ввод ходов/вариантов с экспортом. Точная фиксация решений — `decisions.md`. -| Часть | Назначение | Подробности | +## Почему этот стек + +1. Соответствует прямому пожеланию использовать технологии PhotoCraft: в его desktop manifest явно включены eframe, egui, wgpu, Wayland/X11 и AccessKit. +2. Rust обслуживает и интерфейс, и PGN, и процессы движков; не нужен отдельный frontend-язык. +3. Рисование доски и стрелок, таблица и изменяемые панели укладываются в egui. Для нотации потребуется специализированный компонент. +4. `storytold/craft-libs` предлагает действительно общие компоненты: `craft-ui`, `craft-settings`, `craft-atomic`. Их можно подключать выборочно, на фиксированной ревизии, через тонкий адаптер. +5. В согласованную первую версию не входит полноценное редактирование rich text и миллионов записей, что уменьшает основные риски egui. + +Оговорка: PhotoCraft в каталоге отмечен early alpha; общие библиотеки не являются гарантированно стабильным SDK. Качество будущего приложения проверяется своим прототипом и тестами. + +| Вариант | Оценка | +| --- | --- | +| **Rust + egui/eframe** | Основная рекомендация; доску и нотацию делаем под наши сценарии | +| Tauri 2 + React/TypeScript | Резерв при существенных проблемах текстового UI/доступности; можно использовать Chessground, но появляются webview и второй стек | +| GTK4/Relm4 | Сильная Linux-интеграция; меньше соответствия выбранному PhotoCraft-стеку, шахматные компоненты также собственные | + +Важно: другие продукты организации ArtCraft используют и Tauri/React. Утверждение о egui относится конкретно к PhotoCraft/native Craft Apps, а не ко всем репозиториям организации. + +## Состав компонентов + +| Область | Рекомендуемый компонент | Наша работа | | --- | --- | --- | -| `crates/chess-core` | Документ партии: арена узлов со стабильными `NodeId`, собственный байтовый PGN-лексер и writer, кодировки, диагностика, терпимость к повреждённым данным | `docs/dev/chess-core.md` | -| `crates/chess-import` | Всё, что не простой PGN: ChessBase `.cbh`/`.cbv`, архивы; большие базы читаются на месте; фильтры/сортировка каталога; поиск по позиции (ускоритель `.cbb`, свой бустер, дебютный индекс, таблица позиций PGN) | `docs/dev/import.md` | -| `crates/uci` | Протокол UCI как чистый автомат без ввода-вывода; транспорты: процесс (десктоп) и Web Worker (браузер) | `docs/dev/uci.md` | -| `crates/game-review` | Обзор партии целиком в фоне: задание, отчёт, график, кэш; детерминированные оценки (`go nodes`, сверка со Stockfish 19), метки !/!!, калиброванные на разметке chess.com | — | -| `crates/prep` | Подготовка к сопернику: дерево его дебютов, периоды (по давности/числу партий), сохранённые подготовки, поиск ошибок движком | — | -| `crates/openings` | Названия дебютов (ECO) | — | -| `crates/online-games` | API Lichess и Chess.com: проба, поиск ника, скачивание в PGN-базу с возобновлением | — | -| `crates/play` | Игра с компьютером: Rodent IV/V, личности, книги, часы, предложение ничьей | — | -| `crates/maia` | Нейросетевой соперник Maia: веса, checkpoint, шкала силы | — | -| `crates/trainer` | Дебютные репертуары: PGN-дерево, граф транспозиций, общий LearningItem, независимые попытки, SRS, сессии, аналитика и versioned JSON; Android сохраняет legacy API | `docs/design/repertoire-training.md` | -| `crates/releases` | Данные выпусков для обновления | — | -| `crates/mobile-api` | Общий API Android: сессия партии, движок, обзор, игра, тренировка, обновления | — | -| `apps/desktop` | Приложение: библиотека `chesspenguin_app` (весь интерфейс, ~модули в `src/`) + тонкий `main.rs`; i18n на 6 языков | `docs/dev/desktop.md` | -| `apps/web` | Та же библиотека в WebAssembly: `start(canvas)` → `start_web`; платформенный слой браузера | `docs/dev/web.md` | -| `androidApp` | Kotlin-оболочка (Gradle, Rust через `mobile-api`) | `androidApp/` | -| `website` | Сайт продукта, отдельный деплой | `website/README.md` | +| UI и окно | egui + eframe + wgpu, egui_extras | Экраны, доска, нотация, варианты, клавиатура | +| Общие UI-примитивы | craft-ui выборочно | Визуальная система и компоненты шахматного продукта | +| Правила шахмат | shakmaty | Связь ходов, узлов документа, истории и интерфейса | +| Чтение PGN | pgn-reader | Visitor, дерево, совместимость старых файлов, диагностика | +| Экспорт PGN | Собственный writer | Сохранение тегов, комментариев, NAG и вариантов | +| Legacy-кодировки | encoding_rs как кандидат | Выбор кодировки, сохранение оригинала и диагностик; версию/API проверить на прототипе | +| UCI | Tokio process + vampirc-uci как кандидат | Управление процессом, поисками, таймаутами и MultiPV | +| Библиотека | Метаданные в памяти в прототипе; rusqlite для постоянного индекса | Каталог файлов, поиск, инвалидирование кэша, фоновый импорт | +| Настройки | craft-settings как кандидат | Собственная схема настроек и миграции | +| Файловые диалоги | rfd | Обработка отмены и ошибок | +| Clipboard | eframe API / arboard при необходимости | Копирование PGN и проверка на Wayland | +| Звук | rodio | Предзагрузка коротких звуков, mute/volume, устойчивость к отсутствию аудио | -## Слои и потоки данных +Версии согласовать как комплект. В проверенном PhotoCraft/craft-ui используется линия egui **0.36**; нельзя механически смешивать её с новой несовместимой версией egui_extras. Зафиксировать toolchain, git revisions и Cargo.lock после пробной сборки. Проверенный текущий workspace shakmaty требует более новый Rust, чем PhotoCraft; подробности и SHA — в `research/stack-options.md`. + +Предложение лицензии проекта — **GPL-3.0-or-later**, поскольку shakmaty и pgn-reader имеют эту лицензию. Конкретная лицензия ещё требует подтверждения. Для фигур и звука вести отдельный список происхождения и лицензий; подбор — `research/reuse-and-assets.md`. + +## Границы модулей ```text -desktop (egui, apps/desktop) │ web (wasm, apps/web) │ android (Kotlin + mobile-api) - │ одна библиотека chesspenguin_app │ │ общие крейты через mobile-api - ▼ ▼ - platform (native │ web) — каталоги, файлы, фон, диалоги, clipboard - ▼ - приложение: LibraryState, GameView (документ + Undo/Redo), AnalysisPreview, - UCI-контроллер, обзор, подготовка, игра, онлайн, обновление - ▼ - crates: chess-core │ chess-import │ uci │ game-review │ prep │ play │ maia │ … +desktop UI + ├── LibraryState: выбранная база, поиск, строка, прокрутка + ├── DocumentView: активный узел, раскрытые ветки, ориентация + └── AnalysisPreview: снимок PV и точка возврата + │ команды / события + ▼ +application + ├── GameDocument + команды Undo/Redo + ├── PGN import/export + диагностика + ├── Library repository + настройки + └── UCI supervisor → отдельный engine process + │ + ▼ +shakmaty: правила, позиции, SAN/UCI/FEN ``` -- **UI не блокируется**: открытие/сканирование баз, импорт, поиск по позиции, обзор - партии и перевод работают в фоне с прогрессом и отменой; результаты возвращаются - событиями, UI опрашивает их каждый кадр (`Waker` → `request_repaint`). -- **Документ**: арена узлов, стабильные идентификаторы, один шаг Undo на операцию. - Исходные байты PGN неизменны; запись только явная («Сохранить как…», свои базы). -- **Анализ привязан к истории позиции** (`EngineHistory`: стартовая позиция + ходы UCI), - не к FEN и не к курсору; события с чужым `SearchId` отбрасываются. Предпросмотр PV — - снимок линии, документ меняет только «Добавить как вариант» (один шаг Undo). -- **UCI**: граница поисков — `bestmove`, затем обязательный `isready`/`readyok`, и - только потом новый `position`/`go`; опции во время поиска откладываются. Процесс — - дочерний, без shell, с таймаутами, kill при `Drop`, stderr ограничен. -- **Импорт**: всё не-PGN приводится к `PgnDatabase` (малые базы — конвертация в памяти) - или читается на месте (`Base` для больших ChessBase); дальше единый путь: библиотека, - нотация, анализ, экспорт в PGN. -- **Индексы**: ускорители позиции и дебютный индекс — в кэше приложения (`boosters/`, - `.cpo` от канонического пути/размера/даты `.cbg`); атомарная запись, - непригодный файл перестраивается. Таблица позиций PGN строится в памяти. -- **Обучение дебютов**: PGN-дерево отделено от знания хода. Ключ LearningItem — - `(profile, FEN4, expected UCI)`, поэтому транспозиции и одинаковые ходы из разных - репертуаров используют общую историю. Попытка, SRS-расписание и snapshot сессии - сохраняются атомарно в фоновом worker; UI получает результат через канал и не принимает - повторный ответ до завершения записи. `client_attempt_id` исключает дубли, revision обнаруживает - конфликт одновременных сессий. Исторические снимки не пересчитываются задним числом. - Агрегаты и подготовка сессии выполняются вне UI-потока. +Это границы ответственности, а не требование сразу заводить множество crates. Для первого среза достаточно компактного workspace с библиотекой ядра и desktop-приложением; `pgn`, `library`, `uci`, `platform`, `ui` могут начинаться как модули. Выносить отдельно по фактическим границам зависимостей и тестирования. -## Ключевые решения +### Документ и PGN -Живой журнал — `docs/decisions.md`. Опоры архитектуры: +- Документ хранит упорядоченные теги, корневую позицию, дерево со стабильными ID, комментарии, NAG, неизвестные аннотации и результат. +- У узла один родитель и упорядоченные продолжения; первое — основное. Альтернативы начинаются от позиции до заменяемого хода. +- Активный узел и раскрытие вариантов — состояние представления, не изменение документа. +- Исходные байты/фрагменты и информация о кодировке сохраняются отдельно от нормализованной шахматной модели. Не обещать побайтовую идентичность после редактирования. +- PGN reader сам не строит дерево, не проверяет легальность и по умолчанию может пропускать варианты: visitor должен явно обрабатывать их. +- В текущих материалах найдены не-UTF-8 тексты, учебный `--` и FEN с fullmove=0. Нужен отдельный слой совместимости. Нормализацию не выдавать за оригинал; непонятные фрагменты не отбрасывать молча. +- Полный независимый аудит подтвердил 896 записей, 62 263 узла, вложенность RAV до 7, 846 FEN и 269 учебных null moves. В записи №335 учебника повреждены границы комментария: контрольный парсер теряет фрагмент текста без ошибки. Проверка покрытия исходного текста обязательна; успешный разбор сам по себе недостаточен. +- В первой версии сохраняем отдельную партию через «Сохранить как…». Исходная многопартийная база остаётся источником, а не объектом неявной перезаписи. -1. egui/eframe 0.36 + wgpu; одна кодовая база интерфейса для десктопа и веба - (библиотека + platform-слой), Android — общие крейты через `mobile-api`. -2. Собственный байтовый PGN-лексер: pgn-reader молча пропускает токены и не даёт - смещений (запись №335), поэтому он — лишь независимый эталон в тестах. -3. Терпимость к реальным данным: legacy-кодировки, FEN fullmove=0, `--`, повреждённые - комментарии — всё сохраняется и диагностируется, оригинал доступен (`raw_text`). -4. UCI — явный автомат без ввода-вывода; транспорт подменяем (процесс/воркер). -5. Обзор партии детерминирован: тот же движок-эталон (`go nodes` + сверка Stockfish 19), - одинаковые метки на всех машинах; запись результата в партию — один шаг Undo. -6. Файл не перезаписывается неявно: запись в свои базы — append/replace/remove с - проверкой, что файл с диска не изменился. +### Анализ и предпросмотр -## Проверка качества +- UCI работает в отдельном процессе; CPU/IO не блокируют UI. stdout и stderr читаются независимо. +- На смене позиции остановить старый поиск и дождаться его `bestmove`, затем запустить новый. `readyok` и локальный request ID сами по себе не отделяют поиски. +- Для обычной ветви отправлять начальную позицию и историю ходов; текущий FEN не заменяет историю повторений. +- Учебные null moves обрабатываются отдельно; синтетическую учебную историю не выдавать движку за обычную партию. +- Отображаемая оценка относительно белых, независимо от переворота доски. Мат хранить отдельно от centipawns. +- Клик по PV открывает зафиксированный снимок с явной меткой «Предпросмотр». Выход восстанавливает узел партии. Только команда «Добавить линию как вариант» изменяет документ и Undo-историю. -- `cargo test -p `: unit + fixtures; корпусные тесты на `pgnFilesforExample/` - пропускаются без файлов; тесты на Mega помечены `#[ignore]`. -- UCI-гонки — с детерминированным `fake_uci`; реальный Stockfish — только - интеграционный `#[ignore]`. -- Ручная проверка UI — dev-хуками `CP_*` (снимки в `docs/screenshots/`), - `chesspenguin --bench <база>` — замеры на чужих машинах. -- Независимые QA-проходы — `docs/qa/`; продуктовые проверки тестировщиком — - по ролевому профилю `.opencode/agents/tester.md`. +## Интерфейс первой версии -## Актуальность и границы +**Библиотека:** сверху компактная полка баз и «Добавить PGN», ниже поиск и таблица партий. **Партия:** слева крупная доска, справа анализ и нотация с комментариями; регулируемые панели. «Назад в библиотеку» восстанавливает выбранную базу и строку. -- Реализовано и выпущено: библиотека PGN/ChessBase, нотация с редактированием, - анализ и обзор партии, подготовка к сопернику, игра (Maia/Rodent), онлайн-партии, - свои базы, перевод комментариев, автоматическое обновление. История — `CHANGELOG.md`. -- 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`. -- Не реализовано: веб-версия в проде (этап 2), тренировочные файлы (задача 23), - автоматический сбор дебютного репертуара из большой базы (задача 36), синхронизация, - движковая оценка запоминания и соревнования из V2 тренажёра. +Предлагаемые defaults для прототипа: русский UI, спокойная тёмная тема с возможностью светлой, один клик выбирает строку, двойной клик/Enter открывает партию. Эти детали не считаются уже утверждёнными пользователем. Макеты и состояния — `research/ux-direction.md`; расширенные редакторские команды из этого исследования отложены согласно `decisions.md`. + +## Следующий шаг и критерий выбора + +После согласования стека — технический прототип: окно на Hyprland/Wayland, SVG-доска, таблица реального PGN, кликабельные вложенные варианты, длинный русский комментарий, клавиатура и clipboard. Одновременно проверить парсер на учебных расширениях корпуса. Этот шаг проверяет самые дорогие предположения; остальная последовательность — `implementation-plan.md`. + +Если UI-прототип проходит, фиксируем стек и реализуем полный первый сценарий. Если проблема именно в нотации/доступности/платформенной интеграции и её устранение непропорционально, возвращаемся к сравнению с Tauri до наращивания UI. + +## Фактическое состояние окружения + +- После первоначального обследования пользователь установил Rust: подтверждены rustc/cargo **1.99.1**, rustup **1.29.1**. В PATH текущего процесса инструменты пока не появились; доступны по `~/.cargo/bin/`. Для будущих команд использовать полный путь или локально дополнить PATH. +- Пользователь завершил загрузку `engines/stockfish-linux-x86-64-universal.tar.gz`. SHA-256 и размер совпадают с официальным release asset **Stockfish 19**. Успешно проверены `uci`, `isready`, поиск глубины 4 и `quit` (exit 0). Бинарник временно извлечён для проверки и затем удалён; исходный архив сохранён. +- Linux: Omarchy / Hyprland / Wayland. GUI-прототип и продуктовые тесты пока не запускались. +- Пять профилей OpenCode созданы и обнаружены API без перезапуска; сведения — `agent-team.md`. + +## Материалы исследования + +- `research/requirements-and-pgn.md` — требования и фактическая структура обоих PGN. +- `research/ux-direction.md` — разбор семи скриншотов и UX-предложение. +- `research/stack-options.md` — первоисточники, версии, SHA, лицензии и сравнение стеков. +- `research/quality-plan.md` — обследование окружения и план проверок. +- `research/reuse-and-assets.md` — Lichess, фигуры и звук. + +Ключевые upstream: https://github.com/storytold/photocraft, https://github.com/storytold/craft-libs, https://github.com/niklasf/shakmaty. diff --git a/docs/chesstempo_opening_trainer_TZ.md b/docs/chesstempo_opening_trainer_TZ.md deleted file mode 100644 index 618252e..0000000 --- a/docs/chesstempo_opening_trainer_TZ.md +++ /dev/null @@ -1,945 +0,0 @@ -# Техническое задание: тренажёр изучения шахматных дебютов по принципам ChessTempo - -**Версия:** 2.0 -**Дата исследования:** 04.11.2026 -**Референс:** ChessTempo Opening Training -**Тип документа:** функциональное ТЗ + спецификация алгоритма обучения + спецификация статистики -**Язык интерфейса:** русский (внутренние идентификаторы могут быть английскими) - -> **Граница достоверности.** Исследованы публичный сайт ChessTempo, [официальное руководство](https://www.chesstempo.com/manual/en/manual.html), [FAQ](https://www.chesstempo.com/faq/) и ответы разработчика Richard на форуме. Авторизованная тренировка с реальными пользовательскими данными не проходилась; исходный код серверного алгоритма не доступен. Поэтому документ **не утверждает**, что предложенные внутренние схемы, формулы для неопубликованных деталей и SQL-реализация точно совпадают с ChessTempo. -> -> Обозначения: **[ПОДТВЕРЖДЕНО]** — явно описано в официальном руководстве; **[РАЗРАБОТЧИК]** — подтверждено ответом разработчика на форуме; **[ПРОЕКТ]** — предлагаемый для реализации точный алгоритм; **[НЕИЗВЕСТНО]** — публичного определения не найдено. Наличие [ПРОЕКТ] не означает, что функция существует в оригинале. - ---- - -## 1. Цель и границы продукта - -Необходимо реализовать модуль, который помогает пользователю создавать дебютные репертуары, изучать **свои ходы в конкретных шахматных позициях**, систематически повторять забываемые ответы и видеть достоверную статистику изученности репертуара, отдельных веток и ходов. - -Главный принцип: **изучается не файл PGN и не дебютное название, а запоминание правильного хода в определённой позиции**. Полные варианты нужны как контекст. Если разными порядками ходов получена та же позиция, история знания используется совместно. - -Обязательные модули: - -1. Репертуары за белых и чёрных; дерево вариантов; импорт/экспорт PGN. -2. Представление шахматного материала графом позиций с транспозициями. -3. Тренировка за выбранную сторону, автоматические ходы соперника. -4. Персональная история проверок и интервальное повторение (SRS). -5. Контекстные ходы, подсказки, работа с ошибками. -6. Три режима тренировки и четыре алгоритма введения новых ходов. -7. Подробная статистика: статус, изученность, просроченные повторения, точность, история, динамика, проблемные ходы. -8. Прозрачные формулы процента изучения и статуса *«репертуар изучен»* (предложенная продуктовая надстройка над механикой ChessTempo). - -Вне базового MVP: собственная база гроссмейстерских партий, кластерное обучение, рейтинг игрока по дебютам, оценка движком качества запоминания, рекомендательная система на базе ИИ. - -## 2. Что действительно означает «дебют изучен» в ChessTempo - -### 2.1. В оригинале изучается отдельный ход, а не дебют целиком - -**[РАЗРАБОТЧИК]** Ход получает статус **Learnt** после **трёх или более правильных самостоятельных ответов подряд**. Если пользователь ошибся, ход снова считается **Learning**. Источник: [форум, ответ Richard в теме «Opening training no more positions to schedule yet?»](https://chesstempo.com/forum/topic/opening-training-no-more-positions-to-schedule-yet/9962/). - -**[РАЗРАБОТЧИК]** С точки зрения планировщика есть две основополагающие группы: **Unseen** (ещё не введён в обучение) и **Learning** в широком смысле (уже находится в системе повторений). Метки *Learnt* и *Uncertain* — это **производные категории для показа статистики**. Они не являются отдельными алгоритмами планирования. - -**[ПОДТВЕРЖДЕНО]** Сайт показывает число изучаемых ходов, число изученных ходов, общее число ходов и число `Uncertain`; в интерфейсе встречается вид `Learnt: 2/47` и `Learning: 4`. Источники: [руководство, раздел 10.5](https://www.chesstempo.com/manual/en/manual.html#repertoirestats), [форум с разбором статистики](https://chesstempo.com/forum/topic/trying-to-understand-how-opening-training-works-with-the-scheduling-option/10924/). - -**Вывод:** у ChessTempo нет подтверждённого отдельного глобального флага `whole_opening_mastered=true`, который можно приписать всему дебюту. Вместо этого отображаются результаты изучения составляющих его ходов. Требование «дебют изучен / не изучен» нужно формализовать самостоятельно (§ 5). - -### 2.2. Четыре отображаемых статуса - -| Статус | Значение | Как появляется | -|---|---|---| -| **Unseen** | Есть в репертуаре, ещё не введён в систему повторения | При импорте/добавлении нового обучаемого хода | -| **Learning** | Введён в обучение, но не достиг порога закрепления | После первой проверки или после ошибки | -| **Learnt** | Последние 3 и более самостоятельных ответа правильны | При достижении `correct_streak >= 3` | -| **Uncertain** | Ранее был Learnt, но его проверка слишком давно просрочена | Становится «сомнительно закреплённым» со временем без новой попытки | - -Уточнения: - -- `Uncertain` — **подмножество ранее изученных (`Learnt`)**, а не дополнительное количество независимых ходов. В публичном объяснении это категория ходов, которые удовлетворяют критерию Learnt, но давно не перепроверялись. Обязательно **не считать Uncertain дважды** при вычислении общего количества. -- Ход может быть **Learnt и одновременно Due**: срок повторения пришёл, но трёх успешных ответов подряд никто не отменял. -- `Due = 0` **не означает** `Learnt = Total`: все назначенные на сейчас проверки выполнены, однако остались ходы `Unseen` или `Learning`. -- `Uncertain` — не то же самое, что любой Due. **[НЕИЗВЕСТНО]** Конкретный срок, после которого обычное Due становится Uncertain, в найденной документации не раскрыт. Ниже определён конфигурируемый проектный вариант. -- Статусы Learnt и Uncertain не дают права отменять будущие повторения: знания нужно регулярно подтверждать. - -### 2.3. Как правильно отображать статусы без пересечений — [ПРОЕКТ] - -В хранилище задаём два независимых свойства: - -- `introduced` — добавлен ли ход в расписание SRS; -- `correct_streak` — длина последовательности правильных самостоятельных ответов; - -и вычисляем флаг `uncertain` для закреплённых ходов, которые существенно просрочены. - -В UI удобно показывать **взаимоисключающие группы**: - -```text -UNSEEN: introduced = false -LEARNING: introduced = true AND correct_streak < 3 -LEARNT_FRESH: introduced = true AND correct_streak >= 3 AND NOT uncertain -UNCERTAIN: introduced = true AND correct_streak >= 3 AND uncertain -``` - -**Не создавать отдельного физического состояния Resistant вместо Learning:** устойчиво проблемный ход — это **дополнительный признак**, пересекающийся с Learning/другими состояниями, но не меняющий их арифметику. - -Для экрана, похожего на ChessTempo, счётчик `Learnt` рекомендуется определять как `LEARNT_FRESH + UNCERTAIN`, а `Uncertain` выводить отдельно как уточнение. В интерфейсе подпись должна прямо объяснять вложенность. Можно также показывать отдельный счётчик «Надёжно изучено» = `LEARNT_FRESH`. - -### 2.4. Формула Uncertain — [ПРОЕКТ], а не опубликованный алгоритм ChessTempo - -```text -is_uncertain = - correct_streak >= 3 - AND now_utc > next_review_at + max(7 дней, 0.25 * previous_interval) -``` - -Значения `7 дней` и `0.25` — **предлагаемые настраиваемые коэффициенты**, НЕ подтверждённые значения ChessTempo. Реализация обязана выделить вычисление в отдельную функцию `is_uncertain(item, now, settings)`. При изменении настроек статусы должны пересчитываться без переписывания истории ответов. - -После новой самостоятельной проверки: - -- правильный ответ: состояние остаётся/становится Learnt, дата следующей проверки переносится; Uncertain снимается; -- ошибка: `correct_streak=0`, состояние становится Learning; Uncertain снимается; -- отсутствие ответа: никаких искусственных успехов или ошибок, статус изменяется только за счёт времени. - -## 3. Предметная модель и единица учёта - -### 3.1. Сущности - -| Сущность | Ключевые данные | -|---|---| -| `User` | `id`, настройки, часовой пояс | -| `Repertoire` | `id`, `owner_id`, `name`, `color`, начальная позиция | -| `Position` | нормализованное состояние, уникальный `position_key` | -| `MoveEdge` | `from_position_key`, `move_uci`, `to_position_key`, SAN, аннотации | -| `RepertoireEdge` | `repertoire_id`, ссылка на ребро, включён/выключен, главный/побочный, порядок | -| `LearningItem` | `user_id`, `position_key`, `move_uci`, интервалы, серии, суммарные показатели | -| `TrainingAttempt` | событие проверки: ожидалось/сыграно, результат, время, подсказка | -| `TrainingSession` | режим, охват, порядок, завершённые элементы, настройки на момент старта | -| `RepertoireSnapshot` | снимок агрегатов на дату/момент | - -### 3.2. Ключ учебного элемента - -```text -LearningItemKey = (user_id, position_key, expected_move_uci) -``` - -**[ПРОЕКТ]** Данные запоминания принадлежат **пользователю**, а не одной ветке репертуара. Если два репертуара ссылаются на один и тот же учебный элемент, он имеет одну историю и одно расписание. Появление общего хода во втором репертуаре не создаёт второй учебный элемент. - -**[ПОДТВЕРЖДЕНО]** ChessTempo использует единое представление шахматной позиции для транспозиций, общий прогресс и графические переходы между ветвями. Источник: [руководство, § 17.4.6](https://www.chesstempo.com/manual/en/manual.html#transpositions). - -### 3.3. Почему позиция не равна строке PGN - -Пример одной позиции из двух последовательностей: - -```text -Путь A: 1.d4 Nf6 2.c4 e6 3.Nf3 d5 -Путь B: 1.d4 d5 2.c4 e6 3.Nf3 Nf6 -``` - -В обоих случаях последующие ходы пользователя нужно проверять на основе одной и той же позиции. Требуется нормализованный ключ с доской, очередью хода, рокировочными правами и легально релевантным взятием на проходе. Счётчики FEN для 50 ходов и номера хода не должны разносить одинаковые дебютные позиции на разные учебные записи. Полная проверка легальности ходов обязательна. - -### 3.4. Варианты с несколькими собственными ответами — [ПРОЕКТ] - -Если в одной позиции активны два собственных хода, системе нужно **явно определить, чему именно она обучает**: - -- рекомендуемый режим `one_answer_per_position`: один выбранный главный ответ, альтернативы хранятся для справки; -- расширенный режим `multiple_accepted_moves`: если целью является конкретный ответ, допускается заранее настроить, какие ответы зачтутся; при показе альтернативы не следует одновременно засчитывать два разных `LearningItem`. - -Точная трактовка альтернативных собственных ходов исходной системой в открытых источниках не установлена. Это обязательно согласуемая часть реализации, но для MVP принят `one_answer_per_position`. - -## 4. Объём статистики и правило подсчёта множества ходов - -### 4.1. Базовое множество - -Для репертуара `R`, пользователя `U`, глубины `D` и фильтра `F` определим: - -```text -S(U,R,D,F) = множество уникальных активных (позиция, собственный ход), - достижимых от корневой позиции R, - с глубиной <= D, - удовлетворяющих фильтру F. -``` - -Тренировка за белых проверяет **только белые ходы**, за чёрных — **только чёрные**. Ходы соперника служат условиями ветвления и автоматически проигрываются. **[ПРОЕКТ]** Для процентов прогресса и требований тестирования в знаменатель входят именно проверяемые собственные ходы. В публичном интерфейсе ChessTempo употребляется термин *positions/moves*, но правила знаменателя для всех случаев (например, отключённые ходы) не полностью формализованы — при необходимости буквального совпадения требуется дополнительная экспериментальная проверка. - -Транспозиции в `S` **не дублируются**. При выборе нескольких репертуаров используем объединение множеств, а не сумму: `S_all = S_A ∪ S_B`. - -### 4.2. Фильтры и область охвата - -Каждый статистический ответ обязан содержать `scope`, например: - -```json -{ - "repertoire_ids": [12, 13], - "side": "WHITE", - "max_depth": null, - "only_active": true, - "branch_root": null, - "as_of": "2026-11-04T12:00:00Z" -} -``` - -Без `scope` невозможно понять, относится «70% изучено» ко всему репертуару или только к выбранной ветке. - -**[ПОДТВЕРЖДЕНО]** В ChessTempo ограничение `Maximum learning depth` влияет на **сводные цифры под доской**, но **не влияет на графики прогресса**, которые считают полную глубину. Для нового продукта рекомендуется отображать переключатель «текущий тренировочный охват / полный репертуар», чтобы это отличие не воспринималось как ошибка. Источник: [руководство § 17.4.2](https://www.chesstempo.com/manual/en/manual.html#trainingdepth). - -## 5. Точные формулы прогресса репертуара — [ПРОЕКТ] - -### 5.1. Счётчики - -Для набора `S` с числом элементов `T = |S|`: - -```text -Unseen = count(item in S: not item.introduced) -Learning = count(item in S: item.introduced and item.correct_streak < 3) -Learnt = count(item in S: item.introduced and item.correct_streak >= 3) -Uncertain = count(item in S: item.correct_streak >= 3 and is_uncertain(item,now)) -LearntConfident = Learnt - Uncertain -Due = count(item in S: item.introduced and item.next_review_at <= now) -NextDueAt = min(next_review_at) для введённых элементов с future next_review_at -``` - -**Инварианты:** - -```text -T = Unseen + Learning + Learnt -0 <= Uncertain <= Learnt -0 <= LearntConfident <= Learnt -0 <= Due <= Learning + Learnt -``` - -Не суммировать `Uncertain` второй раз: `T != Unseen + Learning + Learnt + Uncertain`. - -### 5.2. Проценты - -Для `T > 0`: - -```text -CoveragePercent = 100 * (T - Unseen) / T -LearntPercent = 100 * Learnt / T -ConfidentPercent = 100 * (Learnt - Uncertain) / T -LearningPercent = 100 * Learning / T -UnseenPercent = 100 * Unseen / T -UncertainOfLearntPct = 100 * Uncertain / Learnt (если Learnt > 0) -DueOfIntroducedPct = 100 * Due / (T - Unseen) (если введённые > 0) -``` - -Для `T = 0` не показывать `100%`: результат **«нет активных обучаемых ходов»**, процент = `null` (в UI отображается `—`). Это защищает от ложного заявления о полном изучении пустого репертуара. - -### 5.3. Как объявлять «репертуар изучен» - -В оригинале нет подтверждённого бинарного критерия для всего дебюта. Предлагаются **разные статусы**, чтобы не смешивать их: - -| Индикатор | Формальное условие | Значение | -|---|---|---| -| `NOT_STARTED` | `T>0, Unseen=T` | Ещё не начинали | -| `IN_PROGRESS` | `T>0, Learnt0, Learnt=T` | Все ходы хотя бы достигли формального порога | -| `CONFIRMED_CURRENT` | `T>0, Learnt=T, Uncertain=0, Due=0` | Всё достигло порога, критически просроченных и назначенных на сейчас проверок нет | -| `EMPTY` | `T=0` | Учить нечего | - -Переход `ALL_LEARNT → IN_PROGRESS` возможен после единственной ошибки; `CONFIRMED_CURRENT → ALL_LEARNT` возможен автоматически, когда наступает время следующей проверки. Поэтому это **не вечное достижение**, а состояние знаний **на момент `as_of`**. - -**Дополнительно:** разрешается сохранять награду/достижение «Впервые изучены все ходы» как исторический факт (`first_all_learnt_at`), не подменяя им текущую оценку. - -**Рекомендуемые подписи UI:** - -- `Изучено: 80 / 100 (80%)` -- `В процессе: 15` -- `Не начато: 5` -- `Из изученных требуют подтверждения: 12` -- `Проверить сейчас: 9` -- `Актуально подтверждено: 68 / 100 (68%)` - -### 5.4. Числовой пример - -Допустим, активный репертуар содержит `T=100` уникальных обучаемых собственных ходов: - -```text -Unseen = 10 -Learning = 20 -Learnt = 70 (из них Uncertain = 15) -Due = 25 (любая смесь Learning и Learnt) -``` - -Тогда: - -```text -CoveragePercent = (100-10)/100*100 = 90% -LearntPercent = 70/100*100 = 70% -ConfidentPercent = (70-15)/100*100 = 55% -UncertainOfLearntPct = 15/70*100 ≈ 21.43% -``` - -Вывод: **репертуар НЕ считается полностью изученным**, несмотря на 90% охвата. `Due=25` — это число заданий на сейчас, а не процент невыученного материала. - -### 5.5. Разница «Learnt» и «Uncertain» на данных руководства - -В [скриншоте таблицы Repertoire Summary из руководства](https://www.chesstempo.com/manual/en/manual.html#repertoiresummary) приведён пример: **Catalan: Learning 421; Learnt 687; Moves 1643; Uncertain 461**. - -Если трактовать `Uncertain` как **подмножество** `Learnt`, пример непротиворечив: - -```text -Unseen = 1643 - 421 - 687 = 535 -Learnt, не uncertain = 687 - 461 = 226 -``` - -В других строках скриншота `Learning + Learnt + Uncertain` даже превышает `Moves`, что дополнительно показывает недопустимость складывания всех четырёх столбцов как взаимоисключающих групп. При этом точные правила формирования исходного столбца Moves на уровне внутренних структур сайта по скриншоту неизвестны. - -### 5.6. Отдельные показатели для ветки и полного варианта - -Для выбранного узла/ветки повторно вычисляется `S` по **всем достижимым обучаемым ходам внутри ветки**, включая её подварианты. - -Для одной конкретной линии `L`: - -```text -LineLearnt = T_line > 0 AND all(item.correct_streak >= 3 for item in unique(line.items)) -LineFresh = LineLearnt AND no uncertain items AND no due items in line -``` - -Если позиция представлена в двух линиях, в статистике **каждой отдельной линии** она может присутствовать; при агрегировании всего репертуара она учитывается **один раз**. Весь репертуар нельзя оценивать как среднее арифметическое процентов линий, потому что линии разной длины и пересекаются. - -## 6. Статистика точности, ошибок и скорости — [ПРОЕКТ] - -### 6.1. Что известно про ChessTempo - -**[ПОДТВЕРЖДЕНО]** В деталях хода ChessTempo отображаются: *Accuracy*, последнее предъявление, правильные/ошибочные ответы подряд, дата следующего повторения и история неверных ходов с частотой и последним временем ошибочного ввода. В Sunburst и дереве можно окрашивать ходы по Accuracy, Correct sequence, Last seen, Next scheduled. Источники: [руководство § 17.11](https://www.chesstempo.com/manual/en/manual.html#movedetails), [§ 17.8](https://www.chesstempo.com/manual/en/manual.html#openingsunburstrepertoirevisualisation). - -**[НЕИЗВЕСТНО]** Точная опубликованная формула *Accuracy* в разделе **дебютного тренажёра** не обнаружена. Формула ниже — проектная, стандартная и воспроизводимая; не следует утверждать, что она идентична внутренней формуле ChessTempo. - -### 6.2. События и знаменатель точности - -Каждая попытка имеет тип: - -- `CORRECT_INDEPENDENT` — правильный ход без заранее раскрытого решения; -- `INCORRECT_INDEPENDENT` — самостоятельный неправильный ход; -- `PREVIEWED` — решение показано до ответа (стрелка/явная подсказка); -- `REPLAY_AFTER_ERROR` — пользователь повторил уже показанный ответ для продолжения; -- `AUTO_CONTEXT` — ход автоматически проигран системой; -- `ILLEGAL_MOVE` — нелегальный ход, не являющийся содержательной проверкой. - -**Для проверки знания учитываются только `CORRECT_INDEPENDENT` и `INCORRECT_INDEPENDENT`.** Остальные типы могут учитываться в аналитике использования, но не должны искусственно улучшать Accuracy и correct streak. - -В `PREVIEWED` система может назначить быстрое повторение для самостоятельного контроля; см. § 7. - -### 6.3. Формула точности - -Для учебного элемента `i`: - -```text -correct_i = count(CORRECT_INDEPENDENT) -wrong_i = count(INCORRECT_INDEPENDENT) -attempts_i = correct_i + wrong_i -accuracy_i = attempts_i == 0 ? null : 100 * correct_i / attempts_i -``` - -Пример: 7 самостоятельных верных ответов и 3 ошибки → `70%`. - -Для группы `S`: - -```text -GroupAccuracy = - 100 * SUM(correct_i) / SUM(correct_i + wrong_i), если SUM(attempts_i)>0 -``` - -**Не использовать простое среднее `accuracy_i`** для основного показателя: ход, проверенный 100 раз, и ход, проверенный 1 раз, иначе получили бы одинаковый вес. При необходимости дополнительно показывать `MeanPerItemAccuracy` как отдельную метрику с явным названием. - -**Особенность:** высокий Accuracy не доказывает `Learnt`: серия `2 подряд` остаётся Learning даже при 98% общей точности. И наоборот, три правильных ответа после многочисленных прошлых ошибок дают Learnt при низком историческом Accuracy. - -### 6.4. Ошибки - -Для каждого учебного элемента хранить: - -```text -correct_streak -wrong_streak -last_wrong_move_uci -last_wrong_at -wrong_move_histogram[played_move_uci] = {count, last_at} -``` - -При ошибке: - -- `correct_streak = 0`, `wrong_streak += 1`; -- сохранить фактически сделанный неправильный **легальный** ход; -- показать правильный репертуарный ход; -- установить новую дату повторения по правилам SRS; -- попытка пользователя исправить ход **не** превращает ошибку в успех. - -При самостоятельном успехе: `correct_streak += 1`, `wrong_streak = 0`. - -**[ПОДТВЕРЖДЕНО]** ChessTempo сохраняет историю неверных ходов с частотой и последним временем. В руководстве встречается историческое замечание о неполном учёте ошибок в мобильных клиентах; это не должно влиять на проектируемую систему: все платформы отправляют события в единое хранилище. - -### 6.5. Время ответа - -Хранить `response_time_ms` от момента готовности доски к самостоятельному ответу до первого завершённого легального хода. Отдельно учитывать время анимации контекста и пользовательских пауз — **их не включать** в время размышления. Медиану/перцентили скорости показывать дополнительно, но не использовать для Learnt в базовом алгоритме. - -## 7. Расписание интервального повторения (SRS) - -### 7.1. Подтверждённые правила и значения по умолчанию - -| Настройка | Default ChessTempo | Источник | -|---|---:|---| -| `growth_factor` | `2.0` | Руководство § 17.15.2 | -| `first_correct_delay` | `1440 минут` (1 день) | Там же | -| `mistake_delay` | `0.5 минуты` (30 секунд) | Там же | -| `preview_delay` | `1 минута` | Там же | -| `max_interval` | `1095 дней` (3 года) | Там же | -| `sort_due_items_by` | `Variation` | Там же | -| `undue_variation_window` | `0 часов` | Там же | - -Ссылка: [официальные настройки SRS](https://www.chesstempo.com/manual/en/manual.html#spacedrepetitionsettings). - -**[ПОДТВЕРЖДЕНО]** В руководстве приведён пример: если ход был правильно воспроизведён **4 дня назад**, а сегодня снова решён правильно, при коэффициенте `2.0` следующее повторение будет через **8 дней**. Это значит, что правильнее ориентироваться на **фактически прошедший срок**, а не безоговорочно удваивать старый плановый интервал. - -### 7.2. Проектная реализация планировщика - -Данные: - -```text -introduced boolean -correct_streak integer -last_correct_at timestamp|null -last_review_at timestamp|null -next_review_at timestamp|null -previous_interval_seconds integer|null -``` - -```pseudo -on_independent_correct(item, now): - item.introduced = true - if item.correct_streak == 0 or item.last_correct_at is null: - delay = settings.first_correct_delay - else: - elapsed = now - item.last_correct_at - delay = min(max(elapsed * settings.growth_factor, - settings.min_practical_interval), - settings.max_interval) - item.correct_streak += 1 - item.wrong_streak = 0 - item.last_correct_at = now - item.last_review_at = now - item.previous_interval_seconds = delay - item.next_review_at = now + delay - -on_independent_wrong(item, played_move, now): - item.introduced = true - item.correct_streak = 0 - item.wrong_streak += 1 - item.last_correct_at = null # проектное решение: сброс базы роста - item.last_review_at = now - item.next_review_at = now + settings.mistake_delay - save_wrong_move(item, played_move) - -on_preview(item, now): - item.introduced = true - # Без зачёта успеха и без увеличения серии - item.last_review_at = now - item.next_review_at = now + settings.preview_delay -``` - -`min_practical_interval` — внутренний защитный параметр, **не значение ChessTempo**. Должна быть чёткая политика для ответа, сделанного преждевременно: можно использовать фактическое время, но не допускать интервал менее заданного нижнего предела. - -**[НЕИЗВЕСТНО]** Некоторые граничные детали SRS — например, точная база роста после ошибки, досрочного ответа или показа подсказки — по открытой документации не установлены. Для них предписан приведённый выше воспроизводимый алгоритм, покрытый тестами, а не домысел о реализации ChessTempo. - -### 7.3. Due и очередь тренировок - -```text -Due(item, now) = item.introduced AND item.next_review_at <= now -``` - -`Due=0` означает, что на данный момент не осталось введённых ходов, срок которых наступил. **Unseen сюда не входят.** - -**[РАЗРАБОТЧИК]** При `Due=0` обычно разумно остановиться: если продолжить, тренажёр может ввести новые ходы из Unseen, а когда Unseen уже нет — начать проверять ранее запланированные ходы досрочно. Источники: [разбор «Trying to understand…»](https://chesstempo.com/forum/topic/trying-to-understand-how-opening-training-works-with-the-scheduling-option/10924/), [«Opening Training Best Practice»](https://chesstempo.com/forum/topic/opening-training-best-practice/12249/). - -Сортировки: - -- `Variation`: группировать готовые к проверке элементы по веткам. По руководству ошибки текущей сессии обычно попадают на повторную проверку **после первичной очереди**, а не сразу же спустя 30 секунд. -- `Due date`: сначала максимально просроченные; подходит при накопившемся долге. - -Внутренняя очередь на старте сессии должна фиксировать список доступных элементов, но динамически добавлять пропущенные/ошибочные при следующем проходе. Одна и та же проверка не должна считаться дважды. - -### 7.4. Как вводить новые ходы - -Пока есть `Due`, основной режим предлагает их. Если `Due=0` и есть `Unseen`, пользователь может **явно выбрать** продолжение обучения. Новые элементы выбираются по настройке `Learning priority`: - -1. `Depth first` — главная линия полностью, затем боковые. -2. `Breadth over depth` — ранние позиции всех веток, затем более глубокие. -3. `Main lines first` — главные линии раньше подвариантов. -4. `Common positions first` — популярные позиции раньше редких; при отсутствии данных используется fallback на движковые оценки, затем обход в ширину. - -**[ПОДТВЕРЖДЕНО]** Приоритет новых ходов применяется **при переходе Unseen → введён в SRS**, а не переписывает даты повторения уже изучаемых. Ссылка: [руководство § 17.4.3](https://www.chesstempo.com/manual/en/manual.html#availabletrainingmodes). - -## 8. Режимы тренировки - -### 8.1. Spaced Repetition — стандартный - -Выбор по `next_review_at`; периодическое добавление новых ходов; фиксация ошибок и успешных ответов; обновление расписания. Нужна возможность закончить работу при `Due=0`. - -### 8.2. Review in Order - -Проход всего активного репертуара или ветки по `Learning priority` **по одному разу за цикл**. Система хранит позицию цикла и автоматически воспроизводит уже проверенные ранее контекстные ходы. По окончании цикл начинается заново. Есть отдельный `Reset Review Order`, **не сбрасывающий** статистику SRS. - -**[ПОДТВЕРЖДЕНО]** Ответы в этом режиме всё равно меняют SRS-расписание. Новые ходы при первом предъявлении выходят из Unseen. Источник: [§ 17.4.3, Review in order](https://www.chesstempo.com/manual/en/manual.html#reviewinorder). - -### 8.3. Least Recent / Unseen First - -Сначала Unseen, затем ходы с самой давней последней попыткой. Все реальные самостоятельные ответы также обновляют SRS. Контекстные ходы, проверенные досрочно, помечаются как уже пройденные в текущем цикле, чтобы не повторять их без нужды. - -## 9. Контекст: не заставлять каждый раз играть от первого хода - -**[ПОДТВЕРЖДЕНО]** При выборе целевой позиции ChessTempo может автоматически показать ведущую к ней линию, ускорить хорошо знакомые части, пропустить чрезвычайно хорошо известное начало и включить проверку нескольких контекстных ходов, если они сами нуждаются в закреплении. - -Алгоритм: - -```pseudo -train(target_item): - line = choose_repertoire_path(root, target_item.position) - for each earlier move in line: - if move made by opponent: autoplay - else if should_test_as_context(move): ask_user_and_grade - else if can_skip_known_prefix(move): omit prefix presentation - else: autoplay at knowledge_adaptive_speed - ask_user_and_grade(target_item) -``` - -Настройки: - -- `Reinforce minimum correct` — дополнительно спрашивать контекстные ходы с серией короче порога; -- `Reinforce minimum days` — спрашивать контекстный ход, если его ближайшая проверка достаточно скоро; -- `Don't show start moves threshold` — пропускать хорошо выученный **начальный префикс**; -- `Move speed adjustment` — коэффициент скорости анимации; -- `Use fixed piece movement speed` — фиксированная скорость вместо адаптивной; -- `Consider leadup moves when training branch` — проверять контекст выше точки начала ветки (по умолчанию в ChessTempo выключено). - -Источники: [руководство § 17.4.3 Context](https://www.chesstempo.com/manual/en/manual.html#contextfortrainingmoves), [§ 17.15.3](https://www.chesstempo.com/manual/en/manual.html#advancedsettings), [FAQ](https://www.chesstempo.com/faq/). - -**Правило статистики:** автоматическое проигрывание не изменяет `correct_streak`, `accuracy`, `last_correct_at` и не образует самостоятельную попытку; если контекстный ход реально проверен пользователем, результат учитывается как обычная проверка один раз. - -## 10. Проверка ответа и подсказки - -### 10.1. Неверный ход - -После первого легального неверного хода: - -1. Зафиксировать ошибку ровно один раз. -2. Показать ожидаемый ход. -3. Позволить сыграть ожидаемый ход для продолжения линии. -4. Повторное проигрывание этого показанного хода не засчитывать как правильный ответ. -5. Поместить элемент в очередь на скорое повторение по SRS. - -Нелегальное перемещение не считается ответом; интерфейс просто возвращает фигуру на место. - -### 10.2. Предварительный показ ответа - -**[ПОДТВЕРЖДЕНО]** ChessTempo может подсвечивать ход стрелкой для новых позиций, ранее ошибочно решённых ходов или вообще всех ходов — в зависимости от настроек. Если решение предварительно показано, повторение назначается быстрее, по умолчанию через одну минуту. Источники: [§ 17.4.1](https://www.chesstempo.com/manual/en/manual.html#movehints), [§ 17.15.2](https://www.chesstempo.com/manual/en/manual.html#spacedrepetitionsettings). - -**[ПРОЕКТ]** В проекте при любой подсказке, которая раскрыла ожидаемый ход ДО самостоятельного ответа, событие помечается `PREVIEWED`; оно не увеличивает `correct_streak` и не ухудшает accuracy как неправильное. Движок должен позже проверить знание без подсказки. - -### 10.3. Пауза/завершение линии - -Кнопки `Pause`, `Continue`, `Stop`. Опциональная остановка в конце линии. Отображение комментариев и анализа вне фазы `AWAITING_MOVE`, чтобы случайно не выдавать ответ заранее. - -## 11. Панель статистики отдельного хода - -При выборе хода в дереве (и в паузе тренировки) показывать: - -| Поле | Формула / источник | -|---|---| -| Статус | Из § 2.3 | -| Точность | `correct / (correct + wrong) * 100` | -| Правильно / ошибки | Счётчики самостоятельных попыток | -| Всего самостоятельных проверок | `correct + wrong` | -| Правильных подряд | `correct_streak` | -| Ошибок подряд | `wrong_streak` | -| Последний показ | `last_review_at` | -| Последняя самостоятельная проверка | `max(timestamp независимых попыток)` | -| Следующий повтор | `next_review_at` или `—`, если Unseen | -| Время до повтора | `next_review_at - now`, если будущее | -| Просрочка | `max(0, now - next_review_at)` | -| Причина статуса Uncertain | При наличии — просрочка и порог | -| Ошибочные ответы | UCI/SAN, число ошибок, последний раз | -| Медиана времени ответа | По самостоятельным проверкам | -| Где встречается | Репертуары и ветки, содержащие тот же учебный элемент | - -Если `attempts=0`, точность выводится как `—`, а не `0%` или `100%`. У каждой метрики должна быть информационная подсказка с определением. - -## 12. Сводная статистика репертуара - -### 12.1. Главная строка (как в ChessTempo) - -**[ПОДТВЕРЖДЕНО]** ChessTempo имеет таблицу `Repertoire Summary` со столбцами **Name, Learning, Learnt, Moves, Uncertain, Due**. Если есть назначенные повторения, в `Due` видно их число; если всё актуально — время до следующей проверки. Источник: [руководство § 10.5](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). - -Для своего продукта рекомендуемые колонки: - -| Название | Ходов (`T`) | Не начато | Изучается | Изучено | Uncertain | Due | Изучено % | Актуально % | -|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| -| Сицилианская защита | 100 | 10 | 20 | 70 | 15 | 25 | 70% | 55% | - -Под таблицей добавить `Next due at` и кнопку «Продолжить изучение» (когда Due=0, но Unseen>0). - -### 12.2. Блок «Что мне делать сегодня» - -Приоритет отображения: - -1. `Due > 0`: «Повторить N ходов». -2. `Due = 0` и `Unseen > 0`: «На сегодня повторений нет; можно изучить новые ходы». -3. `Due = 0`, `Unseen = 0`, `Learning > 0`: «Плановые повторы выполнены; часть материала ещё на этапе закрепления». -4. `Due = 0`, `Unseen = 0`, `Learning = 0`: «Все ходы изучены; следующее повторение …». - -**Не писать «дебют полностью освоен», если `Due=0`, но есть Unseen или Learning.** - -### 12.3. Несколько репертуаров и глобальная статистика - -Общий счётчик строить по `UNION DISTINCT LearningItemKey` внутри выбранных репертуаров: - -```text -GlobalTotal != SUM(RepertoireTotal) при общих позициях -``` - -При этом таблица каждого репертуара использует собственное множество, поэтому **сумма чисел строк таблицы может не равняться глобальному уникальному итогу**. На экране пометить эту особенность. - -### 12.4. Сравнение веток - -По каждой ветке показывать T, Unseen, Learning, Learnt, Uncertain, Due, Accuracy, прогресс %, дату последней тренировки. Дочерние ветки могут содержать общие транспозиции; при свёртке верхнего уровня требуется объединять по уникальным ключам, а не складывать дочерние суммы. - -## 13. Графики и их алгоритмы - -### 13.1. History — динамика изучения - -**[ПОДТВЕРЖДЕНО]** ChessTempo показывает изменение числа Learning, Learnt и Uncertain по времени; Uncertain может появляться просто из-за просрочки, без новой ошибки. Источник: [руководство § 17.25.1](https://www.chesstempo.com/manual/en/manual.html#globalstats). - -**[ПРОЕКТ]** Ежедневно (в указанном часовом поясе пользователя) вычислять срез статусов всех активных учебных элементов: - -```text -(date, scope, total, unseen, learning, learnt, uncertain, due) -``` - -Для каждого исторического дня нужно использовать **состав репертуара на этот день**, либо явно подписывать график как **ретроспективный пересчёт текущего состава**. Эти подходы дают разные линии после добавления/удаления ходов; нельзя незаметно смешивать их. - -Рекомендуемый режим по умолчанию: исторический снимок фактического состава на конец дня. Не реконструировать прошлый `Uncertain` только из текущего статуса — он зависел от того времени и тогдашних настроек. - -График 1: `Learning`, `Learnt` и `Uncertain` (можно показывать Uncertain как подмножество Learnt). График 2 (проект): `% изучено`, `% актуально`, `Unseen`. - -### 13.2. Scheduled — распределение предстоящих повторений - -**[ПОДТВЕРЖДЕНО]** ChessTempo отображает количество уже просроченных, ожидающих повторения сегодня, на следующей неделе, месяце, году и дальше года. Источник: [руководство § 17.25.2](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). - -**[ПРОЕКТ]** Предписать **непересекающиеся временные корзины** для введённых элементов, исключая Unseen: - -```text -OVERDUE: next_review_at <= now -TODAY: now < next_review_at < end_of_current_local_day -WEEK: end_today <= next_review_at < now + 7d -MONTH: now+7d <= next_review_at < now + 30d -YEAR: now+30d <= next_review_at < now + 365d -LATER: next_review_at >= now + 365d -``` - -Точная граница календарных «неделя/месяц/год» должна быть определена в единой функции с явным часовым поясом. Более однозначный вариант для API — корзины по фиксированным `7/30/365` суткам, а для UI — локальный календарь. В одной модели смешивать нельзя. - -**Проверка:** сумма корзин = `T - Unseen` (у каждого введённого элемента есть `next_review_at`). График можно строить по любому репертуару и ветке. - -### 13.3. Sequences — длины серий - -**[ПОДТВЕРЖДЕНО]** ChessTempo имеет две гистограммы длины последовательных правильных и неправильных ответов (1, 2, 3, …) и третью — сколько ходов было сыграно 1, 2, 3… раз. Источник: [§ 17.25.2](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). - -**[ПРОЕКТ]** - -```text -CorrectStreakHistogram[k] = count(item in S: item.correct_streak = k) -WrongStreakHistogram[k] = count(item in S: item.wrong_streak = k) -AttemptsHistogram[k] = count(item in S: item.correct_i + item.wrong_i = k) -``` - -Добавить категорию `0` в расчётах, но при отображении можно скрывать её или выводить отдельной колонкой «Без проверок». Если число серий больше 20, последний столбец может быть `20+`; сумма по отображаемым столбцам должна сохраняться. - -### 13.4. Дополнительные графики — [ПРОЕКТ] - -- Accuracy по дням — самостоятельные попытки в выбранный день, без подсказок. -- Частота ошибок по веткам — `wrong / (correct + wrong)`, при наличии попыток. -- Самые проблемные позиции — ранжирование по ошибкам и устойчивости ошибки. -- Учебная нагрузка — количество проверок по дням и ожидаемые Due на будущее. -- Время решения — медиана по веткам. - -Не смешивать статистику изучения дебютов с engine accuracy, win rate в партиях или качеством позиционной оценки: это **разные метрики**. - -## 14. Resistant — устойчиво проблемные ходы - -**[ПОДТВЕРЖДЕНО]** ChessTempo выделяет повторяющиеся проблемные ходы как `Resistant`, имеет виртуальные общие репертуары таких ходов отдельно за белых и чёрных, а для выхода из Resistant требует более одного правильного ответа подряд. **[НЕИЗВЕСТНО]** Конкретная формула вступления/выхода в категорию публично не раскрыта. Источник: [руководство § 17.4.5](https://www.chesstempo.com/manual/en/manual.html#resistantrepertoires). - -**[ПРОЕКТ]** Формула, пригодная для первой реализации: - -```text -becomes_resistant = attempts_in_last_10 >= 5 AND wrong_in_last_10 >= 3 -exits_resistant = 3 independent correct answers in a row since last error -``` - -Это **отдельный флаг**, а не пятый взаимоисключающий статус. `Resistant = true` совместим с `Learning`; после восстановленной серии теоретически может кратковременно совмещаться с Learnt, если настройки выхода отличаются. Статистика Resistant выводится отдельной строкой и **не прибавляется** к Total. - -## 15. Сброс и изменение структуры репертуара - -### 15.1. Reset training - -**[ПОДТВЕРЖДЕНО]** ChessTempo сбрасывает статистику и расписание SRS до Unseen. Поскольку общие позиции разделяются между репертуарами, сброс одного репертуара может затронуть статистику того же элемента в другом. Источник: [руководство § 17.24.3](https://www.chesstempo.com/manual/en/manual.html#resettraining). - -**[ПРОЕКТ]** Перед сбросом показывать предупреждение: «Из N сбрасываемых учебных элементов M используются также другими репертуарами». Варианты безопасной операции: - -- `Reset shared learning data` — очистить общую историю и для пересекающихся репертуаров (аналог семантики ChessTempo). -- `Reset selected view only` — **не поддерживать**, если нет независимой статистики по конкретному репертуару: нельзя обещать изолированный сброс одного и того же учебного элемента при глобальном ключе. - -`Reset Review Order` меняет только прогресс порядка обхода, оставляя SRS без изменений. - -### 15.2. Добавление/удаление/отключение ходов - -- Добавленный активный обучаемый ход увеличивает `T` и `Unseen`; прогресс % может уменьшиться **без ухудшения памяти**. -- Отключённый ход исчезает из активного набора `S`, но его история сохраняется для обратного включения. -- Удаление ветки не должно стирать общую позицию, если на неё есть ссылки из других веток/репертуаров. -- Переименование/изменение комментария не меняет историю обучения. -- При изменении корневой позиции необходимо пересчитать достижимость и предупреждать о масштабных изменениях T. - -### 15.3. Импорт/экспорт PGN - -Поддержать вложенные вариации, комментарии, NAG и транспозиции, объединение с существующим репертуаром, включение/отключение ходов. Экспортировать репертуары отдельно по именам и цветам. **Не рассчитывать**, что обычный PGN содержит историю SRS: для неё нужен отдельный резервный формат (например, JSON backup с версиями схемы). - -## 16. Пользовательские сценарии - -### Сценарий A. Создание и первый урок - -Пользователь импортирует PGN за белых, видит `T=120`, `Unseen=120`, `Learnt=0`, `Due=0`. Нажимает «Изучить новые ходы». Система показывает нужный контекст, обучает выбранный ответ, ставит ближайшую проверку. `CoveragePercent` растёт, а `LearntPercent` ещё равен нулю. - -### Сценарий B. После трёх правильных ответов - -Один и тот же учебный ход правильно воспроизведён три раза подряд **самостоятельно**, с соблюдением интервалов SRS. Его `correct_streak = 3`, статус `Learnt`. Сводный счётчик Learnt увеличивается на 1, Learning уменьшается на 1. Следующая проверка **всё равно запланирована**. - -### Сценарий C. Ошибка после изучения - -Ход был Learnt (`correct_streak=5`). Пользователь ошибся: `correct_streak=0`, статус `Learning`, правильный ход показан, назначено скорое повторение. Подсказанное исправление не возвращает Learnt. - -### Сценарий D. Статистика становится Uncertain без новой ошибки - -Ход был Learnt, но с даты `next_review_at` прошло больше установленного grace-периода. Без действия пользователя он попадает в `Uncertain`. `Learnt` как число исторически достигших порога **не увеличивается**, но «актуально подтверждено» уменьшается. Правильный самостоятельный ответ снимает Uncertain. - -### Сценарий E. Общая позиция двух дебютов - -Один учебный ход присутствует в двух репертуарах. Пользователь правильно ответил в первом — во втором одновременно отображаются новая серия и новое время проверки. В глобальном `T` этот ход учитывается только один раз. - -### Сценарий F. За сегодня всё повторено - -`Due=0`, `Learning=20`, `Unseen=10`. UI не пишет «репертуар выучен», а сообщает, что текущие плановые проверки закончились, и предлагает либо завершить занятие, либо вручную добавить новый материал. - -### Сценарий G. Глубина тренировки - -В репертуаре 100 ходов, но до установленной глубины доступно только 40. Сводка тренировочной области показывает 40, полная статистика — 100, обе подписаны своими охватами. Ни один ход не теряется. - -## 17. Структура данных для разработчика - -Пример рекомендуемой реляционной схемы (имена иллюстративные): - -```sql -CREATE TABLE learning_item ( - id BIGSERIAL PRIMARY KEY, - user_id BIGINT NOT NULL, - position_key TEXT NOT NULL, - expected_move_uci VARCHAR(8) NOT NULL, - introduced BOOLEAN NOT NULL DEFAULT FALSE, - correct_count INT NOT NULL DEFAULT 0, - wrong_count INT NOT NULL DEFAULT 0, - correct_streak INT NOT NULL DEFAULT 0, - wrong_streak INT NOT NULL DEFAULT 0, - last_review_at TIMESTAMPTZ, - last_correct_at TIMESTAMPTZ, - next_review_at TIMESTAMPTZ, - previous_interval_seconds BIGINT, - resistant BOOLEAN NOT NULL DEFAULT FALSE, - updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), - UNIQUE (user_id, position_key, expected_move_uci) -); - -CREATE TABLE training_attempt ( - id UUID PRIMARY KEY, - user_id BIGINT NOT NULL, - learning_item_id BIGINT NOT NULL REFERENCES learning_item(id), - session_id UUID NOT NULL, - event_type VARCHAR(32) NOT NULL, - expected_move_uci VARCHAR(8) NOT NULL, - played_move_uci VARCHAR(8), - response_time_ms BIGINT, - happened_at TIMESTAMPTZ NOT NULL, - settings_version TEXT NOT NULL, - UNIQUE (session_id, id) -); - -CREATE INDEX idx_learning_due ON learning_item (user_id, next_review_at) - WHERE introduced = TRUE; -CREATE INDEX idx_attempt_item_time ON training_attempt (learning_item_id, happened_at); -``` - -Отдельные таблицы нужны для `Repertoire`, `Position`, `MoveEdge`, `RepertoireEdge`, членства репертуара, сессий и ежедневных снимков. В `TrainingAttempt` желательно добавить ID идемпотентности **от клиента**, чтобы повторный сетевой запрос не создавал вторую попытку: `UNIQUE(user_id, client_attempt_id)`. - -Сложные агрегаты считать как `COUNT(DISTINCT learning_item.id)` по выбранному `scope`. **Не группировать по SQL-строке полного FEN**, если ключ позиции нормализован другим алгоритмом. - -## 18. API: контракт статистики — [ПРОЕКТ] - -### 18.1. Обязательные конечные точки - -```text -GET /api/repertoires/{id}/stats?scope=full|training&depth=... -GET /api/repertoires/{id}/stats/history?from=...&to=... -GET /api/repertoires/{id}/stats/scheduled -GET /api/repertoires/{id}/stats/sequences -GET /api/repertoires/{id}/stats/branches -GET /api/learning-items/{id}/stats -POST /api/training-sessions -POST /api/training-sessions/{id}/attempts -POST /api/repertoires/{id}/reset-training -POST /api/repertoires/{id}/reset-review-order -``` - -### 18.2. Пример сводного ответа - -```json -{ - "repertoire_id": 12, - "as_of": "2026-11-04T12:00:00Z", - "scope": {"max_depth": null, "only_active": true, "distinct_transpositions": true}, - "total": 100, - "unseen": 10, - "learning": 20, - "learnt": 70, - "uncertain": 15, - "learnt_confident": 55, - "due": 25, - "next_due_at": null, - "coverage_percent": 90.0, - "learnt_percent": 70.0, - "confident_percent": 55.0, - "repertoire_status": "IN_PROGRESS", - "accuracy_percent": 74.6, - "accuracy_attempts": 280, - "resistant": 7 -} -``` - -`next_due_at` здесь `null`, поскольку уже есть Due; при Due=0 должна быть минимальная будущая дата (или null, если ни одного введённого элемента нет). - -API должен возвращать **все** числа, из которых рассчитаны проценты. Frontend не должен самостоятельно суммировать пересекающиеся категории и менять знаменатель. - -## 19. Обновление статистики и техническая консистентность - -- Все события записываются сервером. Клиент не устанавливает сам `Learnt` или `Due`. -- Время `happened_at` и расчёт интервала — серверное UTC; календарные графики конвертируются в часовой пояс пользователя. -- Обновление серии, агрегатов, следующего срока и запись попытки атомарны. -- Повторная доставка одного `client_attempt_id` возвращает прежний результат, не изменяя счётчики. -- Исторические снимки в конце дня строятся в одном и том же часовом поясе; при изменении зоны отображение должно иметь явную политику. -- Исторические изменения после удаления/отключения хода не должны переписывать прежние снимки без отдельной команды пересчёта. -- Расписание не должно ломаться при одновременных сессиях одного пользователя. Для учебного элемента требуется блокировка строки/optimistic version. -- При массовом пересчёте нужно поддерживать `as_of`, чтобы все счётчики одного ответа строились на одном моменте времени. -- Проектировать агрегаты так, чтобы `T = Unseen + Learning + Learnt` всегда проходил проверку. - -## 20. Проверки/критерии приёмки (обязательные) - -| ID | Проверка | Ожидается | -|---|---|---| -| AT-01 | 100 новых ходов | `T=100, Unseen=100, Learning=0, Learnt=0, Due=0` | -| AT-02 | Первый самостоятельный правильный ответ | `correct_streak=1`, Learning, next due +1 день | -| AT-03 | Третий ответ подряд без подсказок | `correct_streak=3`, Learnt | -| AT-04 | Ошибка после Learnt | `correct_streak=0`, Learning, ближайший повтор через 30 секунд | -| AT-05 | Повтор показанного правильного хода после ошибки | Нет дополнительного самостоятельного успеха | -| AT-06 | Превью перед ответом | Результат `PREVIEWED`, next due +1 минута, streak не растёт | -| AT-07 | Нет Due, но есть Unseen | UI не выводит «всё изучено», предлагает новые ходы | -| AT-08 | Learnt и Due одновременно | Должен входить и в Learnt, и в Due | -| AT-09 | Learnt просрочен за grace-период | Входит в Uncertain, но не суммируется к T | -| AT-10 | Uncertain правильно повторён | Снимается Uncertain, остаётся Learnt | -| AT-11 | Uncertain решён ошибочно | Learning, следующий повтор по ошибке | -| AT-12 | 7 успехов + 3 ошибки | Accuracy = 70%, отдельно от статуса изученности | -| AT-13 | Нет попыток | Accuracy = null, UI: `—` | -| AT-14 | Общий ход двух репертуаров | Одна запись LearningItem, статистика общая | -| AT-15 | Глобальная агрегация двух пересекающихся репертуаров | Общий T считается через объединение, без дублирования | -| AT-16 | У репертуара 0 активных ходов | Status EMPTY, проценты не равны 100% | -| AT-17 | Максимальная глубина = 10 полуходов | Сводка меняет охват; полный график остаётся полным по соответствующей настройке | -| AT-18 | Отключить ветку | Она исчезает из активной статистики, история не удаляется | -| AT-19 | Включить ветку обратно | История и предыдущий correct_streak восстановлены | -| AT-20 | Review in Order | Каждый целевой элемент один раз за цикл, SRS также обновляется | -| AT-21 | Wrong в Variation mode | Не вытесняет исходную очередь сразу; повтор возможен в следующем проходе | -| AT-22 | Сброс одного репертуара с общими позициями | Явное предупреждение и корректное последствие для второго | -| AT-23 | Два одинаковых сетевых ответа | Один учтённый TrainingAttempt | -| AT-24 | Два разных порядка ходов, одна позиция | Одна учебная запись, одинаковый прогресс | -| AT-25 | Изменение состава репертуара на +20 ходов | T и проценты пересчитываются, старые успехи остаются | -| AT-26 | Сумма корзин Scheduled | Ровно равна количеству введённых элементов | -| AT-27 | Снимки истории без новых попыток | Uncertain может увеличиться с течением времени | -| AT-28 | Сводка 100/100 Learnt, Due=3 | Статус ALL_LEARNT, не CONFIRMED_CURRENT | -| AT-29 | Сводка 100/100 Learnt, Due=0, Uncertain=0 | CONFIRMED_CURRENT | -| AT-30 | Статистика линии и репертуара | Линия может учитывать пересечения; общий итог дедуплицируется | - -### Особые математические инварианты - -```text -T == Unseen + Learning + Learnt -Uncertain <= Learnt -LearntConfident == Learnt - Uncertain -CoveragePercent >= LearntPercent >= ConfidentPercent -0 <= each percentage <= 100 -Due <= (Learning + Learnt) -GlobalTotal <= sum(T per repertoire) -AccuracyPercent is null OR 0 <= AccuracyPercent <= 100 -``` - -Любое нарушение должно регистрироваться в логах/метриках, а тесты обязаны падать. - -## 21. Интерфейс: минимальный набор экранов - -### 21.1. Редактор репертуара - -Шахматная доска, дерево ходов, имя/цвет, главное и побочные продолжения, комментарии, импорт/экспорт, переключатель активности ветки. Выбранная позиция показывает её учебные показатели и ссылку на все репертуары, где она встречается. - -### 21.2. Экран тренировки - -Доска, название репертуара/ветки, прогресс текущей сессии, «Повторить сейчас: N», сообщения об ошибке/подсказке, кнопка паузы. В обычном режиме нельзя заранее показывать решение. Если при новом ходе включена автоподсказка, UI и API должны отметить попытку как `PREVIEWED`. - -### 21.3. Дашборд репертуара - -Верх: главные KPI — `T`, `Unseen`, `Learning`, `Learnt`, `Uncertain`, `Due`, `% изучено`, `% актуально`, `NextDueAt`. - -Ниже: график истории, распределение расписания, серии ответов, распределение числа попыток и список проблемных ходов. Все числа зависят от явно выбранного `scope`. - -### 21.4. Общий дашборд - -Сравнение репертуаров за белых/чёрных; глобальный прогресс **без повторного подсчёта пересекающихся элементов**; учебная нагрузка и список того, что требует действий сегодня. Разница между суммой по строкам и глобальным итогом объясняется всплывающей подсказкой. - -## 22. Этапы разработки - -**MVP:** граф позиций и PGN, редактор, `LearningItem`, `TrainingAttempt`, правильный/неправильный ответ, 3 подряд, SRS, Due, транспозиции, базовая таблица показателей и математические инварианты. - -**V1:** три режима тренировки, четыре приоритета нового материала, контекст и reinforcement, истории/графики, ветки, снимки, предупреждение при сбросе, подробные ошибки, динамические Uncertain и Resistant. - -**V2:** синхронизация дебютной базы, движковые оценки, Sunburst, анализ сыгранных партий, расширенная аналитика качества репертуара, режим соревнований. - -## 23. Открытые вопросы, которые нельзя выдавать за факты ChessTempo - -1. **Порог Uncertain:** подтверждено только, что ход достаточно сильно просрочен. Точная продолжительность не найдена. В этом ТЗ предложена формула с конфигурируемым grace-периодом. -2. **Формула Resistant:** не раскрыта; предложено правило «≥3 ошибок среди последних ≥5 проверок из окна 10» и выход после трёх правильных подряд. -3. **Формула дебютного Accuracy:** сам показатель отображается, но точная серверная формула для дебютного тренажёра не опубликована. Предложено `correct/(correct+wrong)` только по самостоятельным проверкам. -4. **Сложные случаи SRS:** известны дефолты, коэффициент роста и пример с фактически прошедшими четырьмя днями, но не все граничные случаи. Псевдокод выше — воспроизводимый проектный вариант. -5. **Альтернативные собственные ходы:** нужен продуктовый выбор строгого или свободного режима. В MVP выбран один обязательный ответ на позицию. -6. **Знаменатель Moves в абсолютном соответствии ChessTempo:** точная внутренняя трактовка каждой категории сложного графа не раскрыта. В ТЗ принят однозначный набор уникальных активных собственных учебных элементов. -7. **«Весь дебют изучен»:** бинарного подтверждённого глобального критерия ChessTempo нет. Для продукта введены явные формулы `ALL_LEARNT` и `CONFIRMED_CURRENT`. -8. **Экспорт статистики:** PGN не должен рассматриваться как резервная копия SRS, если история отдельно не сериализуется. - -## 24. Источники для проверки реализации - -Официальные: - -1. [ChessTempo — Opening Training](https://www.chesstempo.com/opening-training/). -2. [ChessTempo User Guide, § 17 Opening Training](https://www.chesstempo.com/manual/en/manual.html#openingtraining). -3. [ChessTempo User Guide, § 17.4 Training Mode](https://www.chesstempo.com/manual/en/manual.html#trainingmode). -4. [ChessTempo User Guide, § 17.15 Settings](https://www.chesstempo.com/manual/en/manual.html#openingtrainingsettings). -5. [ChessTempo User Guide, § 17.25 Graphs and Statistics](https://www.chesstempo.com/manual/en/manual.html#graphsandstatistics). -6. [ChessTempo User Guide, § 10.5 Repertoire Stats](https://www.chesstempo.com/manual/en/manual.html#repertoirestats). -7. [ChessTempo FAQ](https://www.chesstempo.com/faq/). - -Ответы разработчика: - -8. [«Opening training no more positions to schedule yet?» — прямое определение 3 правильных подряд, Unseen/Learning/Learnt/Uncertain](https://chesstempo.com/forum/topic/opening-training-no-more-positions-to-schedule-yet/9962/). -9. [«Trying to understand how opening training works with the scheduling option?» — Due, Learnt N/T, разбор статистики](https://chesstempo.com/forum/topic/trying-to-understand-how-opening-training-works-with-the-scheduling-option/10924/). -10. [«Opening Training Best Practice» — почему логично останавливаться при Due=0](https://chesstempo.com/forum/topic/opening-training-best-practice/12249/). -11. [«Moves stuck in learning» — статус зависит от серии правильных ходов](https://chesstempo.com/forum/topic/moves-stuck-in-learning/11361/). - -**Рекомендация по реализации:** разработчик должен начать не с графиков, а с однозначной модели `LearningItem` и детерминированных unit-тестов из § 20. Тогда интерфейс и проценты будут лишь разными проекциями одних и тех же непротиворечивых данных. diff --git a/docs/decisions.md b/docs/decisions.md index 4ca09b8..521a372 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -71,7 +71,6 @@ - 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 @@ -174,402 +173,7 @@ - **!!** — корректная жертва фигуры не дешевле лёгкой (по расчёту размена соперник выигрывает ≥ 2 очков сверх взятого), ход лучший или почти лучший, после него не хуже ≈ −0,5, без него партия не была выиграна и так (лучший другой ход < 90 %). Конь за две пешки — не !!. - **!** — ход движка №1, все остальные хуже не меньше чем на 10 % шанса (наша «ошибка»), после него не хуже ≈ −0,2 и без него не было уже выиграно. Взятие обратно, выгодное взятие и мат не отмечаются. - **Калибровка по chess.com (2026-10-28, владелец прислал разметку «Вечнозелёной»):** жертва — только фигура, отданная самим ходом (а не висевшая и раньше: 18…Rg8 — «!», не «!!»); правила «одна отметка на комбинацию», «уход атакованной фигуры» и «ход меняет исход» убраны (22.Bf5+! 23.Bd7+!, 13.Qa4!, 8…Qf6!). Совпало 7 из 8 отметок chess.com; 10…Nge7 (разрыв 9 % при пороге 10) — нет. Дальше калибровать по присылаемым партиям, а не подгонять порог под одну. -- **Калибровка 2 (2026-10-28, партия владельца с Rodent IV):** 18.Bxa7 — не жертва: ход вскрывает линию d на ферзя, и взятие слона сразу проигрывает больше (18…Rxa7 19.Rxd8). Правило ChessCom: фигура не считается отданной, если после её взятия ходящий тут же выигрывает не меньше (`taking_loses` в `features.rs`); правило Strict не менялось. **Набор сверки** — `crates/game-review/chesscom/` (партии с отметками chess.com в NAG, README); после каждой калибровки прогонять все: `cargo run --release -p game-review --example chesscom_check -- `. На 2026-10-28: 10 из 10 совпадений («Вечнозелёная» 8, партия с Rodent 2 !!). -- **Калибровка 3 (2026-10-28, «Бессмертная» по chess.com):** (а) жертва, которая матует быстрее любого другого хода, — не «и так выиграно»: 22.Qf6+!! (мат в 2), хотя 22.Qf7 тоже матует (в 4) — win % этого не различает (`mates_sooner` в `report.rs`); (б) для «!» лучшего хода движка падение оценки к следующей позиции не учитывается — это шум двух поисков (9.Nf5! и 12.h4! пропадали на оценках владельца: −0,51 → −0,82). Обе правки — только правило ChessCom. Набор: 17 из 17 на наших оценках; на оценках из кэша владельца 16 из 17 — 10…Nge7 «Вечнозелёной» (разрыв 9 % при пороге 10, пограничный случай с первой калибровки; порог под одну партию не двигаем). -- **Калибровка 4 (2026-10-28, Стейниц — фон Барделебен по chess.com):** правило калибровки 2 оказалось слишком широким — оно сняло 22.Rxe7+!! и 24.Rg7+!!: после 22…Qxe7 белые отыгрываются 23.Rxc8+, но эту угрозу открыло само взятие (ферзь ушёл с d7). Уточнено: фигура не отдана, только если угроза, отыгрывающая её, стояла уже сразу после хода (18.Bxa7: ферзь d8 под ладьёй до взятия). Оба !! совпали, 18.Bxa7 по-прежнему без !!. Расхождения по «!» в этой партии (у нас лишние 6…Bb4+, 8.exd5, 13.Bxe7, 17.d5, 18.Nd4, 19.Ne6, 23.Rf7+, 25.Rxh7+; нет 18…Kf7) — открыты, см. разбор владельцу. -- **Калибровка 5 (2026-10-28, по предложению, владелец согласился «посмотрим»):** правило ChessCom — (а) книжный ход (позиция после хода лежит на линии таблицы дебютов `chess-openings`, крейт `crates/openings`) не получает ни !, ни !!; (б) ! нет, если лучший другой ход оставляет ≥ 60 % (было 75; у всех ! chess.com в наборе — не больше 59 %, запас мал). Убрало 6…Bb4+, 18.Nd4, 23.Rf7+, 25.Rxh7+. Набор: 23 совпадения, 5 расхождений (8.exd5, 13.Bxe7, 17.d5, 19.Ne6 у нас лишние; 18…Kf7 нет — у чёрных 17 %, ! там не ставим); на оценках владельца ещё 10…Nge7. -- **Калибровка 6 (2026-10-28, ещё три партии: Пиллсбери — Ласкер, Ротлеви — Рубинштейн, Рети — Тартаковер):** правило ChessCom — (а) атакованная фигура, тихо переставленная под новый бой, — жертва (могла уйти): 18…Ra3!!, 20…Ng4!!; «всё равно потерянной» остаётся только фигура, которая напоследок бьёт (десперадо); (б) взятие, лишь отыгрывающее только что взятое соперником (не на том же поле), — не «выгодное взятие» и может быть «!»: 18.fxe6!; но не когда соперник взял фигуру, которую мы только что отдали (24…Bxe4+ после 23…Rd2 24.Qxd2 — продолжение комбинации); (в) пешка, отданная ради более быстрого мата, — «!!»: 29…b5+ (мат в 4 против 6 у 29…Qc4+). Набор: 7 партий, 38 совпадений, 6 расхождений (23.Rd2 у Пиллсбери: наш движок предпочитает 23.Qh3; остальные 5 — прежние в партии Стейница); на оценках из кэша владельца 35/9 — разброс движка (лучший ход другой, нет второго поиска). -- **Калибровка 7 (2026-10-28, ещё три партии; сначала прогон без правок):** Ласкер — Томас, Капабланка — Маршалл (поход по ходам) и Левицкий — Маршалл (только итоговые числа chess.com). До правок на двух партиях с ходами: !! 2 из 2, ! 1 из 1, лишних ! 2 (15.d4, 23.Kd3). Правка, правило ChessCom: «и так выиграно» для !! — только форсированный мат у лучшего другого хода (было: ≥ 90 % шансов); в наборе каждая жертва, где другой ход тоже выигрывал (до 93 %), — !! у chess.com (23…Qg3, 22…Rxc3, 20…Ng4). 22…Rxh3 (Левицкий — Маршалл) жертвой не считается: ладья за слона и пешку — чистая потеря 1 пункт при пороге 2; порог не двигали. 19.Rxd5 у нас !!, у chess.com у белых !! нет — ждём запись ходов. -- **Обмен партиями (2026-10-28):** владелец отдаёт chess.com партии, которые выбирает оркестратор; наш прогноз фиксируется коммитом до ответа (`chesscom/pending/README.md`). Бирн — Фишер: до правок !! 2/3, ! 1/1 (лишних 4). Правила ChessCom: взятие — «!» только когда все другие ходы проигрывают (≤ 33 %); отыгрыш после принятой собственной жертвы — не отдельный «!». Отброшено: «оставленная под боем фигура — жертва» (17…Be6!!, но +4 ложных !!). Каспаров — Топалов: до правок !! 3/5, ! 6/8 (лишних 6). Правило: жертву отменяет только угроза, созданная самим ходом, а не стоявшая до него (37.Rd7!!). Отброшено: «пешка, отданная единственным хорошим ходом, — !!» (33.c3+!!, но ложный !! на 17.d5). Фиксированный режим разбора (1 млн узлов, 1 поток) — набор: !! 91 % найдено, 95 % наших верны; ! 78 % / 72 %. -- **Строже «!» (2026-10-28, владелец: «!! почти 100 %, а ! можно и меньше, чем у chess.com — закрутить гайки»):** правило ChessCom — взятие никогда не «!»; «!» только если лучший другой ход хуже на ≥ 25 % (было 10). Перебор порогов на наборе: точность «!» упиралась в 72–76 % из-за взятий в форсированных вариантах; с этими правилами наши «!» — chess.com в 87 % случаев (найдено 54 % их «!»). 2 млн узлов вместо 1: «!!» без изменений, «!» +1 из 37 — оставили 1 млн. -- **Тихое отступление — не «!» (2026-10-29, владелец о 10.Be2 своей онлайн-партии: «ну какой же это !»):** правило ChessCom — атакованная фигура, уходящая на своё единственное хорошее поле без шаха, «!» не получает; уход с шахом — может (19…Ne2+, 23.Bd7+ у chess.com «!»). Теряем 13.Qa4! «Вечнозелёной» (chess.com) — осознанно: владельцу важнее, чтобы «!» не было лишних. Набор: «!» найдено 20 из 40, наших верных 80 %; «!!» без изменений. Ra7! из второй партии владельца был в 2.0.0, в 2.1.0 его уже нет. -- **Трудный ход — «!!» и без жертвы (2026-10-29, идея владельца «двумя движками»):** для кандидатов в !!/! — ещё неглубокий поиск (5 000 узлов, тот же детерминированный режим). Если ход — единственный хороший (разрыв ≥ 10 %), а неглубокий поиск выбирает другой ход и ставит этот на ≥ 30 % ниже — «!!». Опора — статья Zaidi & Guerzhoy 2024 (arXiv 2406.11895: блестящим считают ход, который слабый движок оценивает ниже, а сильный — лучшим). Набор: !! найдено 35 из 39 (было 32), верных 95 %; ложных не прибавилось; одинаково на 2 000–5 000 узлов и порогах 20–40 %. Для «!» трудность не включена: при «неглубокий выбрал тот же ход» «!» исчезает почти весь (5 000 узлов уже находят 127 из 141), при «неглубокий оценил ниже» уходят и матовые шахи, которые chess.com отмечает. Разбор длиннее на 1–2 %. Прежние правила — ветка Forgejo `marks-before-shallow`. В набор добавлены партии владельца с его вердиктом «это не !» (`owner-*.pgn`, тег `OwnerPlain`): 10.Be2 и Ra7 — сейчас без отметок. -- **Уход короля из-под шаха — не «!» (2026-10-29, владелец: «будем считать очевидным»):** правило ChessCom. Убрало три наших лишних «!» (23.Kd3, 20…Ka7, 32.Kd2) и три совпадения с chess.com (22.Ke3, 25…Kb6, 20.Ke2 — chess.com здесь непоследователен; к тому же на новой учётке он щедрее, сам писал об этом в 2023). Набор: наших «!» верны 27 из 28 (96 %), найдено 27 из 82 отметок chess.com; «!!» без изменений (35 из 39, 95 %). - Второй поиск движка (лучший ход, кроме сыгранного) — **всегда**, только для подходящих ходов: разбор примерно на треть дольше. Старые разборы дозаполняются кнопкой «Обновить» без пересчёта оценок. - Для оценок из PGN (`[%eval]`) !! и ! нет: в отчёте прочерк и пояснение. - В PGN — `$3`/`$1` с комментарием, только если у хода нет оценки автора. Русское имя `$3` — «Блестящий ход» (было «Отличный ход»); «Отличный ход» стал !, затем переименован в «Замечательный ход» (владелец, 2026-10-28). - -## Разбор партии на фиксированных параметрах движка (2026-10-28) - -Владелец: разбор партии всегда идёт на одних и тех же параметрах движка, пользователь их не выбирает — чтобы отметки ?!/?/??/!/!! и точность были одинаковы у всех людей и на всех машинах, а на слабых компьютерах и телефонах разбор шёл с разумной скоростью. Для анализа позиции «живым» движком выбор движка, потоков и памяти остаётся. - -- **Поиск** (`crates/game-review/src/job.rs`): каждая позиция — `go nodes 1 000 000` (`SEARCH_NODES`; 0,85 с на i7-13700KF, глубина ≈ 24), Stockfish с `Threads=1`, `Hash=32` МБ (`SEARCH_HASH_MB`), `MultiPV=1`, `ucinewgame` перед **каждым** поиском, включая второй (`searchmoves`, для !!/!). Результат зависит только от позиции (с её историей): не от машины, порядка позиций и числа процессов. Движок — Stockfish 19 из ChessPenguin (на компьютере — встроенный или скачанный программой, на Android — его сборка); пользовательский движок для разбора не берётся (с 2026-10-31 на компьютере — берётся Stockfish 19 пользователя, прошедший проверку, см. ниже). -- **Параллельность** — несколькими процессами движка, каждый берёт следующую позицию: по числу логических ЦП, на компьютере не больше 8, на телефоне не больше 4, и не больше, чем помещается в свободную память (`MemAvailable` в `/proc/meminfo` на Linux и Android: ≈ 200 МБ сети NNUE — она у Stockfish 19 в общей памяти, одна на все процессы, — плюс ≈ 70 МБ на процесс; где память не узнать — только пределы). Итого ≈ 0,8 ГБ на 8 процессов, ≈ 0,5 ГБ на телефоне. Процессы — с `nice 10` и на компьютере, и на Android. -- **Замер** (i7-13700KF, партия `rodent-roman-2026-10-27.pgn`: 113 позиций, 163 поиска): 1 процесс — 106 с, 4 — 28 с, 8 — 16 с; оценки всех трёх прогонов побайтно одинаковы (`examples/review_bench.rs`). Тест на `fake_uci --hash-memory` проверяет то же для 1/3/8 процессов и обратного порядка позиций. -- **Версия поиска** `SEARCH_VERSION` (сейчас 1) записывается в кэш разбора (`ReviewMeta.search`). Разбор другой версии (в том числе все разборы до этого решения, на «Быстро/Обычно/Глубоко») — устаревший: отчёт показывается, в панели отчёта «Этот анализ сделан с прежними настройками движка» и «Обновить», которое пересчитывает всё заново (не дополняет). Смена узлов, памяти, движка или его версии — повышать `SEARCH_VERSION`. -- **Подготовка к сопернику** ищет ошибки в дебютах тем же поиском (качество «Быстро» 250k узлов убрано — поиск в 4 раза дольше прежнего по умолчанию); кэш позиций и отчёты с оценками другой версии их не используют (ошибки ищутся заново). -- **Интерфейс.** Компьютер: диалог «Анализ партии» убран — кнопка 📈 сразу запускает разбор, оценка времени («N позиций, около T») — в её подсказке (выбирать в диалоге больше нечего, а прогресс виден на графике). «Проанализировать заново…» убрано (тот же поиск дал бы те же оценки); для оценок из PGN — «Проанализировать движком». Диалог подготовки к сопернику остался только с выбором цвета и оценкой времени. Без собственного Stockfish предлагается скачать его (окно без «Выбрать файл движка…»; скачанный становится активным движком, только если активного не было). Android: в листе запуска разбора — только описание, оценка времени и кнопка (на сенсорном экране нет подсказки); «Заново» и выбор качества убраны. -- Настройки `review.{quality,threads,hash_mb,chosen}` и `prep.quality` удалены; старые файлы настроек читаются (лишние поля пропускаются). -- Оценка времени — по скорости одного процесса из последнего разбора (или живого движка на поток; до замера — 700k узл/с на компьютере, 250k на телефоне) × число процессов. -- Сверка с chess.com (`chesscom_check`) идёт в том же режиме; `CP_REVIEW_NODES` — только для подбора узлов в этом примере, кэш в отдельной папке. Первый прогон на 1M (правила — на коммите 968ab22, 10 партий): !! — 17 из 18 chess.com (94 %), наших 18, из них 94 % совпали; ! — 24 из 29 (83 %), наших 30, совпали 80 %; совпадений 41, расхождений 12. - -## Встроенные базы-примеры обновляются с программой (2026-10-28) - -Владелец: база классики растёт (до 120–150 партий) и должна быть сразу доступна, в том числе у тех, у кого уже лежит старая версия. - -- **Компьютер** (`apps/desktop/src/examples.rs`). Текст примеров вшит в программу (`include_str!`). При первом запуске файлы пишутся в `/examples/` под именем на языке интерфейса и ставятся на полку (`settings.examples_added`). При **каждом** запуске файл примера сравнивается с вшитым текстом побайтно; отличается (старая версия, повреждён, изменён снаружи) — заменяется атомарно (`chess_core::pgn::store::write_atomic`). Отдельной версии нет: версия — сам текст. Файл ищется под именем примера на любом языке (имя дал язык первого запуска). -- Пример, убранный с полки, **на полку не возвращается**; его файл, если он остался на диске, всё равно обновляется (это файл программы, только для чтения; открыть его снова — получить новую версию). Удалённый с диска и не стоящий на полке файл заново не создаётся; стоящий на полке — создаётся. -- Кэши не мешают: число партий на карточке (`db_counts`) привязано к размеру и времени файла — пересчитывается; отметки просмотренных партий (`viewed`) — к тексту партии, у неизменных партий сохраняются; поиск позиций по PGN и справочник держат данные в памяти, а замена идёт при запуске, до открытия баз. -- **Android** (`data/Library.kt`). Примеры не копируются: читаются прямо из assets приложения, поэтому с обновлением приложения новая версия открывается сама. Запомненное число партий в строке списка сверяется с SHA-256 текста, из которого оно взято (`DbEntry.sha256`); не совпало — пример перечитывается при показе списка баз (`countSamples`). - -## Веб-версия (2026-10-30) - -Исследование — `docs/research/web-version.md`, `web-version-tech.md`; подпроект `web/`, задача 22. Решения владельца: -- Начинаем с **лёгкой версии**: открыть PGN/ChessBase-архив, смотреть и править партии, анализ движком, разбор с !!/!, скачать PGN. Полная (свои базы, подготовка к сопернику, игра с компьютером, офлайн) — потом. -- Размещение — **наш сайт**, адрес вида `chess.vrubel.xyz/app/` (заголовки COOP/COEP для многопоточного Stockfish). -- Браузеры: **Chrome, Edge, Firefox, Safari** — веб-приложение **только на компьютере**. **Телефоны и планшеты (в том числе iPad) — без веб-приложения** (владелец, 2026-10-30: «не будем на это тратиться»): страница «на Android — скачайте приложение, на iPhone/iPad — приложение скоро будет»; определение устройства — по `docs/design/web-version.md` §3.6 (iPadOS выдаёт себя за Mac; короткая сторона экрана, касание), тихая ссылка «всё равно открыть веб-версию». -- По открытым вопросам дизайна приняты рекомендации: только чтение и в Chrome (в исходный файл не пишем никогда); справочника в лёгкой версии нет; предупреждение для файлов больше 1 ГБ; на странице для iPhone/iPad — «напишите нам» ссылками (почта/Telegram), без форм. -- **Базы — только чтение, прямо с диска**, без копии: Chrome/Edge помнят выбранный файл (одно «разрешить»), Firefox/Safari — файл выбирается заново после перезагрузки; по желанию — «оставить копию в браузере» с показом занятого и свободного места (квота браузера) и отказом с объяснением, если не помещается. -- **Свои партии** (игры с движком, созданные для анализа), разборы и настройки — в хранилище браузера (OPFS/IndexedDB) с запросом постоянного хранения, показом занятого места и кнопкой «скачать мои партии в PGN». -- **Интерфейс адаптируется под веб** (палец, узкие экраны, открытие файлов кнопкой/перетаскиванием, замена Ctrl+W/Ctrl+N, установка на главный экран) — сначала дизайн. - -## Разбор партии на Stockfish 19 пользователя; перетаскивание файлов (2026-10-31) - -Владелец одобрил по жалобе пользователя (свой stockfish в настройках, анализ позиции работает, а разбор просил скачать). - -- **Движок разбора на компьютере** (`apps/desktop/src/review_engine.rs`): свой Stockfish 19 программы → движок пользователя, прошедший проверку → предложение скачать. Кандидаты — движки анализа из настроек (активный первым) и `stockfish` из `PATH`; движки игры (Rodent IV/V, Maia — их папки) не проверяются никогда, при любых настройках. Android и веб не меняются. -- **Проверка** (`game_review::probe`): движок, назвавшийся (`id name`) не «Stockfish 19», отвергается сразу после `uci`, без поисков (Rodent, Komodo — доли секунды). «Stockfish 19» делает три поиска в режиме разбора (`Threads=1`, `Hash=32`, `MultiPV=1`, `ucinewgame` перед каждым, `go nodes 100000`, строка — как в разборе); лучший ход, оценка и число узлов должны совпасть с эталоном `REFERENCE` (снят 2026-10-31 нашим `stockfish-linux-x86-64-universal`; тот же ответ дали сборки SF19 из исходников релиза под x86-64 (SSE2) и x86-64-bmi2; Stockfish и сам требует одинакового `bench` от всех срезов универсальной сборки, `scripts/check_universal.sh` релиза). Сторож: 10 с на поиск, 30 с на всю проверку; не успел — «не успел ответить на проверку», в памяти до следующего запроса, на диск не пишется. Проверка — в фоне (`nice 10`), движок запускается по пути из настроек/`PATH` (snap и обёртки смотрят на имя запуска), вердикт — для реального файла. При выходе программа ждёт проверки не дольше 2 с; движок, зависший на рукопожатии, умирает вместе с потоком проверки (`EngineConfig::kill_with_parent`, `PR_SET_PDEATHSIG` на Linux). -- **Кэш**: вердикт по реальному файлу (ссылки разрешены) + размер + время, вместе с ключом эталона (`reference_key`, FNV позиций/узлов/хэша/ответов) в `/review-engines.json`; другой ключ — всё проверяется заново. «Не запустился» не запоминается: сказано один раз, при следующем запросе — новая попытка. При старте разбора `id name` движка пользователя сверяется ещё раз (обёртка могла начать запускать другое): не «Stockfish 19» — разбор останавливается до первой оценки, вердикт забывается. Оценки те же, поэтому `SEARCH_VERSION` и кэш разборов не меняются. -- **Ожидание проверки** привязано к своей партии/подготовке (номер экрана): закрыта или открыта другая — разбор не начнётся на чужой; разбор партии и ошибки в дебютах ждут отдельно; «Проанализировать движком» (заново) сохраняется. Тост «Проверяю, подойдёт ли ваш движок для разбора…» — только когда движок действительно проверяется. -- **Окно, если не подошёл** — пять случаев: другой движок («В настройках указан …» / «В системе найден …»), «Ваш Stockfish 19 считает иначе, чем сборка ChessPenguin (другая сборка или сеть)…», «Не удалось запустить …», «… не успел ответить на проверку — проверю снова в следующий раз»; затем зачем нужна официальная сборка, «Скачать?», «Ваш движок остаётся для анализа позиции» (кроме незапустившегося) и «…начнётся сам после загрузки»; ниже — «N МБ · с официальной страницы Stockfish». Без движка — как прежде. -- **Перетаскивание на компьютере** (`platform::files::take_dropped`): брошенные файлы открываются как «Добавить базу» (на полку, выбирается первая; партия на экране не закрывается, тогда тост «Добавлено на полку: …»). `.pgn/.cbh/.cbv/.zip/.7z` — базы; другие файлы ChessBase-базы (`.cbg`, `.cba`, `.cbj`, … — известные расширения) — её `.cbh` рядом, база один раз (дубли по реальному файлу); папка — базы в ней (без вложенных), пустая — тост; несуществующий файл — «Не найдено: …»; прочее — «Это не база: …». База, уже стоящая на полке под другим путём к тому же файлу (ссылка), второй раз не добавляется (`touch_database` сравнивает реальные файлы). Брошенные файлы не заменяют базу из «Выбрать снова»; отмена этого диалога его завершает. Пока файл над окном — подсветка окна с рамкой и карточка «Отпустите, чтобы открыть». -- **Где работает перетаскивание**: Windows, macOS, Linux в X11 и XWayland. В сеансе Wayland окно перетаскивание не принимает (система и не показывает «можно отпустить»): в winit 0.30.13, на котором стоит eframe 0.36, перетаскивание есть только в X11 (`platform_impl/linux/x11/event_processor.rs`), в `wayland/` его нет. Принудительный запуск через X11 не делаем (без обходов). - -## Подготовка к сопернику: какие партии брать; сохранённые подготовки (2026-10-31) - -Владелец, задачи 20 и 21: -- **Период.** Рядом с глубиной — выбор партий: все / за 3 месяца / полгода / год / 2 года / последние 50 / 100 / 200 (5 лет владелец убрал: «бред»). У каждого варианта сразу видно, сколько партий он берёт (для показанного цвета). Время считается **от последней партии соперника в базе**, не от сегодня (владелец: «давай от последней») — так старая база не оказывается пустой. «Последние N» — самые свежие N партий каждым цветом. -- **Партии без даты** берутся только во «Всех партиях». При выборе периода под списком написано, сколько их не учтено. Если дат нет ни у одной партии, выбор по времени не показывается, остаётся выбор по числу: последние записи базы. -- **Сохранённые подготовки.** С 2026-11-01 (владелец) сохранение автоматическое, кнопки «Сохранить» больше нет: подготовка попадает в «Подготовки» сразу при запуске, её отчёт с найденными ошибками записывается, как только построен, и дальше все изменения (поиск ошибок, период, глубина) пишутся сами. Подготовка лежит в данных программы (`~/.local/share/chesspenguin/preparations/`, не в кэше). На каждого игрока базы — одна подготовка: повторный запуск заменяет прежнюю. Удалённая из «Подготовок» не воскрешается сама: пока её экран жив, обратно она не пишется. -- **Где их открыть.** Кнопка «📑 Подготовки» в библиотеке: список (имя, база, период, партии, цвет, ошибки, дата), там же «Открыть», «Переименовать», «Удалить» и «♟ Новая подготовка…». Если в базе появились новые партии, подготовка собирается заново с прежними оценками, и движок досчитывает только новые позиции. - -## Подготовка: ручная сверка с книгой и автозапуск движка (2026-11-01) - -Владелец: -- **Сверка с книгой — только вручную.** Автоматический поиск «выхода из книги» после построения отчёта грузил все ядра без ведома пользователя (замерено ~2300 % CPU без stockfish). Теперь запуск — только кнопкой «▶ Сверить с книгой» рядом с выбором книги, с прогрессом «X из N партий» и отдельной остановкой. Остановка отбрасывает незавершённый проход (результат применяется только целиком), частичных чисел нет; прежний завершённый результат сохраняется. -- **Движок — автозапуск.** Поиск ошибок стартует сам после построения отчёта, без диалога-объяснения; вкладка «Ошибки» открывается один раз при фактическом старте. Полный кэш — без запуска и без переключения вкладки. Ручная остановка сохраняет оценённые позиции и запрещает автоперезапуск этой конфигурации, **включая повторный вход в сохранённую подготовку** (флаг в отчёте); сброс — только смена глубины/периода или явное «Продолжить» (запускает лишь недостающие позиции). -- **Смена условий.** Другая книга во время сверки отменяет проход и отбрасывает его результат; глубина/период отменяют проход вместе со старым отчётом. После перестроения книга сама не сверяется, движок запускается автоматически. Уход с экрана фон не останавливает. -- **Движок не установлен** — автозапуск не открывает диалог и не качает сам: на «Ошибках» предложение добавить движок; после установки — существующий `start_after_engine`. - -Дизайн движка — `docs/design/opponent-prep.md` (§4); прежние книжные требования и 22 сценария сохранены как история в `docs/research/prep-manual-book.md`. Книжная часть отменена следующим решением. - -## Подготовка: сверка с книгой удалена (2026-11-02) - -Владелец отменил книжную часть решения от 2026-11-01: анализ выхода из книги убирается из подготовки полностью, а не только непонятная сводка с медианой и процентом. Из диалога и отчёта удаляются выбор книги, ручной запуск, прогресс/остановка, фоновый проход, колонки и все сохранённые книжные результаты; алгоритм `find_book_exits`, example и dev-hook тоже удаляются. Обычный Справочник и книги движков игры не затрагиваются. - -Старые поля книги в JSON отчёта, сохранённой подготовки и настроек остаются пассивными legacy-данными: не вычисляются и не показываются, но не стираются при обычном автосохранении. Миграции и удаления пользовательских файлов нет. Это осознанно оставляет возможность вернуть функцию будущим откатом; в описании будущего коммита удаление книги отметить отдельно. Автозапуск движка, ручная остановка и сохранение `engine_stopped` не меняются. - -## Партия на Lichess / Chess.com (2026-10-31) - -Владелец: из скачанной партии перейти на её страницу. Ссылка берётся из тега Link (Chess.com), иначе из Site (Lichess), если там веб-адрес. Кнопка «🌐» в шапке партии после результата, пункт в ☰ и в контекстном меню строки списка партий. Партия Lichess открывается на показанном ходу (`#ply`) и со стороны, которая внизу доски (`/black`); у Chess.com такой ссылки нет — открывается страница партии. Адрес из подстроки шапки убран: его открывает глобус. - -## Дебютные репертуары и тренировка по дереву (2026-11-02) - -После исследования ChessTempo (`docs/research/chesstempo-opening-trainer.md`) владелец делегировал оставшиеся решения оркестратору и попросил начать реализацию. Принято: - -- **Два режима.** Одноцветный ChessTempo-режим: пользователь играет свою сторону, программа отвечает только ходами включённого дерева; SRS-задание — конкретный ход. Режим за оба цвета: пользователь делает каждый полуход, любой включённый ход из текущей позиции принимается и ведёт по его ветке, ход вне разрешённых продолжений — ошибка. Прежний запрет одноцветного режима отменён. Подсказка по запросу после третьей ошибки и отметка «с подсказкой» сохраняются. -- **Библиотека.** На экране баз рядом с «Подготовками» — «Тренировка дебюта». Полноценный экран репертуаров, дерева и тренировки, не последовательность модальных окон. Прежнее «Учить дебют до этого хода» заменяется на **«Добавить в репертуар…»**: путь от начала партии до выбранного хода сливается с деревом без немедленного запуска и без изменения исходной партии/PGN. -- **PGN и глубина.** Репертуар — самодостаточный PGN-снимок со всеми ветками, комментариями, NAG и исходным FEN. Учебные хвосты не удаляются и не угадываются автоматически. По умолчанию тренируются первые **10 ходов (20 полуходов)**; глубину можно менять, ветки можно отключать без удаления и ограничивать область тренировки. Добавление «до этого хода» сохраняет точный выбранный префикс, без соседних веток и хвоста. -- **Транспозиции и статистика.** Одинаковые позиции объединяются по FEN4 внутри одного репертуара: одна learning-запись и каноническое продолжение, все PGN-пути сохраняются. Между разными репертурами и режимами White/Black/Both статистика не смешивается. Старые line-run агрегаты не превращаются в выдуманную per-move статистику. -- **Фундаментальный объём.** Несколько репертуаров, добавление/импорт дерева, depth/disable, одноцветная SRS-очередь (due/unseen, успех отодвигает, ошибка приближает), обзор подряд и сначала новые/давние, транспозиции, статистика по ходам/веткам/репертурам. Расширенные графики, resistant-наборы и массовые операции — следующие этапы. -- **Платформы.** Сначала полный desktop. Android продолжает использовать прежний линейный тренер, его UniFFI API и `training.json`; новая библиотека требует отдельных Kotlin-экранов позже. Web не включается до отдельного хранилища VFS. Все записи атомарны, ошибки видны пользователю, исходные базы не изменяются. - -## Прохождение дебютов без скрытого целевого хода (2026-11-02) - -Владелец после живой тренировки отверг сценарий «ход есть в репертуаре, но сейчас -повторяется другой»: непонятно, чего программа требует и как продолжить. Это -изменяет прежние решения о target/try again в одноцветном тренере. - -- Основной сценарий desktop — **«Пройти варианты»**: выбрать цвет и пройти ветку - целиком. Любой включённый ход принимается, за другой цвет отвечает программа - ходами из PGN. За обе стороны все ходы делает пользователь. -- Автоответы следуют очередной предложенной ветке, пока пользователь не выбрал - другое включённое продолжение. Его выбор переключает фактический путь. -- Подсказка доступна сразу и предлагает ход текущей ветки. На развилке явно - сказано, что допустимо несколько продолжений. Ошибка — только ход вне - включённого репертуара; возвращение позиции сопровождается понятной подсказкой. -- После конца области/глубины/листа/повторения — результат фактического прохода, - основное действие «Следующая ветка» (Enter), отдельно «Повторить путь». -- Повтор отдельных позиций — отдельный дополнительный режим. И здесь включённая - альтернатива принимается: учитывается только сыгранный ход, а несделанная - целевая позиция остаётся due/unseen. Угадывать скрытый ответ не требуется. -- Старые сохранённые настройки очереди однократно переключаются на основной - сценарий с сохранением выбранного цвета. Позднее явно выбранный режим повторения - сохраняется; PGN и история попыток при миграции не меняются. -- Android остаётся на старом линейном API; web новый вход не получает. - -## Простая случайная тренировка вариантов (2026-11-03) - -Владелец отменил ручные параметры и расширенные режимы в desktop-интерфейсе. Это решение имеет приоритет над пунктами про глубину, disabled, scope и SRS выше; внутренние совместимые API и старая статистика могут остаться, но скрыто ограничивать тренировку не должны. - -- В репертуаре остаются только выбор цвета `Белые / Чёрные / Оба`, число доступных вариантов и запуск. Настроек глубины, области, отключения веток и «Пройти варианты / Повторять отдельные позиции» нет. Видимое дерево ходов также удалено; PGN-дерево остаётся внутренней моделью. -- В самой тренировке текстовые ходы также не показываются: ни SAN/номера, ни отметки ошибок у ходов, ни отдельная панель нотации. Повторное уточнение владельца 2026-11-03 выбрало удаление, а не копирование нотации из экрана партии. Просматривать уже показанные позиции можно только на доске прежними кнопками/клавишами; внутренний путь для механики сохраняется. -- Тренируются все варианты целиком, без лимита 20 полуходов. Старые `max_plies` и `disabled_prefixes` при загрузке библиотеки снимаются; PGN и исходные файлы не меняются. -- Очередь случайная. Полный маршрут не повторяется, пока пользователь не прошёл остальные маршруты текущего круга; затем начинается новый случайный круг. Общий префикс разных веток не считается пересечением: иначе невозможно пройти все ветки. -- Проход может начинаться не с первого хода. Программа автоматически показывает предыдущий участок как контекст и предлагает продолжить вариант; для White/Black первая пользовательская позиция соответствует выбранному цвету, для Both пользователь продолжает за обе стороны. -- На развилке по-прежнему принимается любой ход из PGN. После завершения две отдельные операции: «Повторить путь» — тот же фактический маршрут с тем же началом, без продвижения очереди; «Следующая ветка» — новый непройденный маршрут текущего круга. -- В библиотеке остаются `Название | Варианты | меню`. Число вариантов — доступные полные маршруты, а не завершённые тренировки. Колонки due удалены вместе с SRS UI; сохранённые попытки и история не стираются. -- Случайная очередь не блокирует окно и не требует материализации всех маршрутов большого дерева. Это относится и к «Следующей ветке», не только к первому запуску. Курсор и совместимость сохранённой статистики проверяются тестами; изменение PGN начинает новый круг по fingerprint содержимого, даже если число маршрутов осталось прежним. -- Уточнение владельца 2026-11-03: создание пустого репертуара оставляет пользователя в списке; импорт/экспорт убраны с экрана доски и доступны в меню строки; настройки — в правом углу шапки. Список оформлен как основная таблица партий: один клик выделяет, двойной открывает. - -## Единый экран репертуаров и ECO в таблице (2026-11-03) - -Владелец отменил раздельные экраны списка и описания репертуара. Это решение заменяет прежние требования к переходу по двойному клику и кнопкам навигации по позициям. - -- «Тренировка дебюта» сразу открывает одну рабочую область с доской. Карточка выбранного репертуара, таблица и все операции библиотеки находятся рядом; таблица доступна и во время тренировки. Отдельного экрана списка нет. -- Один клик выбирает строку и меняет доску без перехода. Запуск — отдельной кнопкой. Кнопки `⏮ ◀ ▶ ⏭` удалены из панели тренировки. -- Таблица `Название | ECO | Варианты | ⋯`: названия дебютов и вариантов перечислены с новой строки в ячейке названия, коды — в отдельной колонке. Используется встроенный справочник `chess-openings`, наиболее точное название каждого полного маршрута; вычисление выполняется в фоне. Большая база не требуется. -- Создание, переименование, импорт, экспорт и удаление выполняются в той же рабочей области. Несохранённая статистика активной тренировки по-прежнему защищена от молчаливой потери. -- Уточнение владельца 2026-11-03: «Пути» переименованы в «Варианты»; ECO выровнены построчно с названиями тем же мелким шрифтом; карточка и статистика используют ровные сетки. Кнопка «Репертуары» удалена. Статусы «Импорт PGN», «Индексация вариантов и ECO» и «Подготовка тренировки» заменяют непонятное «Готовим дерево». -- Уточнение владельца 2026-11-03: статистика всегда занимает одну высоту, до попыток показаны нули и прочерк даты. Все строки таблицы одинаковые, с местом под пять ECO/названий. Добавлен сброс статистики текущего репертуара и цвета с подтверждением; другие режимы не очищаются. -- Уточнение владельца 2026-11-03: число вариантов — слева у подписи, «Начать» и «Сбросить» — одинаковой ширины. Для UI обязательна приёмка отдельным дизайн-ревьюером с реальными снимками и проверкой отсутствия скачков; требование закреплено в `AGENTS.md` и `.opencode/agents/`. -- По результатам независимой визуальной приёмки: workspace и тренировка имеют общую шапку и одинаковую геометрию доски; нижняя область задаётся явными прямоугольниками, чтобы содержимое не меняло её размер. Выбранная строка прокручивается в видимую область один раз, запуск использует primary-стиль. -- Уточнение владельца 2026-11-03: случайный круг и счётчик используют только исходные PGN-ветки; переключение между ними по транспозициям не создаёт новые варианты. Старт не позже чем за семь полуходов до конца ветки, короткие ветки проходятся с начала. -- Уточнение владельца 2026-11-03: на доске тренировки показываются NAG и графические пометки PGN (`[%cal]`, `[%csl]`) теми же значками и цветами, что при просмотре партии. Пометки относятся только к текущему узлу. -- Уточнение владельца 2026-11-03: раздел «Прежние линии» удалён из библиотеки как непонятный и ненужный до первого выпуска функции. Переключателя и таблицы архивной статистики больше нет. Старые файлы данных и Android-совместимость не затрагиваются. -- Уточнение владельца 2026-11-03: ячейка репертуара получила отступ 8 pt сверху и интервал 12 pt перед первым дебютом. Название — 16 pt, дебюты/ECO — 14 pt вместо заниженного `.small()`; высота строки 156 pt фиксирована для 0–5 названий (верх 8 pt, низ 4 pt), чтобы не было скачков и вертикального clipping. По результатам независимой визуальной проверки фоновый статус получил постоянную строку 24 pt, чтобы таблица не подпрыгивала после индексации. - -## Тренажёр по ТЗ ChessTempo: новая модель обучения (2026-11-04) - -Владелец подтвердил, что `docs/chesstempo_opening_trainer_TZ.md` имеет приоритет над его прежними импровизированными упрощениями и над прежними решениями здесь, включая random path practice, per-repertoire историю, any-enabled-answer и изолированный reset. Сохраняются текущая рабочая область, PGN-дерево, FEN4, доска, таблица библиотеки, типографика и защита несохранённых данных. UI развивается внутри этой концепции, без переноса всех графиков на один экран. - -- **Единица знания.** Общая `LearningItem(user/profile, FEN4, expected UCI)`, не запись по репертуару/режиму. Одинаковый ход в разных репертурах и транспозициях имеет общую историю и расписание. Членство в репертурах/ветках отделено от знания. Старые `MoveStats/RunStats/PathStats/random cursor` — legacy, а не второй источник новых показателей. -- **Попытки.** Независимые `CORRECT_INDEPENDENT` и `INCORRECT_INDEPENDENT` влияют на серии и Accuracy. `PREVIEWED`, `REPLAY_AFTER_ERROR`, `AUTO_CONTEXT`, `ILLEGAL_MOVE` не увеличивают успех или ошибку. Learnt — три независимых успеха подряд, но повторения продолжаются. Каждая попытка имеет `client_attempt_id` для идемпотентности. -- **MVP.** Один основной ответ на собственную позицию репертуара; альтернативы остаются в PGN/редакторе. Это ограничение нашего MVP, не правило ChessTempo: ответ Richard подтверждает, что оригинал может обучать несколько собственных ответов одной позиции как отдельные элементы. Поэтому модель ключа сразу содержит UCI и не закрывает расширение позже. -- **SRS.** Реализуется проектный псевдокод ТЗ, не объявляется побитовым алгоритмом ChessTempo: first correct +1 день, mistake +30 секунд, preview +60 секунд, growth ×2 от фактически прошедшего времени, max 1095 дней. Review in Order/Least Recent используют общий обработчик попыток и тоже обновляют SRS. -- **Статистика.** `T = Unseen + Learning + Learnt`; `Uncertain ⊆ Learnt`, `Due ⊆ Learning+Learnt`, повторного сложения нет. Проценты и статусы вычисляет core по активному множеству и единому `as_of`, а не UI по старым записям. Общая статистика нескольких репертуаров — union по LearningItemKey. При T=0 проценты — `—`. -- **Reset/delete.** Общий LearningItem сбрасывается во всех затронутых репертурах с предварительным показом N/M и имён. `Reset selected view only` не предлагать. Удаление репертуара не стирает глобальные записи; они лишь перестают входить в активное множество. -- **Хранение.** Следующая версия JSON читает старую, перед записью делает новый backup и сохраняет legacy без выдумывания независимой Accuracy. Старые streak/schedule можно мигрировать консервативно; смешанные hinted/replay счётчики не превращаются в независимые попытки. Запись события и изменение состояния атомарны. -- **Этапы.** Сначала LearningItem/events/SRS/aggregates и AT-ядро, затем graph/main answer/scope, хранилище v3 и строгая session state machine, затем desktop MVP. После него: Review in Order/Least Recent, четыре Learning priority, reinforcement/adaptive context, Uncertain/Resistant, shared reset, истории/графики и дашборды V1. V2 вне текущего этапа. -- **UI.** Единый workspace сохраняется. Основные CTA и KPI используют один scope. Таблица остаётся библиотечной, полные summary/истории открываются отдельно по мере готовности. Automatic context анимируется последовательно со `settings.animation.seconds()` (Off/Fast/Normal/Slow = 0/0,12/0,25/0,5 с) при фиксированной скорости; при адаптивной — с `base / speed_factor` текущего шага. Фактический slide и scheduler обязаны совпадать, автоматические события не являются независимыми попытками. -- **Context policy.** Шесть параметров контекста/скорости сохраняются отдельно для каждого репертуара в Settings. Сессия получает snapshot политики при создании; изменение настроек не переписывает уже начатую сессию. Дополнительные параметры находятся в collapsed-блоке, доска не перегружается. -- **Dashboard.** Details открывает текущие репертуар и сторону, Global выбирается явно. Вместо непонятного `T` используется Total; видно `Learnt = Confident + Uncertain`, знаменатель процентов — Total. Графики разделены по вкладкам History/Scheduled/Sequences, точные значения остаются в таблицах. Снимок текущей статистики сохраняется автоматически при первом просмотре scope в локальный день и доступен вручную; дубли date/scope запрещены, PGN и знание ходов снимок не меняет. -- **Depth и линии.** `max_plies` из редактора ограничивает тренировочный scope и его CTA/KPI; полная история dashboard сохраняет полный scope. Статистика конкретной линии допускает пересечения с другими линиями; ветка объединяет свои транспозиции, а весь репертуар/Global — только уникальные LearningItemKey. Среднее арифметическое процентов линий не используется. -- **Визуальная матрица.** По решению владельца 2026-11-04 минимальный размер визуальной приёмки — **960×600**, основной — **1400×900**. Размер 640×480 и микро-контейнеры не определяют дизайн и не используются для визуального вердикта; прежние кадры остаются только историческими QA-артефактами. -- **Проверка.** AT-01…30 являются обязательными поэтапными критериями, а не формальным списком. До соответствующей реализации не объявлять их выполненными. Production агрегаты проверяют математические инварианты и сообщают нарушения в лог. После UI — отдельный design reviewer с реальными снимками и переходами, согласно `AGENTS.md`. - -## Android: открытие PGN из буфера обмена (2026-11-04) - -Владелец уточнил сценарий задачи 35. При холодном запуске и возврате в приложение оно проверяет текст буфера на PGN, но импортирует только после подтверждения пользователя. При нескольких партиях всегда открывается первая; остальные остаются доступны в локальной копии базы. Диалог использует существующий Material 3 стиль, без нового отдельного экрана-мастера. - -- Текст проверяется существующим PGN-reader на фоновом потоке; некорректный или пустой текст не вызывает предложение. Сетевых вызовов и передачи содержимого наружу нет. -- Импорт использует `Library.addCopy`: локальная копия сохраняет полное PGN-дерево, комментарии и анализ. Навигация открывает `GameAt(id, 0)`, независимо от числа записей; поведение обычных файлов `Incoming.Opened` не меняется. -- Один и тот же SHA-256 текста не предлагается повторно после открытия или отказа, в том числе при повороте и холодном перезапуске. Сам текст в настройки не записывается; обработанный hash сохраняется локально. Состояние нерешённого вопроса сохраняется в Application, асинхронный результат устаревшего текста отбрасывается. -- Диалог не перекрывает `UpdateSheet`, `Incoming.Opening` или `Incoming.Failed`; после подтверждения используется существующий прогресс и обработка ошибок. Если блокировщик появляется поверх нерешённого предложения, оно скрывается без отказа, а после закрытия выполняется свежая проверка. - - -## Переработка UI/UX тренажёра после проверки владельцем (2026-11-05) - -Владелец отклонил предыдущую компоновку: непонятные Total/Unseen, техническая глубина, -разнородные и разнесённые кнопки, нечитаемые ветки, ручное сохранение истории. -По этому запросу дизайн пересмотрен (`docs/design/opening-cleanup-2026-11-05.md`). -Реализованы единая строка трёх основных действий, сводка с единицей «ходы», отсутствие -числовой глубины на старте, обзор выбранного репертуара, дополнительный отчёт вариантов -с четырьмя колонками и автоматическая история без ручной кнопки. Прежние указания о -расположении кнопок сброса/деталей и дублирующем счётчике вариантов заменены этой компоновкой. -SRS, общий прогресс, явное подтверждение сброса и точные существующие лимиты сохранены. -Это реализация по запросу владельца; независимая QA-проверка не заменяет его оценку дизайна. - - -## Тихие фоновые операции и общая дизайн-система (2026-11-05) - -Владелец попросил не показывать «Сохранение прогресса» при каждом ходе и вращающийся -индикатор при запуске на главном экране. Обычная запись прогресса выполняется без -уведомления; ошибки и безопасный повтор остаются видимыми. На главном экране круговые -индикаторы убраны, информативные текстовые статусы/проценты длительных операций сохранены. - -Общая дизайн-система описана в `docs/design/design-system.md` по библиотеке, просмотру -партии и игре с движком. Тренировка дебюта не является стилевым эталоном. Фактические -значения текущего UI отделены от рекомендуемых правил унификации новых экранов. - -## Общие настройки и ошибки при подготовке к сопернику (2026-11-05) - -По запросу владельца глобальные настройки доступны справа в шапке библиотеки -репертуаров, статистики, прохождения тренировки и редактора. Используется общая -кнопка библиотеки/партии: «⚙ Настройки», в узком окне — значок с подсказкой Ctrl+,. -Параметры конкретной тренировки остаются отдельным действием. Открытие общих -настроек не сбрасывает текущую задачу, позицию, вкладку или черновик. - -Владелец исключил из подготовки ошибки изучаемого игрока, которым предшествовала -ошибка его соперника. Отбор проходит по хронологии каждой партии: после первого -?!, ? или ?? другой стороны поздние ошибки игрока не включаются. Пороги остаются -существующими; ранние ошибки игрока сохраняются. Пока предыдущие ходы другой -стороны не проверены, поздняя ошибка не публикуется. При транспозиции применимость -проверяется по истории каждой партии, а не только по общей позиции. - -Кэш и сохранённые отчёты пересчитывают производные ошибки/повторы/счётчики из -сохранённых оценок; повторный запуск движка для этого не нужен. Старые счётчики -в списке подготовок скрываются до открытия и пересчёта соответствующего отчёта. -PGN, дерево дебютов и оценки движка от этого фильтра не меняются. - -## Первый вход и понятные параметры тренировки (2026-11-05) - -При первом открытии автоматически выделенный репертуар проходит тот же выбор, -что и при клике: сразу восстанавливаются его сохранённые цвет, режим и порядок. -Раньше до клика использовались белые и SRS по умолчанию, поэтому кнопка и счётчики -могли относиться не к ожидаемым настройкам. При доступных заданиях запуск работает -без повторного выбора строки. Расписание SRS не обходится: если пока нет заданий, -подсказка объясняет возможность выбрать режим повторения. - -Параметры вынесены из длинного меню в отдельное окно с прокручиваемым содержимым -и видимой кнопкой закрытия. Группы: предыдущие ходы, пропуск знакомого начала, -скорость показа; единицы и условия действия подписаны. «Минимум дней для закрепления» -заменён на горизонт повторения до срока: это не возраст знания. Порог пропуска — -серия верных ответов для каждого своего хода, а не число пропускаемых ходов. -Параметры относятся к новым сессиям; продолжение сохранённой сессии оставляет её -прежнюю политику, как и до UI-правки. Хранение, диапазоны и алгоритмы не менялись. - -Независимая сверка счётчиков по пользовательской копии, журналу событий и реальным -сессиям не выявила арифметического дефекта. «Изучено» по-прежнему требует трёх -самостоятельных верных ответов подряд; автоматический показ и повтор решения -не увеличивают серию, ошибка сбрасывает её. Подсказка не увеличивает и не сбрасывает -серию. Параметры контекста не меняют этот критерий. Подробности и границы проверки: -`docs/qa/learning-counts-and-parameters-2026-11-05.md`. - -## Обозначение альфы и управление доской тренировки (2026-11-05) - -По запросу владельца название раздела в библиотеке и его шапке — -«Тренировка дебюта (α версия)», с греческой буквой α. Кнопка переворота доски -относится к нижней панели управления, как на экране партии, а не к группе подсказки. -Подсказка и управление показом ходов остаются возле текущего задания. - -Повтор первого хода оказался повторным показом автоматического контекста следующей -цели, а не двойным самостоятельным ответом. Если новая цель продолжает уже показанный -путь того же репертуара, UI сохраняет текущую доску и не озвучивает/анимирует этот -префикс повторно. Проверяются полный путь и позиция; совпадение FEN при другом порядке -ходов недостаточно. Самостоятельные вопросы контекста не пропускаются. События -AUTO_CONTEXT сохраняются прежним способом, включая обработку ошибки записи и retry. - -## Перетаскивание во время сохранения ответа (2026-11-05) - -Отдельно воспроизведён возврат перенесённой фигуры на исходную клетку во время -фоновой записи. На отпускании мыши и в кадрах ожидания ещё рисовалась старая доска. -Виджет теперь рисует результат легального переноса уже в кадре отпускания; -тренировочный UI сразу показывает эту позицию, сохраняя блокировку повторного ввода -до подтверждения записи. Подтверждение и retry не запускают движение заново. -Самостоятельный успех не записывается до успешного сохранения. Для хода двумя -кликами остаётся обычная анимация; для неверного ответа — возврат, для рокировки -и взятия — движение ладьи и исчезновение взятой фигуры. PGN-модель виджет не меняет. - -## Стабильная панель библиотеки при запуске (2026-11-06) - -По сообщению владельца воспроизведены сдвиг кнопок после проверки сети и ложный -неактивный стиль отдельных действий на переходном кадре. Кнопка «Онлайн-партии» -теперь присутствует с первого кадра на поддерживающей эту функцию платформе; -загрузка базы и завершение сетевой проверки не меняют состав панели. Действиям -назначены стабильные идентификаторы, чтобы предыдущий ответ соседнего разделителя -не определял оформление кнопки. Счётчик скачивания остаётся в подсказке и диалоге, -не расширяя панель по мере роста числа. - -При раннем открытии окна онлайн-партий текст объясняет проверку соединения; -при недоступности обеих платформ предлагается повторить её. Список платформ -по-прежнему содержит только ответившие сервисы. Доступность обновления уже -открытой онлайн-базы сохраняет прежнюю зависимость от результата проверки. -На главный экран индикатор ожидания не возвращается. - -## Выпуск 2.2.0 (2026-11-06) - -Владелец разрешил закоммитить изменения, слить ветку тренировки в `main`, отправить -в Forgejo и GitHub и выпустить сборки с обновлением сайта. Версия «2.2» оформляется -по принятому SemVer как `2.2.0`, тег `v2.2.0`. Тренировка дебюта в desktop сохраняет -пометку α; Android получает уже включённое открытие PGN из буфера с подтверждением. -GitHub публикуется существующим фильтром внутренних материалов; ТЗ тренажёра -также исключено. Отправка главной ветки и тегов атомарная, без перезаписи чужой -истории. Сайт получает номер и файлы выпуска из GitHub; новый текст на девяти -языках публикуется после готовности сборок. - -## Разметка PGN и собственные альтернативы после 2.2.0 (2026-11-06) - -Владелец подтвердил выпуск 2.2.0 в подготовленном виде и поручил следующую -доработку: значки ходов, авторские стрелки и отмеченные поля показываются в -тренировке как после ответа пользователя, так и при автоматической прокрутке. -Используется существующее оформление просмотра партии; обычный просмотр, -создание партий и анализ не изменяются. Пометки относятся к конкретному -показанному узлу PGN, а не к совпавшему FEN и не к уже выбранной следующей задаче. - -По новому указанию изучаются разные собственные варианты, поэтому прежнее -ограничение одним main-answer отменяется. Ключ знания остаётся `(профиль, FEN4, -UCI)`: разные ответы различаются, транспозиции одного ответа разделяют историю. -Другой ожидающий ответ из той же позиции получает собственный зачёт, исходная -цель остаётся в очереди. Уже повторённый или не запланированный активный ответ -репертуара не записывается как ошибка. Предпочтительный ход влияет только на -порядок; выключение ветки — отдельное действие. Контекст хранит реальный путь -PGN для точного выбора пометок, минимальная глубина графа остаётся отдельной метрикой. - -Отдельно запрошены уточнения: исключать ли собственные ветки с `?`/`??`/`?!` и -считать ли авторскую стрелку, раскрывающую ответ, подсказкой для SRS. До ответа -эти дополнительные политики не включены: оценки NAG сами не фильтруют ветки, -рисунки PGN сами не создают событий PREVIEWED. - -## Выпуск 2.3.0 (2026-11-06) - -Владелец поручил коммит, push, новый тег с минорным увеличением версии и выпуск -сборок. После 2.2.0 это версия 2.3.0, тег v2.3.0. В выпуск входят аннотации 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». «Выучено» по ядру — три верных самостоятельных ответа подряд, обычно за несколько дней; поэтому таблица показывает и «учится» (двухсегментная полоса, подсказка), а итог занятия — «Учится: +N» (2026-11-27). -- Из UI удалены выбор режима и порядка, шесть параметров контекста, дашборд с вкладками и графиками, отчёт Branches/Lines, режим «за оба цвета». Сохранённые значения остаются на диске, но не действуют; лимит `max_plies` снимается при загрузке; незавершённые сессии 2.x не возобновляются. Это заменяет UI-части решений 2026-11-04/05. -- Вторичные действия: «Повторить всё подряд», «Тренировать эту ветку», экран «Варианты». Редактирования ходов на доске в этом этапе нет. Строка ходов линии в занятии показывается по решению владельца 2026-11-27 (заменяет решение 03.11): одна бледная строка SAN с номерами до позиции на доске, без спрашиваемого хода и без отметок ошибок, обрезка слева, постоянная высота; место — между строкой дебюта и комментарием (блок C спецификации). -- Цвет задаётся при импорте/создании. При первом открытии раздела (файла библиотеки ещё нет) создаются два примера: Испанская партия (белые) и Найдорф (чёрные); удалённые примеры не возвращаются. -- Неверный ход на только что показанном новом ходе ошибкой не считается: «Не тот ход» ~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» с полосой «пройдено/закреплено»; слова «учится/выучено» заменены на «пройдено/закреплено». - -## Стартовые репертуары и тестовые окна (2026-11-27) - -- Владелец: примеры дебютов должны появляться и у обновившихся. Выбран вариант «выдавать недостающие один раз»: ключ каждого примера запоминается в `repertoire-starters.json`, удалённые не возвращаются. Заменяет правило 2.4.0 «только при первом открытии раздела». Пользователь 2.4.0, удаливший пример до обновления, получит его один раз — подтверждено владельцем 2026-11-27. -- Набор: Испанская партия и Ферзевый гамбит за белых, Найдорф и Треугольник (полуславянская) за чёрных. -- Визуальная приёмка этого раздела — на Full HD 1920×1080 (владелец). -- Тестовые окна приложения — только на невидимом мониторе Hyprland через `scripts/dev/headless-run.sh`, не на мониторах владельца (владелец выбрал вариант 2). -- Комментарии примеров — на русском для русского интерфейса и на английском для остальных (владелец, 2026-11-27). Следующий выпуск — 2.4.1; не выпускать, пока владелец не добавит задачи из бэклога (42, 43 и др.) и не скомандует выпуск. -- Задача 42, пакетная копия в новую базу (владелец, 2026-11-27): дублем считается только запись с тем же текстом PGN (пробелы и переносы не в счёт); версия партии с другими комментариями копируется; номера пропущенных — в итоге. Минимум: только desktop и только новая база; новая база встаёт в конец полки, вперёд — только по «Открыть». - -## Выпуск 2.5.0 (2026-11-27) - -Владелец поручил коммит, push в Forgejo и GitHub, тег v2.5 и новую сборку, обновить сайт. Ранее названный номер 2.4.1 заменён: в выпуске новые функции (задачи 27, 42, 43), поэтому минорное увеличение — 2.5.0, тег v2.5.0. В выпуск входят задачи 26, 27, 42, 43, 44, 45. - -## Пакетный анализ вручную выделенных партий (2026-11-27) - -Владелец расширил задачу 27 после выпуска 2.5.0: массив для общего анализа можно получить не только фильтром, но и существующим ручным выделением партий из задачи 42. Это отменяет прежнее согласованное ограничение «кнопка только по фильтру, без пункта для выделенных»; остальные правила задачи 27 сохраняются. - -- **Приоритет источника.** Если выделена хотя бы одна партия, существующая кнопка анализирует выделение; если выделения нет — отфильтрованный массив, как раньше. Отдельную вторую кнопку не добавляем. -- **Скрытые фильтром.** В анализ входят все выделенные партии, включая скрытые текущим фильтром: выделение по-прежнему переживает смену фильтра. Перед запуском явно показывается число выбранных партий и, если они есть, число скрытых текущим фильтром. -- **Лимит.** Для выделения действует тот же предел: 1–100 партий включительно. При большем числе кнопка неактивна и подсказка просит выбрать не больше 100; очистка выделения возвращает прежнее поведение по фильтру. -- **Без нового механизма.** Диалог, предупреждение о времени, кэш, проход Stockfish, прогресс, остановка/продолжение, итоговое окно и отметки `!!` используются общие. Создание новой базы из выбранных и исходные PGN не меняются. - -## Выпуск 2.5.1 (2026-11-28) - -Владелец явно выбрал увеличение последнего числа после 2.5.0: версия **2.5.1**, тег `v2.5.1`. В выпуск входит задача 46. Поручены отправка в Forgejo и GitHub и публикация сборок. - -## Android: простая подготовка к сопернику (2026-11-28) - -Владелец поручил мобильный сценарий задачи 48: выбрать соперника из базы или открытой партии и его цвет, показать доску цветом пользователя вниз (противоположным цвету соперника), продолжения стрелками и списком по частоте, число партий и победы/ничьи/поражения выбранного игрока. Ход разрешён и на доске, и касанием продолжения. Это разрешает **простую** подготовку на Android и не переносит настольный отчёт целиком; прежнее «на Android не делаем» задачи 19 остаётся в силе для его сложных разделов. - -Технические границы реализации, выбранные оркестратором в рамках этого простого сценария: точный вариант имени без склейки, одна выбранная сторона, транспозиции, только первое вхождение позиции в основную линию каждой партии, RAV не считаются сыгранными ходами, неизвестный `Result` отдельно от поражений. Никаких оценок движка, поиска ошибок, SRS и изменения исходных баз. - -## Android: ориентация доски подготовки — стороной пользователя (2026-11-29) - -Владелец уточнил: подготовка строится от его стороны против выбранного соперника. Поэтому соперник белыми означает чёрные внизу (`flipped = true`), соперник чёрными — белые внизу (`flipped = false`). Прежняя реализация с цветом соперника вниз была неверной интерпретацией и исправлена. Ручной переворот доски остаётся доступным; обе стартовые ориентации и ручной flip проверены на эмуляторе и приняты независимым ревью (`docs/qa/android-prep-orientation.md`). - -## Android: список игроков с плоскими строками (2026-11-29) - -Владелец выбрал улучшенный экран Players по варианту B+: плоские строки 72 dp вместо двух плашек White/Black у каждого игрока. Если ненулевой цвет один, касание строки сразу открывает подготовку этим цветом; если доступны оба, открывается короткий лист с двумя действиями по 64 dp и без дополнительного подтверждения. Нулевой цвет остаётся видимым текстом, но не отдельной disabled-кнопкой. Поиск, точные имена, счётчики и возврат в подготовку сохраняются. Проект — `docs/design/android-players-improvement.md`. По ремарке владельца 2026-11-29 лист озаглавлен «Подготовиться к %1$s» (без двоеточия), действия названы «Против белых» и «Против чёрных», чтобы цвет не читался как цвет самого пользователя (`docs/qa/android-color-sheet-wording.md`). - -## Выпуск 2.5.2 (2026-11-30) - -Владелец явно выбрал увеличение последнего числа после 2.5.1: версия **2.5.2**, тег `v2.5.2`. В выпуск входят задачи 29 и 48: кнопка анализа и навигация на экране Android-партии, простая подготовка к сопернику. Поручены commit и push в Forgejo и GitHub, Android-сборка для сайта, обновление сайта и RuStore. diff --git a/docs/design/android-opponent-prep.md b/docs/design/android-opponent-prep.md deleted file mode 100644 index e617f17..0000000 --- a/docs/design/android-opponent-prep.md +++ /dev/null @@ -1,332 +0,0 @@ -# Задача 48. Android: простая подготовка к сопернику по базе - -Дизайнер, 2026-11-28, ветка `feature/android-opponent-prep`. Документ описывает **MVP для Android**, а не перенос настольного отчёта. Код не изменялся. - -## 1. Задача и границы - -**Задача экрана — за один взгляд понять, как выбранный человек играет из текущей позиции: доска и ход важнее всего, затем частые продолжения, число партий и результаты именно этого человека.** - -В MVP есть два входа в один экран исследования: - -1. **Из открытой партии** — соперник и позиция уже известны; остаётся выбрать, чей репертуар смотреть: белых или чёрных. -2. **Из базы** — через экран игроков, где видны общее число партий и отдельные входы «белыми» / «чёрными» с числом партий. - -На экране исследования: - -- доска изначально повёрнута **цветом пользователя вниз — противоположным цвету соперника**; -- ход можно сделать на доске, касанием стрелки частого продолжения или касанием строки продолжения; -- продолжения отсортированы по числу партий; у каждого видны число, доля и W/D/L выбранного игрока; -- ◀/▶, удержание для перехода к границам и ручной переворот работают как в текущей партии; -- всё происходит локально и только для чтения: партия, PGN и база не меняются. - -**Не входит:** Stockfish и оценки, поиск ошибок, вкладки «Дебюты/Ошибки», ECO и названия вариантов, фильтры периода/силы, список партий узла, экспорт досье, сохранённые подготовки, онлайн-explorer, desktop-отчёт и новая система повторений. Связь с задачей 38 — только техническая, через чтение базы и позиции; отдельного позиционного поиска и его фильтров здесь нет. - -## 2. Что проверено в реальных материалах - -Просмотрены сами изображения: - -- приложенный владельцем монтаж `docs/screenshots/android.jpg`, **1920×1080**: список партий, партия, лист игры и список людей; -- `website/shots/raw/phone/01-home.png`, `02-games.png`, `03-game.png`, `04-engine.png`, каждый **1080×2400**; -- реальный кадр текущей панели после `a005185` — `/tmp/opencode/29-final.png`, **1080×2400**; -- `designExample/reference.png` — доска и таблица продолжений ChessBase; -- `designExample/доска.png` и `designExample/панель ходов с ответвлениями.png` — ориентация, координаты и чтение ходов; -- настольный `docs/screenshots/prep-openings.jpg` использован только как подтверждение смысла цвета и статистики, не как макет для телефона. - -Снимки телефона относятся к AVD **420 dpi**, то есть density **2,625**, а не ×3: 1080×2400 px соответствует примерно **411×914 dp**. Поэтому проектные размеры ниже даны в dp/sp; отдельно проверяется эталон **360×800 dp**. - -По снимкам и коду текущего `a005185` подтверждено: - -- доска в портрете занимает всю ширину, без полей и скругления; плашки игроков — 36 dp; -- строка партии — 80 dp, поля списка — 16 dp, разделитель — 1 dp `outlineVariant`; -- нижняя панель партии — **72 dp**, поверхность `surfaceContainer`; после `a005185` ◀/▶ делают один шаг, удержание идёт в начало/конец без автоповтора; -- `Board` уже умеет ориентацию, последний ход, стрелки, tap-tap и drag через `BoardInput`; сами стрелки сейчас только рисуются и отдельного hit testing не имеют; -- `GamesScreen` имеет поиск и постранично читаемый `LazyColumn`; `Navigation.kt` сохраняет состояние экранов в стеке; -- в `mobile-api` пока нет Android-экрана игроков и готового API подготовки: его нужно спроектировать, а не выдавать настольный `prep` за уже доступный на телефоне. - -## 3. Пользовательские пути и сохранение контекста - -### 3.1. Из партии: «Кого изучить — белых или чёрных?» - -Путь: **Партия → ⋮ → «Подготовиться к сопернику…» → строка игрока/цвета → исследование**. - -Меню открывает небольшой `ModalBottomSheet`, а не добавляет два почти одинаковых пункта в основное меню: - -```text -┌────────────────────────────────────┐ -│ ─── │ -│ Подготовка к сопернику │ -│ ○ Morphy, Paul │ -│ Белые │ 64 dp, вся строка — кнопка -│ ● Duke Karl / Count Isouard │ -│ Чёрные │ 64 dp -└────────────────────────────────────┘ -``` - -- Имя — `bodyLarge`, цвет — `bodyMedium` `onSurfaceVariant`; слева существующий `SideDisc` 12 dp. Полное имя доступно TalkBack, визуально — по правилу `PlayerName`. -- Одно касание сразу открывает исследование. Дополнительная кнопка «Открыть» не нужна: выбор строки уже однозначен. -- Если имя одной стороны пусто или `?`, показывается только строка другой стороны. Если имена совпадают, остаются обе строки — репертуары за разные цвета различаются. -- Пункт доступен только у партии, открытой из существующей базы. У новой партии нет источника статистики, поэтому пункта нет; у активной игры с компьютером меню и так отдельное. -- Во время предпросмотра PV пункт неактивен; вторая строка пункта — «Сначала закройте линию движка». Нельзя молча подменить позицию партии позицией PV. Если на пути текущего узла есть учебный null move `--`, вторая строка — «Поиск после учебного -- недоступен»: после него нельзя честно сопоставить линию с реально сыгранными партиями. - -**Стартовая позиция — текущий реальный узел партии**, включая вариант и исходный FEN, но не PV. В исследование передаётся путь от начала этой партии до текущего узла, поэтому ◀ позволяет пройти назад по уже виденной линии. Сама партия не продолжается и не редактируется. - -Возврат системной «Назад» или ← восстанавливает партию на том же узле, с прежними нотацией, прокруткой, ориентацией и несохранёнными правками. Диалога «сохранить?» у исследования нет — оно ничего не изменило. - -Почему этот вход нужен наряду со списком игроков: человек уже нашёл партию соперника и конкретную позицию; повторный поиск имени и переход в начальную позицию потеряли бы главный контекст. - -### 3.2. Из базы: «Найти человека и сразу выбрать его цвет» - -Путь: **Партии базы → значок «Игроки» → кнопка цвета в строке игрока → исследование с начальной позиции**. - -В `TopAppBar` экрана «Партии» добавляется `IconButton` с `Icons.Rounded.Groups` и описанием **«Игроки»**. Значок ставится перед поиском; поиск остаётся на привычном месте. У онлайн-базы после них остаётся существующее скачивание/обновление. Каждая цель — 48×48 dp, длинное имя базы уступает место и обрезается многоточием. - -Отдельный видимый значок выбран вместо пункта меню, которого сейчас у «Партий» нет: это второй равноправный вход в задачу, а не скрытая команда. На полку баз новая кнопка не добавляется — сначала нужен источник, то есть конкретная база. - -Стек: - -```text -Базы → Партии → Игроки → Подготовка - └───── Партия ────→ Подготовка -``` - -«Назад» из игроков возвращает в ту же выдачу партий с поиском и прокруткой. Возврат из подготовки — в игроков с прежними запросом и прокруткой. Стартовая позиция из этого входа — обычная начальная; никакие поиск/фильтры списка партий не переносятся скрыто в статистику. - -## 4. Экран «Игроки» - -### 4.1. Задача и компоновка - -**Задача экрана — выбрать точное написание игрока и цвет одним действием, видя объём данных по каждому цвету.** - -```text -┌────────────────────────────────────┐ -│ ← Игроки ⌕ │ -│ Alekhine │ -│ Alekhine, Alexander 266 партий│ -│ [○ Белыми · 153] [● Чёрными · 113] │ 48 -│────────────────────────────────────│ -│ Anderssen, Adolf 2 партии│ -│ [○ Белыми · 2] [● Чёрными · 0] │ -└────────────────────────────────────┘ -``` - -- Заголовок — «Игроки», вторая строка — имя текущей базы. Справа поиск с существующим поведением `GamesScreen`: поле вместо заголовка, клавиатура, ✕, задержка 250 мс. Подсказка — **«Имя игрока»**. -- Список по умолчанию — по алфавиту через `Collator`, без отдельной кнопки сортировки. Поиск фильтрует по подстроке без учёта регистра. Это не поиск похожих имён и не объединение людей. -- Строки — плоские, как список партий, **без карточек**. Разделитель 1 dp `outlineVariant` находится внутри строки и не добавляет высоту. -- Обычная высота строки — **88 dp**: 8 сверху + имя/счёт 24 + 4 + кнопки 48 + 4 снизу. При крупном шрифте используется `heightIn(min = 88.dp)` и строка растёт. Если две подписи цвета больше не помещаются рядом, кнопки становятся одна над другой на всю ширину, каждая остаётся не ниже 48 dp; название цвета не обрезается. -- Поля — 16 dp. Имя — `bodyLarge`, общее число партий справа — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`; имя сокращается первым. Полное имя и полное число озвучиваются. -- Между цветовыми кнопками — 8 dp. На ширине 360 dp каждая занимает **160 dp**: `(360 − 32 − 8) / 2`. На 320 dp — 140 dp, на 280 dp — 120 dp. Подпись одной строкой, сначала сокращается число по `short_count`, полное остаётся в описании. -- Кнопка — нейтральная `surfaceContainerLow`, скругление 8 dp, `SideDisc` 12 + 8 + текст `labelLarge`. Никаких двух ярких цветовых плашек: круг и слова уже различают стороны. -- **Вся кнопка 48 dp — действие.** Нажатие на имя ничего не открывает, поэтому нет конкурирующего третьего сценария. -- Нулевой цвет остаётся видимым, но кнопка неактивна. Это честная информация «партий этим цветом нет», а не причина переставлять кнопки. - -Ключ игрока — точное имя из тега после `trim`, без нечёткого слияния. `Alekhine`, `Alekhine, Alexander` и другое написание остаются разными строками. Пустые и `?` в список не попадают. Автоматических догадок, кто из тегов является учебным названием, MVP не делает. Общее число — число различных записей; счётчики цветов считаются отдельно. Если имя стоит на обеих сторонах одной партии, общее число не складывает её дважды, а результат в исследовании зависит от выбранной стороны. - -### 4.2. Состояния списка - -| Состояние | Поведение | -|---|---| -| Первое чтение | Верхняя панель уже видна; в области списка — индикатор и «Читаю игроков…». Нули вместо неизвестных счётчиков не показываются | -| Подгрузка страниц | Заглушки тех же 88 dp, разделители остаются; список не скачет | -| Поиск | Старый результат другой строки запроса не выдаётся за новый; показаны заглушки/индикатор, затем результат | -| Нет именованных игроков | «В этой базе нет именованных игроков» и кнопка «К партиям» | -| Ничего не найдено | «Игрок не найден» + «Сбросить поиск» | -| Ошибка базы/индекса | «Не удалось прочитать игроков» + существующее `openProblem`, кнопка «Повторить»; технический текст не подменяет причину | -| Большая база | Индекс и поиск в фоне, `LazyColumn`, чтение страницами; уход отменяет незавершённый запрос | -| Возврат | Запрос, выдача и прокрутка сохранены; выбранный ранее игрок не подсвечивается как «текущая позиция» — это другое состояние | - -## 5. Экран исследования - -### 5.1. Портрет 360×800 dp - -Плашки двух игроков из экрана партии здесь не повторяются: выбранный человек и цвет уже находятся в заголовке. Это освобождает 72 dp под продолжения, не уменьшая доску. - -```text -┌────────────────────────────────────┐ 24, системная строка -│ ← Alekhine, Alexander │ 64 -│ Чёрными · Alekhine │ выбранный цвет · база -├────────────────────────────────────┤ -│ │ -│ ДОСКА 360 × 360 │ чёрные внизу -│ до 3 стрелок продолжений │ -│ │ -├────────────────────────────────────┤ -│ Соперник играет · 1.e4 113 партий │ 32 -│ 1…c5 79/113 · 70 % │ 56 -│ +55 =14 −10 · W/D/L 70/18/13 % │ -│────────────────────────────────────│ -│ 1…e5 20/113 · 18 % │ 56 -│ +13 =4 −3 · W/D/L 65/20/15 % │ -│────────────────────────────────────│ -│ 1…Nf6 8/113 · 7 % │ -│ +4 =3 −1 · W/D/L 50/38/13 % │ -│ … прокручивается только список … │ -├────────────────────────────────────┤ -│ ⇅ ◀ ▶ │ 72 -└────────────────────────────────────┘ 24, системная навигация -``` - -Верхняя панель: - -- ← с описанием «К партии» или «К игрокам» по источнику; -- имя игрока — `titleMedium`, одна строка, полное имя в TalkBack; -- вторая строка — **цвет словом + имя базы**, `bodyMedium` `onSurfaceVariant`; -- новых ⋮, движка, разбора и настроек в этой панели нет. - -Строка контекста 32 dp явно называет, чьи продолжения показаны: - -- на ходе выбранного человека — **«Соперник играет»**; -- на ходе другой стороны — **«Его оппоненты играют»**. - -Затем идёт «начало» либо «после {SAN с номером}», справа — число партий текущей позиции M. Левая часть обрезается, M остаётся. При неизвестном счётчике стоит `…`, не `0`. Для TalkBack добавляется точная сторона «ход белых/чёрных»: по FEN её нельзя выводить из чётности хода. Подпись «Его оппоненты играют» не даёт принять первый ход белых за выбор соперника чёрными. - -### 5.2. Строка продолжения и смысл чисел - -Обычная высота — **56 dp**, поля 16 dp, две строки: - -1. SAN по настройке записи ходов, 17 sp, слева; справа **`N/M · P %`** `bodyMedium.merge(Tabular)`, где M — партии текущей позиции, N — партии с этим продолжением. -2. **`+W =D −L · W/D/L wp/dp/lp %`**, `labelSmall.merge(Tabular)`, `onSurfaceVariant`: слева исходные счётчики, справа их доли в том же порядке. Если у продолжения есть партии с неизвестным итогом, перед W/D/L добавляется `ещё U`. - -Вся строка — `Role.Button` с обычным ripple. Разделитель 1 dp входит в её высоту. Никаких карточек, графиков, рейтинговых цветов и сортировки по столбцам. - -- Порядок: **N по убыванию**, при равенстве — по SAN. Все продолжения остаются в `LazyColumn`; редкие не скрываются. -- `P = N / M × 100 %`, а не доля от начального репертуара. Существующий ход с долей меньше 1 % показывается как `<1 %`, не `0 %`. Одновременные `N/M` не дают принять процент на одной партии за устойчивую закономерность. -- В статистику входят **только реально сыгранные основные линии**. RAV в базе не считается ходом соперника; позиция, взятая из RAV открытой партии, при этом разрешена как отправная. -- Транспозиции объединяются по позиции. Партия учитывается один раз, по **первому вхождению позиции в её основную линию**; другой ход после повторного вхождения не добавляется. -- Если сумма долей меньше 100 %, после продолжений обычными недоступными строками показываются **«Здесь закончились: N»** и, при учебном/неподдерживаемом следующем ходе, **«Нет обычного продолжения: N»**. Должно выполняться `ΣN(move) + ended + noNormalContinuation = M`. -- Неизвестный результат `*` не становится поражением. Он входит в N, M и частоту, но не в знаменатель W/D/L: `known = W + D + L`, каждая доля делится на `known`. Если известных результатов нет, вместо всех трёх долей — `—`. Доли округляются независимо и не подгоняются до суммы ровно 100 %. -- Если нечитаемые записи повлияли на выборку, отдельная служебная строка — **«Пропущено нечитаемых: N»**. Ошибка чтения не маскируется под ноль совпадений. -- При нехватке места вторая строка переносится, а высота растёт через `heightIn(min = 56.dp)`. При крупном шрифте первая строка использует компактное `N/M · P %`. Горизонтальной прокрутки нет. - -**W/D/L всегда относится к выбранному человеку, а не к стороне, которая сейчас ходит.** На ходе его соперников список показывает их продолжения, но победы/ничьи/поражения по-прежнему считаются для выбранного человека. Например, для выбранных чёрных `0-1` — W, `1-0` — L. Это результат после фактически сыгранного продолжения, а не вероятность победы или оценка качества хода. Правило должно быть общим для API, отображения и TalkBack. - -### 5.3. Доска и стрелки - -- Начальная ориентация: соперник белыми — чёрные внизу (`flipped = true`), соперник чёрными — белые внизу (`flipped = false`). Она **не зависит от того, чей сейчас ход**. Уточнение владельца 2026-11-29 заменяет прежнюю неверную ориентацию цветом соперника вниз. -- ⇅ позволяет вручную перевернуть доску; выбор сохраняется при навигации по позициям и повороте телефона, но новый вход снова начинает с выбранного цвета. -- После готовых данных рисуются **до трёх самых частых различных направлений** из списка. Не все сразу: десяток пересекающихся стрелок закрыл бы фигуры и сделал hit testing случайным; полный выбор остаётся в списке. Цвет и геометрия — существующие `BoardArrow`/`EngineArrow`: первый вес 1,0 и alpha 0,63, следующие — 0,85/0,45 и 0,70/0,35. Новых цветовых легенд нет; порядок дополнительно виден в списке. -- Если разные UCI имеют одинаковые from/to (например, превращения), рисуется одна стрелка, а не несколько одинаковых поверх. -- Касание стрелки делает соответствующий ход **один раз**. Область — не только тонкий видимый штрих: используется невидимый коридор вокруг shaft/head и зона не менее 48 dp у наконечника, ограниченная доской. -- Касание наконечника и касание строки передают **точный UCI продолжения**, включая недопревращение. Обычный ручной ввод пешки сохраняет текущее правило приложения — по умолчанию ферзь. -- Если коридоры/наконечники нескольких ходов пересекаются в точке касания, нельзя молча выбирать верхнюю стрелку: открывается короткий лист **«Выберите ход»** только с конфликтующими SAN. Если from/to совпадают, лист обязателен. После выбора делается один ход. -- При уже выбранной фигуре обычный `BoardInput` имеет приоритет над shortcut стрелки. Drag не считается касанием стрелки. Реализация должна использовать **один распознаватель жестов** для доски и стрелок, а не два конкурирующих `pointerInput`. -- Стрелки исчезают сразу при смене позиции, загрузке, ошибке и пустом результате. Статистика прежней позиции не остаётся ни на доске, ни в списке. -- На доске также работают существующие tap-tap и drag любого легального хода, даже если его нет в базе. Тогда следующая позиция может честно показать «0 партий»; это не ошибка и не запрет продолжать. - -До реализации нужен небольшой UI-прототип именно hit testing: повёрнутая доска, пересекающиеся стрелки, ширина 280 dp и drag. Существующий `Board` доказывает отрисовку и ввод фигур, но не касаемость стрелок. - -### 5.4. Линия, ◀/▶ и нижняя панель - -Нижняя панель остаётся **72 dp** и использует текущий `BarButton` из `a005185`: - -| ⇅ | ◀ | ▶ | -|---|---|---| -| 72 dp | оставшаяся ширина поровну | оставшаяся ширина поровну | - -На 360 dp это 72 / 144 / 144, на 320 dp — 72 / 124 / 124, на 280 dp — 72 / 104 / 104. Кнопки не уже 48 dp и занимают всю высоту панели; значки ◀/▶ — 32 dp. - -- Короткое ◀/▶ — один полуход по исследуемой линии. Удержание ◀ — в её начало, ▶ — в конец, один раз и без предварительного шага/автоповтора. -- После ◀ кнопка ▶ возвращается **тем же продолжением**, а не самым частым. -- Новый ход после возврата назад отбрасывает только будущий хвост временной линии. Это не удаление варианта PGN и не требует подтверждения. -- Длинное нажатие имеет те же accessibility custom actions «В начало/конец линии». Звук и вибрация — только после совершённого хода и по общим настройкам. -- Недоступные ◀/▶ остаются на месте и не меняют геометрию. - -## 6. Загрузка, пусто, ошибка и гонки - -Область под доской имеет постоянную геометрию: доска, верхняя и нижняя панели не двигаются при смене данных. Меняется только содержимое прокручиваемой области. - -| Состояние | Что видно | -|---|---| -| Первый вход | Сразу доска правильной ориентации и текущий путь; в области продолжений — место тех же строк и индикатор | -| Запрос короче 300 мс | Результат появляется без промежуточного мигания | -| Запрос дольше 300 мс | «Считаю продолжения…» в области списка; фиксированная полоса 2 dp над ним. Прежние SAN, стрелки и W/D/L уже удалены | -| Ход во время запроса | Доска и путь меняются сразу; запрос прежней позиции отменяется/игнорируется по поколению, новый начинается независимо | -| Позиция не встречалась | «В партиях {name} этой позиции нет» и подсказка «Можно продолжить на доске или вернуться ◀»; стрелок нет | -| Продолжений нет, партии закончились | «Все партии здесь закончились»; W/D/L не выдумывается | -| Ошибка текущего запроса | Доска и путь остаются; в области списка «Не удалось посчитать продолжения» + причина + «Повторить». Повтор относится к видимой позиции | -| Не хватает памяти для индекса | Отдельный текст «Недостаточно памяти для поиска по этой базе», не «позиция не найдена»; доступны «Повторить» и возврат | -| База исчезла/изменилась | Не показывать кэш как актуальные данные; та же ошибка с `openProblem`, возврат по ← доступен | -| Много продолжений | Прокручивается только список; доска, контекст и кнопки закреплены | -| Выход из исследования | Временная линия исчезает без вопроса; исходный экран сохраняется | -| Поворот/возврат из фона | Игрок, цвет, путь, курсор, ориентация и прокрутка списка восстанавливаются; ответ старого поколения не применяется | - -Для каждого запроса ключ должен включать базу и её версию, точное имя, цвет и текущую позицию/историю, необходимую ядру. Ответ применяется только если ключ всё ещё видим на экране. - -## 7. Альбомная ориентация, узкие экраны и HiDPI - -- **Портрет:** доска `fillMaxWidth().aspectRatio(1f)`, как в партии. На очень низком экране она не уменьшается; список получает остаток и прокручивается. -- **Альбомная ориентация/широкое окно:** верхняя панель общая; слева квадратная доска на всю доступную высоту, справа — строка контекста, `LazyColumn` с весом 1 и нижняя панель 72 dp. Системные insets учитываются отдельно, доска не пересекается с навигацией. -- **Планшетный портрет:** доска ограничена 480 dp и центрируется; строка контекста и список имеют ту же ширину, а не растягиваются на весь экран. Пустые поля не заполняются декоративными карточками. -- **280/320 dp:** те же три кнопки внизу, две цветовые кнопки у игрока и двухстрочные продолжения; ни одна цель не уже 48 dp, горизонтальной прокрутки нет. -- **Крупный шрифт:** строка контекста имеет `heightIn(min = 32.dp)` и может вырасти, не обрезая «Соперник играет» / «Его оппоненты играют». Строки продолжений растут, `N/M` и частота остаются в первой строке, исходные +/=/− и W/D/L переносятся на следующие. Числа не исчезают и не обрезаются. У игрока кнопки цвета при необходимости становятся вертикальными по §4.1. -- **HiDPI:** использовать существующие векторные Material icons, dp/sp, `Pieces` с растровым кэшем фактического размера. Новых растровых ресурсов не требуется. Обязательная проверка — реальный 420 dpi, без вывода «×3» из размеров PNG. - -## 8. Доступность, клавиатура и подсказки - -### 8.1. TalkBack - -- **Игрок:** имя и общее число — один информационный узел. Каждая цветовая кнопка отдельно: «{name}, белыми, 153 партии. Подготовиться» / «… чёрными, нет партий, неактивно». Круг не озвучивается отдельно. -- **Доска:** один узел с позицией и ориентацией: «Доска, позиция после 1.e4. Чёрные выбранного игрока внизу». Не создавать 64 отдельных фокуса клеток. -- У доски есть custom actions для видимых стрелок: «Сыграть 1…c5, 79 партий, 70 процентов». Полный список продолжений всегда доступен ниже, поэтому сценарий не зависит от жеста по Canvas. -- **Продолжение:** одна кнопка: «1…c5. 79 из 113 партий, 70 процентов. Результаты Alekhine, Alexander: 55 побед, 14 ничьих, 10 поражений; 70, 18 и 13 процентов. Сыграть». При неизвестных исходах добавляется их число и пояснение, что они не входят в знаменатель процентов. -- **Контекст:** «Соперник играет, ход чёрных, после 1.e4, 113 партий» либо «Его оппоненты играют, ход белых…» объявляется politely после готовности, один раз на позицию. Прогресс не озвучивается на каждое обновление; ошибка и пустой результат объявляются один раз. -- После активации строки фокус не остаётся на удалённом элементе: он переводится на строку контекста новой позиции. При быстром листании не накапливается очередь объявлений. -- ◀/▶ сохраняют текущие полные описания и custom actions границ. Неактивность передаётся семантически, не только серым. - -### 8.2. Аппаратная клавиатура и D-pad - -| Клавиша | Действие | -|---|---| -| Tab / Shift+Tab, D-pad | Стандартный порядок фокуса: ← → доступные custom actions доски → строки продолжений → ⇅ → ◀ → ▶ | -| Enter / Space / DPAD_CENTER | Активировать сфокусированную строку или кнопку, один раз | -| Android Back / Esc | Сначала закрыть лист/меню, затем покинуть текущий экран | -| Длительное действие TalkBack | Границы линии через custom actions, как на сенсорном экране | - -Глобальных буквенных сокращений и перехвата ←/→ в списке нет: они нужны для перемещения фокуса. Произвольный ход по 64 клеткам с аппаратной клавиатуры в MVP не добавляется; все продолжения базы и навигация доступны списком. Это ограничение не должно маскироваться под полную клавиатурную поддержку доски. - -Видимый фокус — рамка 2 dp `primary` вокруг кнопки/строки, а не только смена tint. Hover-tooltip: «Игроки», «Перевернуть доску», «Предыдущий ход. Удержание — в начало», «Следующий ход. Удержание — в конец». На ◀/▶ сенсорное удержание выполняет переход, а не показывает tooltip. - -## 9. Требования разработчику - -1. Добавить в существующий Nav3 два сохраняемых назначения: «Игроки базы» и «Подготовка». Не делать подготовку новым разделом верхнего уровня. Не передавать всё PGN-дерево в `NavKey`; использовать стабильные идентификаторы и сохраняемую сессию исследования. -2. В `GamesScreen` вынести `onPlayers`; в `GameScreen` — `onPrepare(player, white)`. Лист выбора цвета остаётся локальным состоянием партии. Использовать существующий стек, не пересоздавать исходный экран при возврате. -3. Компоненты: `PlayersScreen`, плоская `PlayerPrepRow`, `PrepScreen`, `ContinuationRow`, общий блок `PrepControls`. Переиспользовать `Board`, `BoardInput`, `Pieces`, `SideDisc`, `PlayerName`, `groupDigits`, `displaySan`, `openProblem` и текущий `BarButton`; не копировать жест long press второй реализацией. -4. Нужен новый локальный API, например модели `PlayerSummary(name,total,whiteGames,blackGames)`, `PrepPosition(games,continuations,endedHere,noNormalContinuation,skipped,unknownResults)`, `PrepContinuation(uci,san,games,wins,draws,losses,unknown)`. Названия — ориентир для разработчика, не утверждение о существующем UniFFI. -5. Счётчики строить только по выбранной базе и точному `(name,color)`. Агрегация в Rust — **main line, first occurrence**, с транспозициями и без RAV в статистике; существующий смешанный `MoveStat.tally` для этого не подходит. Частота — от партий текущей позиции; W/D/L — от финального результата выбранного игрока на ходе любой стороны. Не запускать Stockfish и не читать настольный отчёт об ошибках. -6. Чтение игроков и позиций — вне UI-потока, со страницами, отменой и защитой от поздних ответов. Большая база не собирается в память целиком ради списка. Исходные файлы открываются только на чтение; тест — SHA-256/mtime до и после. -7. Путь исследования отделён от `GameSession` партии. Касание строки/стрелки и обычный ввод дают один UCI и один переход. Для недопревращений не заменять UCI продолжения ходом по умолчанию. -8. Доработать `Board` одним gesture resolver: координаты hit regions стрелок вычисляются тем же преобразованием `flipped`, что их отрисовка. Проверить конфликты с выбором фигуры, drag, краями доски и системным «назад». -9. При каждом новом запросе сразу очищать старые стрелки/статистику. Никакого «пока новое считается, покажем прежнее». -10. Все видимые строки и описания — ресурсы на всех девяти уже поддерживаемых языках; числа партий — через plurals. W/D/L можно оставить международным сокращением, но TalkBack обязан произносить локализованные «победы/ничьи/поражения». -11. Compose-тесты: две цветовые цели игрока, disabled при нуле, одна активация продолжения, конфликт одинаковых from/to, flip-hit mapping, ◀/▶ и custom actions, отсутствие фокуса на исчезнувшей строке, стабильные минимальные размеры. -12. Не добавлять сохранение, undo, пункты анализа, список партий или фильтры «на будущее» в этом MVP. - -## 10. Независимой проверке и тестировщику - -Визуальную приёмку выполняет **отдельный ревьюер, не автор макета и не автор реализации**. Он запускает реальное приложение в изолированных настройках и прикладывает снимки; чтения Kotlin и Compose preview недостаточно. - -### 10.1. Обязательные сценарии и доказательства - -1. **Сравнение существующего и нового:** текущие «Партии» и «Партия» из той же сборки, затем «Игроки» и «Подготовка». Сверить фон, `TopAppBar`, поля 16 dp, доску, нижние 72 dp, иконки и типографику. На реальном AVD 1080×2400/420 dpi указать фактические dp, а не называть его 360×800. -2. **Оба входа:** партия → лист White/Black → текущая позиция; база → игроки → цвет → начальная позиция. Показать белые внизу в одном случае и чёрные внизу в другом. Возврат — к прежнему узлу/прокрутке. -3. **Заполненная подготовка:** минимум четыре продолжения, разные N и W/D/L, до трёх стрелок. Проверить выравнивание SAN, `N/M · %`, второй строки +/=/− и W/D/L и отсутствие карточек. -4. **Последовательность без скачков:** загрузка → заполнено → ход стрелкой → ход строкой → ◀ → ▶ → позиция без партий → ошибка → «Повторить». На каждом кадре зафиксировать координаты доски, строки контекста и нижней панели. Изменение высоты допустимо только при переносе текста/смене ориентации по явному условию. -5. **Пустые состояния:** нет игроков, поиск игрока без результата, нулевой цвет, ноль партий в позиции, все партии закончились. Нули не должны мелькать во время загрузки. -6. **Узкое и крупное:** 320 и 280 dp, font scale 1,3 и 2,0: обе цветовые кнопки, три нижние кнопки и W/D/L не обрезаны; строки растут без горизонтальной прокрутки. -7. **Альбомная ориентация:** доска слева, продолжения справа, панель 72 dp; системные панели ничего не перекрывают. Светлую тему проверять отдельно только если добавятся новые цвета — по текущему макету новых ролей нет. -8. **HiDPI:** чёткие SVG-фигуры, Material icons, круги сторон, стрелки и текст на 420 dpi. Снимки подписать файлом, размером px, density, ориентацией и состоянием данных. - -Вердикт «ровно» без снимков не принимается. Дефект записывать как: экран/состояние, ожидаемая и фактическая координата или выравнивание, шаги воспроизведения, файл снимка. - -### 10.2. Функциональная матрица - -- Точные имена и цвета: одинаковое имя за оба цвета, разные написания, пусто/`?`, нулевой цвет, длинное имя. -- Текущий узел и FEN из партии; начальная позиция из базы; вариант партии; PV и путь после учебного `--` не используются. Старт чёрными и `fullmove=0` определяют сторону по FEN, не по чётности ply. -- Стрелка, строка, tap-tap и drag дают один и тот же ход; рокировка, взятие, превращение и недопревращение; flip не меняет UCI. -- Пересекающиеся стрелки и одинаковые from/to не делают произвольный ход. Двойное касание не создаёт два хода. -- ◀/▶ по одному полуходу, удержание без предварительного шага и автоповтора; возврат тем же child; новый ход отсекает только временный хвост. -- Частота `N/M` от текущего узла, сортировка по N, `<1 %`, «закончились здесь», `noNormalContinuation`, неизвестный результат, исходные +/=/− и W/D/L выбранного игрока на ходе обеих сторон. Отдельно проверить белых и чёрных. Контрольный fixture: у соперника чёрными `0-1, 0-1, 1-0, *` → `+2 =0 −1 · ещё 1 · W/D/L 67/0/33 %`; зеркальный пример белыми даёт те же доли. -- Две транспозиции дают одинаковую выборку; повтор позиции учитывается один раз; RAV-only запись не входит, основная линия с RAV добавляет только реальный следующий ход. Проверить равенство `ΣN + ended + noNormalContinuation = M`. -- Гонка A → B → A: ответ первого A не применяется к последнему A без совпадения полного ключа/поколения; ответ B никогда не появляется на A. -- Исходная партия с несохранёнными правками возвращается как была; PGN и база не изменились. Новых записей в «Мои базы» не появляется. -- TalkBack: полные описания, disabled, custom actions стрелок и границ, отсутствие прогресс-спама, фокус после исчезновения строки. Аппаратная клавиатура — по §8.2, без заявления произвольного хода по клеткам. -- Большая база: прокрутка игроков и продолжений, смена запроса во время чтения, уход с экрана, повтор после ошибки, отсутствие блокировки UI. diff --git a/docs/design/android-players-improvement.md b/docs/design/android-players-improvement.md deleted file mode 100644 index d5b6510..0000000 --- a/docs/design/android-players-improvement.md +++ /dev/null @@ -1,211 +0,0 @@ -# Задача 48. Android: улучшение экрана «Игроки» - -Дизайнер, 2026-11-29. Документ предлагает следующий MVP-шаг после уже реализованного экрана. **Production-код, ресурсы и другие документы не изменялись.** Это не отчёт о визуальной приёмке и не исправление падения поиска. - -## 1. Задача и приоритет - -**Задача экрана — быстро найти точное имя и начать подготовку за нужный цвет, не заставляя человека читать по две одинаковые кнопки у каждого игрока.** - -Приоритеты: - -1. точное имя и понятное следующее действие; -2. число партий по каждому цвету, включая честный ноль; -3. одно касание там, где существует только один возможный цвет, и отсутствие отдельного подтверждения «Открыть»; -4. плоский мобильный список, поиск и прокрутка сотен имён — не таблица и не досье. - -Общее число партий остаётся полезным контекстом, но не должно отнимать место у имени и цветов. Поиск похожих имён, объединение написаний, аватары, рейтинги, список партий игрока и досье не добавляются. - -## 2. Что проверено в материалах - -### 2.1. Текущая реализация - -Прочитаны `docs/design/android-opponent-prep.md` §4 и актуальный `PlayersScreen.kt`. - -Сейчас `PlayerPrepRow` действительно состоит из: - -- имени и общего счётчика; -- двух отдельных кнопок высотой не менее 48 dp; -- нейтральных плашек `surfaceContainerLow` со скруглением 8 dp; -- disabled-кнопки при нулевом цвете; -- обычной высоты 88 dp и трёх accessibility-узлов на человека: информация, White, Black. - -Это понятная и быстрая схема: цвет выбирается сразу, одним касанием. Её цена — повторение двух плашек и подписей в каждой строке, а также визуальное присутствие неактивных действий там, где у человека есть партии только одним цветом. - -`/tmp/opencode/qa48-search-crash/players.xml` существует и прочитан как **UI Automator XML, а не PNG**. На AVD 1080×2400, 420 dpi он подтверждает: - -- шаг обычных строк 231 px = 88 dp; -- цветовые цели 126 px = 48 dp; -- поля 42 px = 16 dp; -- у Alekhine две доступные кнопки, у Anderssen — White доступна, Black с нулём disabled; -- имя/счёт и обе цветовые кнопки являются отдельными semantic nodes. - -Также прочитаны `games.xml` и `logcat.txt`. Падение — отдельный `NullPointerException` из-за чтения `players!!` старым `LazyColumn` при смене запроса. Новая компоновка сама по себе этот дефект не исправляет и не должна подменять его regression-фикс. - -**Ограничение evidence:** актуального PNG Players в `/tmp/opencode/qa48-search-crash/` нет; прежний каталог `/tmp/opencode/prep48` отсутствует. Поэтому утверждения о текущей геометрии опираются на XML и Kotlin, а не на несуществующий новый снимок. Ниже — проектное сравнение, не повторная визуальная приёмка старого экрана. - -### 2.2. Визуальная система продукта - -Инструментом просмотра изображений посмотрены сами изображения: - -- `docs/screenshots/android.jpg`, 1920×1080 — монтаж Android-списков, партии и листов; -- `website/shots/raw/phone/01-home.png`, `02-games.png`, `03-game.png`, каждый 1080×2400; -- `designExample/reference.png`, `designExample/доска.png`, `designExample/панель ходов с ответвлениями.png` — референсы смысла доски и нотации, не макет мобильного списка. - -Для Players нужно сохранить уже существующий язык Android-приложения: тёмную `surface`, обычную `TopAppBar`, `bodyLarge`/`bodyMedium`, `SideDisc`, плоские разделители `outlineVariant`, поля 16 dp и стандартный ripple. Новых цветовых ролей, карточек, градиентов, аватаров и dashboard-плиток не требуется. - -## 3. Сравнение вариантов - -| Вариант | Действия | Плотность и шум | Цена | -|---|---|---|---| -| **A. Оставить две кнопки 48 dp у каждого** | Всегда 1 касание | 88 dp; полные слова White/Black самые явные, но две плашки и до двух действий повторяются в каждой строке. Нулевой цвет занимает disabled-плашку | Минимум разработки и уже знакомая модель. Не решает запрос на более спокойный и компактный экран; при линейном TalkBack-обходе много лишних остановок | -| **B. Одна строка игрока → выбор цвета** | Обычно 2 касания: игрок, затем цвет | Строка может быть 72 dp; имя и все счётчики видны без кнопочных плашек. На листе помещаются полное имя, полные подписи и точные числа | Дополнительный лист и второй тап даже тогда, когда ненулевой цвет только один. Если обязательно открывать лист всем, это неоправданная плата за единообразие | -| **C. Компактные segmented controls в строке** | 1 касание, если сегмент сразу запускает подготовку; 2, если это настоящий single-choice с последующим «Открыть» | Возможна строка 72 dp, но на 360 dp группа шириной 144 dp оставляет имени примерно 172 dp после полей и промежутка. Полные локализованные «Белыми»/«Чёрными» и большие числа уже не помещаются; приходится оставлять круги и короткие числа | Маленькие соседние цели повышают цену промаха и снова сокращают имена. При 280 dp/font scale 2.0 блок придётся переносить, возвращаясь к высоте текущего варианта. `SingleChoiceSegmentedButtonRow` со `selected` также ложно обещает сохраняемый выбор, хотя здесь нужен переход, а не фильтр | - -### Рекомендация — **B+: одна спокойная строка, лист только при реальном выборе** - -- **Оба цвета ненулевые:** касание строки открывает короткий `ModalBottomSheet` с двумя большими действиями. Второй тап — сам выбор цвета, отдельной кнопки подтверждения нет. -- **Ненулевой только один цвет:** касание строки сразу открывает подготовку этим цветом. Спрашивать единственный возможный вариант не нужно. -- **Ноль:** остаётся видимым текстом в строке, но перестаёт быть отдельной disabled-кнопкой. -- Никогда не выбирать автоматически цвет с большим числом партий, последний использованный цвет или White по умолчанию. - -Так сохраняется один тап у частого случая «есть только White или только Black», а при двух репертуарах появляется более явный и безопасный выбор. Это не скрытая смена смысла строки: доступные цвета и ноль видны до касания, а TalkBack заранее произносит либо «Выбрать цвет», либо «Подготовиться белыми/чёрными». - -Почему не C: экономия одного касания только у игроков с двумя цветами не оправдывает постоянное сокращение всех имён, риск попасть не в тот сегмент и неоднозначную семантику selected/action. При необходимости A можно оставить как временную реализацию, но не как целевой MVP-экран. - -## 4. Пользовательский путь и контекст - -```text -Партии → Игроки → игрок с двумя цветами → лист цвета → Подготовка - └ игрок с одним цветом ───────────────→ Подготовка -``` - -- Поиск остаётся в текущей `TopAppBar`: подстрока без учёта регистра, задержка 250 мс, ✕ и системное закрытие поиска. Порядок — алфавитный через `Collator`; точные написания не объединяются. -- При переходе в подготовку клавиатура скрывается. Возврат восстанавливает запрос, режим поиска и прокрутку, но сам не открывает клавиатуру поверх списка. -- Возврат из подготовки идёт в Players, а не заново в лист цвета. Прежний игрок не получает постоянную подсветку «выбран» или «текущая позиция». -- Android Back при открытом листе сначала закрывает только лист и возвращает фокус на исходную строку. Следующий Back возвращается в партии. -- Players и лист только читают уже полученный `PlayerSummary`; никаких несохранённых изменений и диалога сохранения нет. - -## 5. Макет списка - -### 5.1. Обычная строка, 360 dp - -```text -┌────────────────────────────────────┐ -│ ← Игроки ⌕ │ -│ Classic games │ -│────────────────────────────────────│ -│ Alekhine, Alexander 5 партий ›│ 24 -│ ○ Белыми · 2 ● Чёрными · 3 │ 20 -│────────────────────────────────────│ обычная высота строки 72 -│ Anderssen, Adolf 2 партии ›│ -│ ○ Белыми · 2 ● Чёрными · 0 │ -│────────────────────────────────────│ -│ Aronian, Levon 1 партия ›│ -│ ○ Белыми · 1 ● Чёрными · 0 │ -└────────────────────────────────────┘ -``` - -`›` показан справа условно по центру строки, а не как третья колонка таблицы. Вся строка, включая имя, счётчики и свободное место, — одна кнопка. - -### 5.2. Геометрия и типографика - -- Минимальная высота — **72 dp**: 12 сверху + имя/общий счёт 24 + 4 + цвета 20 + 12 снизу. Разделитель 1 dp находится внутри нижней границы и высоту не добавляет. -- По сравнению со 88 dp это на 18 % меньше высоты и примерно на 22 % больше видимых строк в той же области. Например, в подтверждённой текущим XML области около 750 dp помещается ориентировочно 10,4 строки вместо 8,5. -- Горизонтальные поля — 16 dp. Справа декоративный `ChevronRight` 24 dp `onSurfaceVariant`, перед ним промежуток 8 dp; отдельной зоны нажатия у него нет. -- Имя — существующий `PlayerName`, `bodyLarge`: полное имя, затем `shortName`, затем многоточие. Полное точное имя остаётся в content description. Общий счёт — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`, одной строкой; перед ним 8 dp, сокращается сначала имя. -- Цвета — `bodyMedium.merge(Tabular)`, `onSurfaceVariant`, в неизменном порядке **Белыми, затем Чёрными**. Существующий `SideDisc` 12 dp, промежуток до текста 8 dp; круг не озвучивается отдельно. -- Группа «круг + название цвета + число» неделима. Между группами 16 dp. Если обе не помещаются, они переносятся на две строки, а высота растёт через `heightIn(min = 72.dp)`; горизонтальной прокрутки и обрезания нулей нет. -- Общее число — прежнее число различных записей, а не обязательно `whiteGames + blackGames`. Оно не должно «исправляться» суммированием на UI. -- Строка плоская, без фона-карточки. Есть стандартный ripple и разделитель `outlineVariant`; постоянного selected-фона после возврата нет. - -### 5.3. Лист выбора цвета - -Открывается только когда `whiteGames > 0 && blackGames > 0`: - -```text -┌────────────────────────────────────┐ -│ ─── │ -│ Alekhine, Alexander │ titleLarge, полное имя -│ 5 партий · выберите цвет │ bodyMedium, secondary -│ ○ Белыми 2 ›│ 64, вся строка — действие -│ ● Чёрными 3 ›│ 64 -└────────────────────────────────────┘ -``` - -- Использовать существующий паттерн `ModalBottomSheet`, горизонтальные поля 24 dp и нижний отступ 24 dp, как у текущего листа подготовки из партии. -- Полное имя переносится, а не заменяется инициалами. При аномально длинном теге содержимое листа прокручивается; цветовые подписи и числа не обрезаются. -- Каждая строка — `heightIn(min = 64.dp)`, `SideDisc` 12 + 12 dp, цвет `bodyLarge`, точный счёт справа `bodyMedium.merge(Tabular)`. Это `Role.Button`, не RadioButton и не `selected` segment. -- Никакой загрузки статистики внутри листа: имя и счётчики уже есть в `PlayerSummary`, поэтому его высота не меняется после появления. -- Касание цвета сразу вызывает существующий `onPrepare(player, white)` и закрывает лист. Кнопки «Открыть»/«Продолжить» нет. - -## 6. Состояния и крайние случаи - -| Состояние | Требуемое поведение | -|---|---| -| Первое чтение | Верхняя панель видна; в области списка текущий индикатор/«Читаю игроков…». Нули вместо неизвестных значений не показываются | -| Подгрузка страниц | Заглушки с той же минимальной высотой 72 dp и теми же двумя текстовыми линиями; разделители не исчезают. Переход заглушка → обычная однострочная запись не меняет шаг списка | -| Поиск | Прежнее поведение и debounce сохраняются; ответ старого запроса не показывается как новый. Одновременно с redesign обязателен отдельный regression-фикс снимка списка, а не новый `players!!` в строке | -| Нет именованных игроков | Прежние «В этой базе нет именованных игроков» и «К партиям» | -| Ничего не найдено | Прежние «Игрок не найден» и «Сбросить поиск» | -| Ошибка | Прежние причина через `openProblem` и «Повторить»; ошибка не маскируется под пустой список или нулевые цвета | -| Оба цвета есть | Одна строка «Выбрать цвет», затем лист с двумя действиями | -| Только White или только Black | Оба счётчика видны, включая `0`; касание сразу запускает единственный ненулевой цвет | -| Нулевой цвет | Текст `… · 0` обычной secondary-краской, без disabled-плашки и отдельного фокуса. Цвет не скрывается и места White/Black не меняются | -| Длинное имя | Действует существующее `PlayerName`; счётчики не наезжают. Полное имя озвучивается, а на листе двух цветов также переносится визуально | -| 280/320 dp и font scale 1.3/2.0 | Цветовые группы переносятся, строка и лист растут; названия цветов и нули не обрезаются. Нет горизонтального скролла и сегментов уже 48 dp | -| Сотни игроков | Сохранить `LazyColumn`, страницы по 100, стабильный ключ `id` и фоновое чтение. Один semantic node на человека сокращает линейный TalkBack-обход. Не добавлять ради этого полную загрузку базы в память | -| Широкое окно/ландшафт | Та же одноколоночная лента и тот же лист, не сетка и не настольные столбцы | -| HiDPI | Только dp/sp, существующие векторные icons и `SideDisc`; новых растровых ресурсов нет | -| Возврат | Запрос и прокрутка прежние; лист закрыт, клавиатура сама не появляется, строка не подсвечена как выбранная | - -Алфавитный быстрый бегунок, буквенные section headers и виртуальные столбцы в этот MVP не входят: поиск уже решает основной сценарий сотен имён без усложнения жестов. - -## 7. Доступность, клавиатура и фокус - -### 7.1. TalkBack - -Вся строка игрока — один `Role.Button`; дочерние тексты не создают самостоятельные остановки. - -- Два цвета: **«Alekhine, Alexander, всего 5 партий. Белыми 2, чёрными 3. Выбрать цвет»**. -- Один цвет: **«Anderssen, Adolf, всего 2 партии. Белыми 2, чёрными 0. Подготовиться белыми»**. -- Только Black формулируется симметрично. Ноль произносится словами/числом, а не только затемнением. -- На листе действия: **«Alekhine, Alexander, белыми, 2 партии. Подготовиться»** и аналогично для чёрных. - -При открытии листа фокус переходит в него и один раз объявляется контекст «выберите цвет». При закрытии без выбора фокус возвращается на исходного игрока. После возврата из подготовки фокус/прокрутка по возможности восстанавливаются на том же `id`, без объявления его «текущей позицией». Ошибка и пустой результат объявляются один раз; подгрузка каждой страницы не читается вслух. - -### 7.2. Аппаратная клавиатура и D-pad - -| Ввод | Действие | -|---|---| -| Tab / Shift+Tab, D-pad | ← → Search/поле поиска → строки игроков → доступное действие пустого/ошибочного состояния. На листе: White → Black | -| Enter / Space / DPAD_CENTER | Активировать игрока или цвет один раз | -| IME Search | Скрыть клавиатуру, не запускать первого найденного игрока | -| Android Back / Esc | Закрыть лист; затем закрыть поиск; затем покинуть Players | -| Буквы и ←/→ вне текстового поля | Не перехватываются глобально; используются системной навигацией фокуса | - -Видимый фокус — рамка 2 dp `primary` вокруг всей строки или действия листа. Hover-tooltip у строки соответствует будущему действию: «Выбрать цвет» либо «Подготовиться белыми/чёрными». Дополнительного сенсорного long press не требуется. - -## 8. Требования разработчику - -1. Заменить в списке `PlayerPrepRow` с двумя `PlayerColorButton` на одну плоскую actionable-строку по §5. `PlayerSummary`, API статистики и `onPrepare(player, white)` не меняются; новых запросов ради листа нет. -2. Локальное состояние листа — только выбранный `PlayerSummary?`. Условие листа строго `whiteGames > 0 && blackGames > 0`; при ровно одном ненулевом счётчике вызывать `onPrepare` сразу. Не добавлять remembered color, сортировку по частоте или автоматический выбор большего репертуара. -3. Не использовать `SingleChoiceSegmentedButtonRow` и `checked/selected` для навигационных действий листа. Нужны две обычные строки `Role.Button`, визуально близкие к существующему листу подготовки из партии. -4. Переиспользовать `ModalBottomSheet`, `SideDisc`, `PlayerName`, `Tabular`, `groupDigits`, plurals и текущие цвета темы. Новые цвета не вводить; все новые строки/action labels перевести на девять поддерживаемых языков. -5. Placeholder и обычная запись имеют одинаковую минимальную геометрию 72 dp. Разделитель рисовать внутри строки, не отдельным элементом `LazyColumn`. -6. Исправление NPE при поиске остаётся обязательной отдельной частью изменения: LazyColumn должен работать с неизменным snapshot страницы, без чтения обнулённого `players!!`. Не считать смену UI-теста доказательством отсутствия гонки. -7. Сохранить точную статистику и постраничность. Общий total не вычислять суммой цветов; пустые/`?` имена и разные написания обрабатывать как раньше. -8. Compose-тесты: два цвета → лист; только White/Black → прямой переход; нули видимы без disabled-действия; отсутствие выбора по большему count; одна активация при double tap; Back из листа/подготовки; сохранение query+scroll; полное semantics-описание; перенос на 280 dp/font scale 2.0; placeholder → данные без скачка 72 dp. - -## 9. Независимой проверке после реализации - -Реализацию принимает отдельный ревьюер, не автор макета и не автор кода. Нужны реальные запуск и снимки, а не только Compose Preview или чтение Kotlin. Сравнить главную/«Партии» и «Партию» той же сборки по фону, TopAppBar, типографике, полям и `SideDisc`. - -Минимальные доказательства с учётом экономии владельца: - -1. **Players, заполненный:** 1080×2400, 420 dpi, тёмная тема; один человек с двумя ненулевыми цветами и минимум один с нулём. Проверить шаг 72 dp, поля 16 dp, переносы, отсутствие карточек и disabled-плашек. -2. **Лист двух цветов:** тот же игрок и те же счётчики; полное имя, White/Black, строки ≥64 dp. Back возвращает к той же строке без выбора. -3. **Единственный цвет:** касание сразу открывает подготовку стороной пользователя вниз (противоположной сопернику); возврат сохраняет query/scroll и не открывает лист. -4. **Переполнение:** длинное имя и font scale 2.0 либо 280/320 dp — отдельный целевой кадр, потому что здесь меняется wrapping. Числа и слова цветов не обрезаны, высота растёт только от переноса текста. -5. **Пагинация/поиск:** заглушка 72 dp → данные, ввод и очистка запроса без crash и без выдачи старого результата за новый. Для скачков зафиксировать координаты соседних строк; не создавать лишнюю серию одинаковых кадров. - -Каждый снимок подписать файлом, px, density, ориентацией и состоянием. Дефект записывать как экран/состояние, ожидаемая и фактическая геометрия или действие, шаги воспроизведения и файл evidence. Отсутствие прежнего `/tmp/opencode/prep48` не разрешает выдавать этот документ за визуально доказанное «стало лучше»: это решение к реализации и последующей приёмке. diff --git a/docs/design/android-review-button.md b/docs/design/android-review-button.md deleted file mode 100644 index 90f260d..0000000 --- a/docs/design/android-review-button.md +++ /dev/null @@ -1,215 +0,0 @@ -# Задача 29. Android: «📈 Анализ» в нижней панели партии - -Дизайнер, 2026-11-28, ветка `feature/android-review-button`. Я менял только этот документ; код не редактировал. - -**Статус решения:** сценарий ниже — подтверждённое требование владельца, не вариант для выбора. Отдельные **⏮ и ⏭ убрать**. **Касание ◀/▶ — один ход, удержание ◀ — в начало, удержание ▶ — в конец.** «📈 Анализ» добавить справа в ту же нижнюю панель, цветом `!!`. Второй панели не будет, доска не уменьшается. - -## 1. Задача экрана и пользовательский путь - -Главное на экране — читать партию и переходить по ходам; разбор должен быть заметен сразу, но не отнимать место у доски и не смешиваться с живым движком. - -Путь становится короче: - -- раньше: «Партия» → `⋮` → «Анализ партии» → лист запуска; -- теперь: «Партия» → **📈 Анализ** → тот же лист запуска → «Анализировать». - -После разбора та же кнопка — **📈 Отчёт**: открывает существующий `ReviewSheet` и возвращает скрытую панель анализа. Алгоритм, кэш, лист запуска, график, отчёт, остановка крестиком и пауза живого движка не меняются. Пункт «Анализ партии / Отчёт по партии» убрать из `⋮`, чтобы не было двух одинаковых входов. Остальные пункты меню и кнопка «Отчёт» внутри панели анализа остаются. - -Закрытие листа запуска или отчёта возвращает к той же позиции и прокрутке нотации. Системная «Назад» по-прежнему сначала закрывает верхний лист, затем предпросмотр PV, и только потом покидает партию. - -## 2. Что проверено в реальных материалах - -Просмотрены изображения, а не только имена файлов: - -- `docs/screenshots/android.jpg` — 1920×1080; -- `website/shots/raw/06-android.png` — 3840×2160; -- `website/shots/raw/phone/03-game.png`, `04-engine.png`, `08-review.png` — каждый 1080×2400, то есть эталонные 360×800 dp при density ×3; -- остальные телефонные снимки `01-home.png`, `02-games.png`, `05-play.png`, `06-who.png`, `07-rodent.png`; -- соответствующие материалы `designExample/`, включая доску с анализом и панель вариантов. - -На `03-game.png` панель высотой 72 dp содержит шесть элементов: движок, переворот, ⏮, ◀, ▶, ⏭. На `04-engine.png` включённый движок обозначен синим и подчёркиванием; это состояние нельзя дублировать у разбора. На `08-review.png` цвет `!!` уже используется в строке «!! Brilliant move» и в кружке на доске, а «Report» находится в строке над графиком. - -Проверен код: - -- нижняя панель — `GameScreen.kt:852–879`, высота `72.dp`; доска в портрете — `fillMaxWidth()` (`1284–1290`), в альбомной ориентации — `fillMaxHeight()` (`1272–1282`); -- повтор ходов сейчас встроен в `BarButton` (`1642–1693`): шаг на нажатии, повтор через 400 мс каждые 120 мс. **Этот автоповтор для ◀/▶ отменяется новым требованием владельца**; -- старый вход в разбор и его условия — `GameScreen.kt:1179–1200`; -- панель разбора и листы — `ReviewViews.kt`; останавливать разбор новой нижней кнопкой не требуется: для этого уже есть ✕ в `ReviewPanel`; -- во время активной партии с компьютером используется отдельный `PlayControls`; его состав этой задачей не меняем. - -## 3. Обязательная компоновка - -### 3.1. Портрет, эталон 360 dp - -```text -┌────────────────────────────────────┐ -│ ← Турнир · год ‹ › ⋮ │ -│ ● Чёрные │ -│ │ -│ ДОСКА 360 × 360 │ без изменения размера -│ │ -│ ○ Белые │ -│ [движок/разбор — только по state] │ -│ нотация, комментарии, варианты │ -├────────────────────────────────────┤ -│ ▣ ⇅ ◀ ▶ [📈]│ 72 dp, одна панель -│ Движок Анализ│ -└────────────────────────────────────┘ -``` - -Порядок слева направо фиксирован: **Движок → Перевернуть → ◀ → ▶ → 📈 Анализ/Отчёт**. ⏮ и ⏭ не остаются ни визуально, ни как невидимые кнопки. - -Размеры слотов на 360 dp: - -| Движок | Перевернуть | ◀ | ▶ | Анализ | -|---:|---:|---:|---:|---:| -| 60 dp | 48 dp | 78 dp | 78 dp | 96 dp | - -Сумма — ровно 360 dp. Все пять целей касания занимают полную высоту 72 dp; минимальная ширина — 48 dp. ◀/▶ остаются шире остальных навигационных кнопок, их значки — прежние 32 dp. - -На 320 dp: **56 / 48 / 64 / 64 / 88 = 320 dp**. Ниже 320 dp подпись «Анализ/Отчёт» скрывается, слот разбора сужается до 52 dp, иконка и полное описание для TalkBack остаются; панель не прокручивается горизонтально и не переносится на вторую строку. При ширине 280 dp раскладка: **52 / 48 / 64 / 64 / 52 = 280 dp**. - -В альбомной ориентации используется та же строка в правой колонке, высота по-прежнему 72 dp. Доска продолжает занимать полную доступную высоту. Никаких дополнительных карточек, отдельной плавающей кнопки или FAB над нотацией нет. - -### 3.2. Сам контрол разбора - -Он повторяет геометрию подписанной кнопки «Движок», чтобы базовые линии совпадали: - -- зона нажатия — весь закреплённый слот × 72 dp; -- визуальный контейнер иконки — **36×36 dp**, значок **24 dp**; -- под иконкой — одна строка `labelSmall` 12 sp/16 dp: «Анализ», «Отчёт» либо табличный счётчик `N/M`; -- контейнер 36 dp и ширина слота не меняются между состояниями; -- у разбора нет синего подчёркивания движка: это действие/переход к отчёту, не переключатель. - -Иконка — `Icons.Rounded.QueryStats`: график с лупой, близкий к настольному 📈 и отличный от `Memory` живого движка. Наличие `rounded/QueryStatsKt` проверено в уже подключённом `material-icons-extended-android:1.7.8`; новую графику и сторонние ресурсы добавлять не нужно. - -## 4. Навигация: касание и удержание - -| Контрол | Короткое касание | Удержание | -|---|---|---| -| ◀ | Ровно один шаг назад, как текущий `back()` | Один переход в начало отображаемой линии | -| ▶ | Ровно один шаг вперёд, как текущий `forward()` | Один переход в конец отображаемой линии | - -Обязательные детали: - -1. **Удержание не должно сначала делать один ход.** Короткий шаг выполняется при отпускании до системного `longPressTimeout`; по достижении таймаута выполняется только переход к границе. Отпускание после него не добавляет ещё один шаг. -2. Автоповтора 400/120 мс больше нет. Удержание срабатывает один раз; движение/отмена касания — без действия. -3. Обычная партия: начало — узел `0`; конец — конец текущей ветки, как у существующего `end()`. -4. Предпросмотр PV остаётся отдельным контекстом: касания листают шаги PV, удержания идут к первому/последнему шагу PV. Выход из PV — прежние ✕, системная «Назад» или касание доски; касание ◀ до первого шага также выходит, как сейчас. Партию предпросмотр не изменяет. -5. `canBack`/`canForward` одновременно управляют касанием и удержанием. Недоступные действия не исчезают и не переставляют соседние кнопки. -6. Для этих двух кнопок нужен отдельный `combinedClickable`-контрол (или эквивалент с такой же семантикой), а не прежний `BarButton(repeat = true)`. Переворот доски остаётся на прежнем `BarButton`. - -## 5. Состояния кнопки разбора - -Действие кнопки переиспользует логику удаляемого пункта меню `1179–1200`; повторный разбор, скачивание движка и открытие сессии для новой/завершённой компьютерной партии не переписываются. - -| Состояние | Вид в постоянном слоте | Действие и доступность | -|---|---|---| -| Партия загружается | Нейтральная иконка, «Анализ» | Недоступна; слот уже занят, последующего сдвига нет | -| Нет ходов | Нейтральная иконка, «Анализ» | Недоступна; подсказка «В партии нет ходов для анализа» | -| Разбора нет, ходы есть | **Бирюзовый контейнер 36 dp**, тёмная/белая иконка по теме, подпись «Анализ» | Открывает существующий лист запуска; разбор не начинается молча | -| Движок ещё не скачан | То же приглашающее состояние | Тот же лист запуска, затем существующий лист скачивания | -| Движок готовится | Индетерминированное кольцо вокруг 📈, «Анализ» | Не даёт открыть дубликат потока; текст «Готовлю движок…» остаётся в панели | -| Идёт первый разбор, данных для отчёта ещё нет | Детерминированное кольцо 📈, подпись `N/M`, без сплошной заливки | Недоступна как действие; прогресс и ✕ «Остановить» — в `ReviewPanel` | -| Идёт разбор, частичный/прежний отчёт уже есть | Кольцо 📈, подпись «Отчёт» | Доступна: открывает отчёт, процесс продолжается; остановка только существующим ✕ | -| Разбор готов или загружен из кэша/PGN | 📈 бирюзовым **без заливки**, подпись «Отчёт» обычным `onSurface` | Открывает `ReviewSheet`, возвращает панель, если она была скрыта | -| Анализ скрыт через «Скрыть анализ» | То же состояние «Отчёт» | `reviewHidden = false` и открытие отчёта; анализ не удаляется | -| `stale`, `missing`, `secondsMissing`, ошибка | Нижняя кнопка остаётся «Отчёт», если `hasData`; иначе обычная «Анализ» | «Обновить», «Дополнить», «Продолжить» остаются в панели; новых параллельных действий нет | -| Идёт партия с компьютером | Эта панель не показывается, действует `PlayControls` | Ничего не добавлять; после завершения доступен обычный экран разбора | - -Прогресс не должен озвучиваться автоматически на каждое обновление: TalkBack читает `N/M` при фокусе, иначе несколько сотен объявлений подряд помешают навигации. - -## 6. Цвет и существующие селекторы - -### 6.1. Источник цвета - -В Android уже есть единый селектор шахматных цветов `nagColor(nag, dark)` в `theme/Color.kt:57–79`; `judgementColor(BRILLIANT, dark)` вызывает его через NAG `$3` (`ReviewViews.kt:81–92`). Использовать его, **не дублировать новую константу разбора в `GameScreen.kt`**. - -| Состояние | Тёмная тема | Светлая тема | -|---|---|---| -| Контейнер «Анализ» | `#26C2A3` — `nagColor(3, true)` | `#1A846F` — `nagColor(3, false)` | -| Иконка на контейнере | `#1B1B1B`, контраст 7,65:1 | `#FFFFFF`, контраст 4,59:1 | -| Hover при мыши | `#3FD3B4` / иконка `#1B1B1B` | `#157461` / белая иконка | -| Pressed | `#1FA88D` / иконка `#1B1B1B` | `#10614F` / белая иконка | -| «Отчёт» | Без заливки; 📈 `#26C2A3`, подпись `onSurface` | Без заливки; 📈 `#1A846F`, подпись `onSurface` | -| Недоступна | Без бирюзового: `onSurface` с alpha 0,38 | То же | - -Оттенки hover/pressed совпадают с уже принятым настольным решением `docs/design/task-26-review-button-2026-11-27.md`. На панели Android `surfaceContainer` контраст самой бирюзовой иконки — 6,89:1 в тёмной и 4,02:1 в светлой теме; для графики достаточно 3:1. Подпись всегда `onSurface`, поэтому читаемость 12 sp не зависит от бирюзового. - -В проекте нет XML `res/color*` или `selector`-ресурсов для этих кнопок: состояния задаются в Compose. Не создавать параллельный `ColorStateList`. Базовый цвет берётся из `nagColor`; производные оттенки, если понадобятся явно, размещаются одной функцией рядом с ним. Обычный ripple нажатия сохраняется поверх указанных цветов. - -Сплошная заливка нужна только до первого разбора. После него яркое приглашение исчезает, чтобы не спорить с доской, синим текущим ходом (`#005C80`) и включённым движком. Состояния различаются также текстом, кольцом прогресса и доступностью, не одним цветом. - -## 7. TalkBack, клавиатура и подсказки - -### 7.1. Семантика разбора - -- Вся область слота — один `Role.Button`, без отдельно фокусируемых иконки и подписи. -- `contentDescription`: полное существующее `review_menu` («Анализ партии») или `review_report_menu` («Отчёт по партии»), а не короткое видимое «Анализ». -- Во время подготовки/разбора `stateDescription`: «Готовлю движок…» или существующий `review_progress` («Анализ партии · N из M»). -- Недоступное состояние выставляется через `disabled()`/`enabled = false`; TalkBack должен сказать «неактивно», касание ничего не запускает. -- Кнопка не `Switch` и не `toggleable`: открытый лист — не включённый режим. - -### 7.2. Семантика ◀/▶ и альтернатива удержанию - -Для ◀: - -- `contentDescription` — «Предыдущий ход»; -- `onClick` — один шаг; -- `onLongClick(label = "В начало линии")` — переход к началу; -- в `customActions` добавить **«В начало линии»**. - -Для ▶ — симметрично: «Следующий ход», `onLongClick(label = "В конец линии")`, custom action **«В конец линии»**. - -Так переходы к границам доступны не только жестом: в TalkBack они есть в меню действий элемента. Двойное касание выполняет один шаг; двойное касание с удержанием — long click. Не полагаться только на последний жест. - -Порядок обхода TalkBack и D-pad: **Движок → Перевернуть → Предыдущий ход → Следующий ход → Анализ партии**. Enter/Space/DPAD_CENTER активирует короткое действие. При фокусе на ◀ клавиша Home повторяет «В начало линии», при фокусе на ▶ End — «В конец линии»; глобальных буквенных сокращений не добавлять. Фокус — видимая рамка 2 dp `primary` вокруг контейнера иконки, не только изменение tint. - -### 7.3. Видимые подсказки - -1. **📈:** `PlainTooltip` по hover и удержанию (у этой кнопки удержание не занято навигацией). Текст: «Анализ партии», «Отчёт по партии», «Анализ партии · N из M. Остановка — крестиком над графиком» либо причина недоступности. Tooltip обёртывает весь слот, поэтому работает и у визуально неактивной кнопки. -2. **◀/▶:** hover-tooltip «Предыдущий ход. Удержание — в начало линии» / «Следующий ход. Удержание — в конец линии». На сенсорном экране долгое нажатие выполняет действие, а не показывает tooltip. -3. Чтобы жест был открываем без мыши и TalkBack, один раз на устройство показать существующий `SnackbarHost`: **«Касание ◀ ▶ — один ход. Удержание — начало или конец линии.»** Показ — после загрузки обычной партии, не во время активной игры с компьютером и не поверх открытого листа. Snackbar перекрывает панель временно, но не меняет размеры layout; повторять при каждом открытии не нужно. Признак показа сохраняется в настройках. -4. Для локализации добавить короткие `review_short` («Анализ» / «Analysis»), подсказки удержания и одноразового Snackbar на все уже поддерживаемые языки. Полные названия берутся из существующих `review_menu`, `review_report_menu`, `review_progress`, `review_stop`. - -## 8. Матрица размеров и остальных состояний - -| Ситуация | Требуемое поведение | -|---|---| -| Пустая/новая партия | Кнопка видна, но неактивна; доска и остальные четыре контрола не двигаются | -| Ошибка загрузки партии | Нейтральная неактивная «Анализ»; ошибка остаётся существующим текстом в области нотации | -| Большая база | Разбор относится к уже открытой партии; новых списков и работы на UI-потоке нет | -| Несохранённые правки | Поведение сохранения и ухода не меняется; нижняя кнопка использует тот же путь, что прежний пункт меню | -| Запуск → прогресс → готово | Панель остаётся 72 dp, слот и контейнер 36 dp неизменны; меняются только иконка/кольцо и подпись | -| Появление кэша при открытии | «Анализ» меняется на «Отчёт» внутри того же слота без изменения ширины и высоты | -| Живой движок включён | Кнопка движка остаётся; во время разбора его строка показывает прежнюю паузу, затем счёт продолжается | -| Крупный шрифт | В узком слоте остаётся только 📈; полное имя есть в TalkBack и tooltip. Текст не обрезается и не переносит панель | -| 320/280 dp | Раскладки из §3.1; пять целей не уже 48 dp, нет горизонтального скролла | -| HiDPI | Vector-иконка и кольцо задаются в dp; эталонные снимки ×3 не должны показать обрезку или размытие | -| Смена темы | Меняется только палитра; размеры и позиции идентичны | - -Появление существующей панели разбора 88 dp уменьшает только нотацию и происходит по явному запуску/открытию сохранённого анализа, как раньше. **Само это изменение новой кнопки не добавляет ни одного dp по вертикали; доска в портрете остаётся 360×360 dp, а в альбомной ориентации — на всю доступную высоту.** Завершение, остановка, возврат из фона и появление статистики не должны вызывать скачков нижней панели. - -## 9. Требования разработчику - -1. В `GameScreen.kt` удалить два слота `FirstPage`/`LastPage`, добавить `ReviewButton` справа и оставить высоту `Surface`/строки без изменений. -2. Для ◀/▶ заменить repeat-контрол на tap/long-click с семантикой §4 и §7. Не вызывать шаг на `down`, иначе удержание даст лишний ход. -3. Вынести текущий обработчик пункта меню в один `onReview()` и вызывать его из новой кнопки; пункт меню удалить. Не заводить вторую реализацию открытия сессии. -4. Базовый цвет получать через `judgementColor(MoveJudgement.BRILLIANT, dark)` или `nagColor(3, dark)`. Не использовать `MaterialTheme.colorScheme.primary`: синий зарезервирован за движком и текущей позицией. -5. Ширину слота не вычислять от текста «Анализ»/`N/M`/«Отчёт». Счётчик — `labelSmall.merge(Tabular)`, одна строка. -6. Состояния и нажатия не должны менять `review`, кроме существующего пути запуска/открытия отчёта. Остановка остаётся только в `ReviewPanel`. -7. Добавить/обновить Compose-тесты семантики: один click, long click без предварительного click, custom actions, disabled, content/state descriptions и постоянные размеры слотов. - -## 10. Что передать независимому ревьюеру и тестировщику - -Ревьюер — не автор реализации; проверять реальное приложение на эмуляторе/устройстве и снимки, не только Kotlin-код. - -1. **Сравнение 360×800 dp, density ×3:** `03-game`, `04-engine`, `08-review` до/после. Доска и верх панели совпадают по координатам; нижняя панель остаётся 72 dp. Состояния: нет разбора, идёт первый разбор, готово/«Отчёт», включён живой движок. -2. **Серия без скачков:** «Анализ» → лист запуска → `N/M` → «Отчёт» → скрыть анализ → вернуть через нижнюю кнопку. Зафиксировать координаты доски, верха нотации и всех пяти слотов на каждом снимке. -3. **Жесты:** 20 коротких касаний дают ровно 20 ходов; удержание ◀/▶ — один переход к границе без предварительного шага и без автоповтора. Проверить вариант и PV, выход из PV прежними способами. -4. **Доступность:** TalkBack озвучивает полные названия, прогресс только по запросу фокуса, disabled; custom actions «В начало/конец линии» работают без удержания. Проверить одноразовый Snackbar и tooltip разбора. -5. **Узкое и крупное:** 320 dp и 280 dp, крупный шрифт: пять кнопок видны, цели ≥48 dp, текст не обрезан, второй строки нет. -6. **Цвет:** пиксельная сверка контейнера с `nagColor(3, dark)` и строкой «!! Brilliant move» на `08-review`-состоянии. В светлой теме — `#1A846F`, белая иконка. «Отчёт» не сохраняет сплошную заливку. -7. **Регрессии:** живой движок ставится на паузу и возобновляется; остановка разбора существующим ✕; поворот и возврат из фона продолжают разбор; активная игра с компьютером использует прежний `PlayControls`. - -Вердикт визуальной приёмки должен ссылаться на файлы снимков, размер/плотность и состояние каждого. Общего «панель выглядит так же» без доказательств недостаточно. diff --git a/docs/design/android-ui.md b/docs/design/android-ui.md index 3b014f4..0446da0 100644 --- a/docs/design/android-ui.md +++ b/docs/design/android-ui.md @@ -209,7 +209,6 @@ - Сноска внизу — единственное место, где объясняется запрет Android. Системный выбор папки сам пишет «Can't use this folder» по-английски и предлагает создать папку; наша строка заранее говорит, что делать. - **«Вставить PGN из буфера»** (§4.5) — первая строка, значок `content_paste`. Она есть, только если в буфере текст. Проверяется лишь описание буфера (`primaryClipDescription`, тип `text/*`): чтение самого текста Android объявляет всплывающим сообщением, поэтому текст читается только по нажатию. - - Отдельный автоматический сценарий из уточнения владельца (§4.5) проверяет текст при запуске/возврате в foreground один раз до решения пользователя; он не меняет этот ручной путь и не создаёт постоянного слушателя буфера. - Строка первой, потому что она контекстная: человек только что скопировал партию в другом приложении и пришёл её вставить. «Файл» и «Папка» сдвигаются на 72 dp, но на них не нажимают вслепую — лист читают глазами. - Подсказка до двух строк — допустимо; на 360 dp по-русски она помещается в одну-две строки, по-немецки «In einer anderen App kopierte Partien» — в одну. @@ -296,18 +295,6 @@ - Нет партий (пустой текст, обычный текст, текст без тегов и ходов) — лист закрыт, снекбар «В буфере нет партий в формате PGN». В список ничего не добавляется. - Тот же текст второй раз открывает уже сохранённую копию (§4.4). -#### Автоматическое предложение при запуске и возврате - -Уточнение владельца: приложение само проверяет буфер при холодном запуске и возврате в `RESUMED`, но только предлагает открыть его. Это не заменяет ручную строку «Вставить PGN из буфера»: ручной путь остаётся доступен для уже отклонённого текста. - -- Текст разбирается локально на фоновом потоке тем же PGN-reader. Предложение появляется только если первая запись содержит теги или ходы; пустой, обычный и повреждённый текст не вызывает диалог или снекбар. Снимок больше 8 MiB игнорируется, чтобы не блокировать интерфейс и не расходовать память. -- Обычный Material 3 `AlertDialog`: заголовок `Партия/Партии в буфере обмена`, короткое пояснение и текстовые кнопки «Открыть»/«Отмена». При нескольких используется локализованное число и явно сказано, что откроется первая. «Назад» и нажатие мимо означают отказ. Залитых кнопок, иконки и нового отдельного экрана нет. -- До выбора копии и записи в библиотеку нет. После «Открыть» вызывается `Library.addCopy`, затем стек `Databases → Games(id) → GameAt(id, 0)`: всегда открывается первая запись. `shown` и `lastOpened` этой копии сбрасываются, чтобы старый поиск не изменил выбор. Остальные записи доступны обычными стрелками и в списке после Back. -- После успешного открытия или отказа SHA-256 сохраняется в приватных настройках и после холодного перезапуска; сам PGN в настройки не пишется. Нажатие «Открыть» само по себе решённым не считается: digest появляется в настройках только после фактически сохранённой записи, поэтому ошибка записи допускает повторную попытку. Открытый или отклонённый текст повторно не предлагается, новый текст получает новое предложение. Нерешённый offer живёт в Application и переживает поворот без повторного разбора и дублирования. -- Пустой или новый буфер инвалидирует предыдущее поколение. Устаревший accept и устаревший импорт не публикуются. Проверка последнего запроса и публикация атомарны; URI и clipboard используют общий порядок последнего запроса и `compareAndSet` при потреблении события, чтобы старый collector не стёр новое. -- `UpdateSheet`, `Incoming.Opening` и `Incoming.Failed` имеют приоритет: clipboard-диалог их не перекрывает. Нерешённый вопрос скрывается без отказа, после закрытия блокировщика выполняется свежая проверка. -- Чтение только в foreground, без постоянного listener и сетевых вызовов. Необработанный текст не пишется в логи, Bundle и настройки; после отказа остаётся только SHA-256. - ### 4.6. «Открыть с помощью» и «Поделиться» - Приложение принимает `ACTION_VIEW` (схема `content`) и `ACTION_SEND` с MIME `application/x-chess-pgn`, `application/vnd.chess-pgn`, `application/zip`, `application/x-7z-compressed` и `application/octet-stream` — последний для `.cbv` и для `.pgn` из приложений, которые не знают этот тип (Telegram). `text/plain` не принимаем: иначе ChessPenguin предлагался бы для любого текста; текст партии вставляется из буфера (§4.5). @@ -1421,11 +1408,13 @@ |---|---|---| | `review_menu` / `review_report_menu` | Анализ партии / Отчёт по партии | Game analysis / Game report | | `review_text` | Движок оценит каждую позицию основной линии. Сама партия не изменится. | The engine evaluates every position of the main line. The game itself is not changed. | -| `review_stale` / `review_update` / `review_engine` | Анализ сделан с прежними настройками движка / Обновить / Проанализировать движком | This analysis was made with other engine settings / Update / Analyse with the engine | +| `review_quality` / `review_fast` / `review_normal` / `review_deep` | Качество / Быстро / Обычно / Глубоко | Quality / Fast / Normal / Deep | | `review_estimate` | Позиций: {n}, примерно {time} | {n} positions, about {time} | | `review_seconds` / `review_minutes` | {n} с / {n} мин | {n} s / {n} min | | `review_partial` | Уже оценено позиций: {done} из {total}. | {done} of {total} positions are evaluated already. | | `review_start` / `review_fill` | Анализировать / Дополнить | Analyse / Fill in | +| `review_restart` * (лист запуска, рядом с «Дополнить») | Заново | Start over | +| `review_again` * (отчёт) | Анализировать заново | Analyse again | | `review_progress` / `review_stop` | Анализ партии · {done} из {total} / Остановить анализ | Game analysis · {done} of {total} / Stop the analysis | | `review_accuracy` / `review_accuracy_of` | Точность / Точность: белые {w}, чёрные {b} | Accuracy / Accuracy: White {w}, Black {b} | | `review_report` | Отчёт | Report | @@ -1656,16 +1645,18 @@ │ основной линии. Сама партия не │ │ изменится. │ │ │ +│ Качество │ +│ [ Быстро | Обычно | Глубоко ] │ сегменты │ Позиций: 80, примерно 2 мин │ │ │ │ [Отмена] [Анализировать] │ └────────────────────────────────────┘ ``` -- Параметров нет (решение владельца 2026-10-28, `docs/decisions.md` «Разбор партии на фиксированных параметрах движка»): поиск один и тот же на всех телефонах и компьютерах — 1 млн узлов, один поток, Hash 32 МБ, процессов движка по числу ядер (до 4, по свободной памяти), `nice 10`. Настройки движка (§9) относятся только к живому анализу. -- Оценка времени — по скорости одного процесса, измеренной в прошлый раз на этом телефоне (сначала — осторожная прикидка), × число процессов, словами «примерно 2 мин». -- Если часть позиций уже оценена этим же поиском, под оценкой времени строка «Уже оценено позиций: 60 из 80.», а кнопка — «Дополнить» (только недостающие). «Заново» нет: тот же поиск дал бы те же оценки. Над оценками из PGN кнопка «Анализировать» считает всё движком. -- Разбор, сделанный до этого решения (на выбранном качестве), — устаревший: панель (§21.3) пишет «Анализ сделан с прежними настройками движка» и «Обновить» — пересчитать всё. +- Качество — те же уровни, что на компьютере: 250 тыс., 1 млн, 3 млн узлов на позицию; по умолчанию «Обычно», выбор запоминается. +- Потоки и память — из настроек движка (§9, «Дополнительно»), отдельно не спрашиваются. +- Оценка времени — по скорости, измеренной в прошлый раз на этом телефоне (сначала — осторожная прикидка), словами «примерно 2 мин». +- Если часть позиций уже оценена, под оценкой времени строка «Уже оценено позиций: 60 из 80.», а кнопки — «Заново» (текстовая) и «Дополнить» (главная, только недостающие). «Отмена» здесь не нужна: лист закрывается свайпом и «назад». Короткое «Заново» понятно только рядом с «Дополнить», поэтому это отдельная строка `review_restart`, а не «Анализировать заново» из отчёта. - Оценка времени считает только те позиции, которые будут считаться: при «Дополнить» — недостающие. ### 21.3. Панель анализа diff --git a/docs/design/design-system.md b/docs/design/design-system.md deleted file mode 100644 index be598b8..0000000 --- a/docs/design/design-system.md +++ /dev/null @@ -1,175 +0,0 @@ -# Дизайн-система ChessPenguin - -Дата фиксации: 2026-11-05. Основа документа — **библиотека баз и список партий, просмотр партии, настройка и игра с компьютером**. Раздел тренировки дебютов не является визуальным эталоном для этого документа. - -Документ различает три статуса: - -- **Факт** — существующая реализация, подтверждённая исходниками и просмотренными снимками. -- **Правило пользователя** — обязательное требование, в том числе новое, даже если раньше интерфейс работал иначе. -- **Рекомендация** — предлагаемый способ унифицировать новые экраны; не утверждение, что все старые экраны уже ему соответствуют. - -Все размеры далее — логические единицы egui (pt), не физические пиксели снимка. Масштаб окна/HiDPI меняет физическое изображение. Значения цветов — исходные токены, а не замер сглаженных пикселей текста. - -## 1. Характер интерфейса и эталоны - -**Факт.** Это плотное настольное приложение для работы с шахматным материалом. Основу составляют панели, таблицы, нотация и доска; заголовки и действия компактны. Выделение синее, фон спокойный, разделители тонкие. Большая часть пространства отдана данным, а не декоративным контейнерам. - -Просмотренные визуальные источники: - -| Экран | Что задаёт эталон | Снимок | -|---|---|---| -| Библиотека | Верхняя полка баз, строка действий, плотная таблица, фильтры справа | [library.png](../screenshots/library.png) | -| Партия | Доска слева, нотация/анализ справа, компактная шапка, toolbar внизу | [game.png](../screenshots/game.png) | -| Настройка игры | Последовательность выбора, равные плитки внутри группы, основной Play и Cancel внизу | [play.jpg](../screenshots/play.jpg) | - -Это реальные снимки приложения, а не новые макеты. Их язык, масштаб и состав данных отличаются; точные размеры берутся из кода. Дополнительно просмотрены свежие RU-снимки текущей сборки, 1400×900, тёмная тема: [главная](../../target/qa-quiet-status/shots/main.png), [партия](../../target/qa-quiet-status/shots/game.png), [настройка игры](../../target/qa-quiet-status/shots/play.png). Последний снимок подтверждает диалог выбора, а не запущенную партию с движком. QA-файлы в `target/` локальные и могут отсутствовать после очистки. - -**Рекомендация.** Новые разделы заимствуют эту структуру и общие widgets. Не вводить отдельную палитру, крупные декоративные KPI-карточки, постоянные пустые резервные блоки или новый комплект шрифтов. Существование карточек базы и шахматных часов не делает карточку универсальным контейнером для любого текста. - -## 2. Типографика - -**Факт.** Приложение начинает с `egui::FontDefinitions::default()`: основной proportional — **Ubuntu Light**, monospace — **Hack**. Дополнительно подключены **Ubuntu Bold**, глифы фигур и NotoSansMath для шахматных оценок. Для фигур используется tweak scale 0.85 и y-offset −1. Источник: [assets.rs:156](../../apps/desktop/src/assets.rs#L156), [assets.rs:168](../../apps/desktop/src/assets.rs#L168). - -| Назначение | Реализованное значение | Источник | -|---|---:|---| -| Обычный текст / стандартная кнопка | 13 | egui `TextStyle::Body` / `Button` | -| Обычный heading | 18 | egui `TextStyle::Heading` | -| Monospace по умолчанию | 13 | egui `TextStyle::Monospace` | -| `.small()` по умолчанию | 9 | egui `TextStyle::Small` — не универсальная рекомендация для важных данных | -| Название базы / строка подробностей на полке | 14 / 12 | [library.rs:1200](../../apps/desktop/src/library.rs#L1200) | -| Ход основной нотации | Ubuntu Bold 16 | [notation.rs:606](../../apps/desktop/src/notation.rs#L606) | -| Номер хода / комментарий | 14 / 14.5 | [notation.rs:299](../../apps/desktop/src/notation.rs#L299), [notation.rs:862](../../apps/desktop/src/notation.rs#L862) | -| Заголовок группы / выбор в настройке игры | 15 strong / 14 | [play.rs:1278](../../apps/desktop/src/play.rs#L1278) | -| Имя игрока / состояние под именем | 15 / 13 weak | [game_view.rs:3515](../../apps/desktop/src/game_view.rs#L3515) | -| Шахматные часы | monospace 18–28, адаптивно | [game_view.rs:3484](../../apps/desktop/src/game_view.rs#L3484) | - -`RichText::strong()` и явный `assets::bold()` — разные механизмы: наличие `.strong()` не означает назначение Ubuntu Bold. Для шахматных ходов уже есть явный семейственный токен, его следует переиспользовать. - -**Рекомендация.** Body/heading применять по смыслу. Второстепенность выражать `weak()`, а не произвольным уменьшением всех подписей. Значимые числа, названия и кнопки не делать 9 pt. Имена обрезать с многоточием и давать полное название в tooltip; пояснения переносить. Для часов и технических последовательностей допустим monospace, для обычных метрик он не обязателен. - -## 3. Темы и цветовые токены - -**Факт.** Используются `egui::Visuals::dark()` и `light()`, без собственной глобальной палитры. Тёмная тема — значение по умолчанию в Settings. Источники: [app.rs:3782](../../apps/desktop/src/app.rs#L3782), [settings.rs:210](../../apps/desktop/src/settings.rs#L210). - -Значения ниже сняты с локально установленной зависимости **egui 0.36.2**, на которой построена текущая реализация. Они описывают snapshot, а не требование дублировать RGB в каждом модуле. Вызывать `ui.visuals()` предпочтительнее литералов. - -| Роль / токен | Тёмная тема | Светлая тема | -|---|---|---| -| Фон панелей/окон `panel_fill`, `window_fill` | RGB(27,27,27), `#1B1B1B` | RGB(248,248,248), `#F8F8F8` | -| Обычный текст `noninteractive.fg_stroke` | RGB(140,140,140), `#8C8C8C` | RGB(80,80,80), `#505050` | -| Разделитель `noninteractive.bg_stroke` | RGB(60,60,60), `#3C3C3C`, 1 pt | RGB(190,190,190), `#BEBEBE`, 1 pt | -| Фон кнопки в обычном состоянии (без наведения) | RGB(60,60,60), `#3C3C3C` | RGB(230,230,230), `#E6E6E6` | -| Текст кнопки в обычном состоянии (без наведения) | RGB(180,180,180), `#B4B4B4` | RGB(60,60,60), `#3C3C3C` | -| Hover-фон обычной кнопки | RGB(70,70,70), `#464646` | RGB(220,220,220), `#DCDCDC` | -| Нажатый фон обычной кнопки | RGB(55,55,55), `#373737` | RGB(165,165,165), `#A5A5A5` | -| Выбранное / primary `selection.bg_fill` | RGB(0,92,128), `#005C80` | RGB(144,209,255), `#90D1FF` | -| `selection.stroke.color` | RGB(192,222,255), `#C0DEFF` | RGB(0,83,125), `#00537D` | -| Фон поля ввода `extreme_bg_color` | RGB(10,10,10), `#0A0A0A` | RGB(255,255,255), `#FFFFFF` | -| Ссылка `hyperlink_color` | RGB(90,170,255), `#5AAAFF` | RGB(0,155,255), `#009BFF` | -| Предупреждение `warn_fg_color` | RGB(255,143,0), `#FF8F00` | RGB(255,100,0), `#FF6400` | -| Ошибка `error_fg_color` | RGB(255,0,0), `#FF0000` | RGB(255,0,0), `#FF0000` | - -`weak_text_alpha=0.6`, `disabled_alpha=0.5`. `faint_bg_color` — аддитивная яркость 5, **не самостоятельный непрозрачный RGB-фон**. Не применять её как единственную заливку полноэкранного workspace. Стандартные радиусы: окно 6, обычный widget 2, hover 3; локальные компоненты могут задавать свои значения. - -Источники чисел: локальный [egui style.rs:1414](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1414), [темы:1498](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1498), [выделение:1618](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1618), [widget states:1681](/home/vrubel/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/egui-0.36.2/src/style.rs#L1681). Это ссылки на локальный cache для воспроизводимости, они не являются файлами репозитория. - -### Шахматные семантические цвета - -**Факт.** Комментарии: dark `#9EC4E0`, light `#2A5B8A` ([notation.rs:1141](../../apps/desktop/src/notation.rs#L1141)). NAG имеют отдельную согласованную палитру, а текст в светлой теме затемнён для читаемости: - -| NAG | Основной цвет | Текст в светлой теме | -|---|---|---| -| `!` | `#81B64C` | `#5B8135` | -| `?` | `#FFA459` | `#C25700` | -| `!!` | `#26C2A3` | `#1A846F` | -| `??` | `#FA412D` | `#D2301C` | -| `!?` | `#EA45D8` | `#B0259F` | -| `?!` | `#56B4E9` | `#1F72A8` | - -Источник: [notation.rs:695](../../apps/desktop/src/notation.rs#L695). Цвета доски/фигуры выбирает пользователь; зелёная или коричневая доска на снимке не задаёт палитру интерфейса. Стрелки PGN имеют самостоятельную семантику ([board.rs:767](../../apps/desktop/src/board.rs#L767)). - -## 4. Кнопки и состояния - -**Факт.** Одного размера для всех кнопок сейчас нет. Это важно учитывать, а не объявлять произвольные 30 pt уже существующим глобальным стандартом. - -| Роль | Реализация | Размер/поведение | -|---|---|---| -| Плотная кнопка toolbar | `ui.button`, обычный egui Button | Базовый `interact_size` 40×18, padding 4×1; фактический размер зависит от текста и widget | -| Главное действие диалога | `widgets::primary[_wide]` | Минимальная высота 30; strong, заливка selection; `_wide` сохраняет минимальную ширину | -| Подтвердить/отменить значком | `widgets::icon_button` | 30×30, радиус 4, рисованные ✓/✕ | -| Небольшая отмена фоновой задачи | `widgets::small_close_button` | 22×20, при hover красный `#C42B1C`, белый крестик | -| Сортировка таблицы | `widgets::sort_header` | Без рамки, strong, направление ⏶/⏷ | -| Выбор цвета/времени игры | selectable button | 32 pt высота, 14 pt текст; внутри строки одинаковая ширина, gap 6 | -| Выбор Maia/Rodent | Специальная плитка выбора | 48 pt высота, два уровня текста | -| Управление текущей игрой | `play_toolbar` | Общая высота 28; значки 18 pt, словесные кнопки 14 pt | - -Источники: [widgets.rs:35](../../apps/desktop/src/widgets.rs#L35), [widgets.rs:80](../../apps/desktop/src/widgets.rs#L80), [play.rs:1274](../../apps/desktop/src/play.rs#L1274), [play.rs:1406](../../apps/desktop/src/play.rs#L1406), [game_view.rs:3561](../../apps/desktop/src/game_view.rs#L3561). - -**Рекомендация для новых групп.** Связанные действия должны иметь одну высоту и baseline. Для группы основных действий использовать 30 pt, для плотного toolbar — существующий размер соседних элементов; не увеличивать всю верхнюю панель без причины. Равная ширина нужна у альтернативных вариантов выбора и заменяющих друг друга действий; кнопка «Закрыть» не обязана быть шириной со всё окно. Primary — одно очевидное основное действие, не каждый переход. Разрушительное действие отделяется смыслом и подтверждением, а не только красным цветом. - -**Факт.** Hover/pressed/open/disabled получают цвета из `ui.style().interact(...)` или стандартного Button. Selected — отдельное состояние: это не hover. Для собственнорисованных кнопок нужно воспроизвести состояние и hit target; рисовать только иконку недостаточно. Доступность `add_enabled` не заменять визуально похожим текстом. - -**Правило пользователя, 2026-11-05.** Глобальные настройки — одна общая кнопка справа -в шапке, включая статистику и прохождение тренировки. `widgets::settings_button` -переиспользуется библиотекой, партией и разделом дебютов: обычная «⚙ Настройки», -без primary-заливки; в компактном режиме — значок с понятной подсказкой и Ctrl+,. -Место под неё резервируется до длинного заголовка. Локальные параметры тренировки -не заменяют общие настройки. Возврат из окна настроек сохраняет контекст экрана. - -## 5. Таблицы, полка баз и нотация - -**Факт — список партий.** `TableBuilder`: полосатые строки, изменяемые ширины колонок, кликабельная строка; header **26 pt**, обычная строка **24 pt**. Ячейки используют left-to-right / Align::Center: вертикально центрированы, текст по умолчанию слева. Числовые колонки здесь **не выровнены глобально вправо**. Названия обрезаются, событие выделено курсивом, неизвестные значения часто пустые. Один клик выделяет; открытие и клавиатура реализованы отдельно. Источник: [large_db.rs:2109](../../apps/desktop/src/large_db.rs#L2109), [large_db.rs:2149](../../apps/desktop/src/large_db.rs#L2149), [large_db.rs:2212](../../apps/desktop/src/large_db.rs#L2212). - -Колонки адаптируются к ширине: второстепенные данные скрываются, дата может стать годом. Не требовать от узкого окна одновременно показывать полный набор колонок. Сортировочный заголовок показывает активное направление. Выбранная строка, hover и отметка просмотренной партии — разные признаки. - -**Факт — полка баз.** Карточка базы **190×64**, промежутки 8×8; название 14 pt максимум две строки, подробности 12 pt, иконка 22 pt. Это специфический переключатель источника данных, а не образец высоты строки таблицы. При более чем двух рядах/низком окне полка сворачивается в компактный вариант. Источник: [library.rs:545](../../apps/desktop/src/library.rs#L545), [library.rs:947](../../apps/desktop/src/library.rs#L947), [library.rs:1172](../../apps/desktop/src/library.rs#L1172). - -**Факт — нотация.** Строка основной пары ходов **26 pt**, колонка номера **38 pt**, каждая ячейка хода максимум **160 pt**. Номер выровнен вправо, white/black стоят в отдельных ячейках. Активный ход выделяется; комментарии и ветви занимают собственные строки/блоки. Источник: [notation.rs:180](../../apps/desktop/src/notation.rs#L180), [notation.rs:290](../../apps/desktop/src/notation.rs#L290). - -**Рекомендация.** Новая одноуровневая таблица начинает с 24/26 pt и увеличивает высоту только по реальному содержимому. Многострочная строка должна иметь отдельное обоснование. Значения 156 pt и оформление списка тренировки дебютов **не входят в общую дизайн-систему**. Числа в новой аналитической таблице удобно выравнивать вправо, но это предложение для неё, не описание существующего списка партий. - -## 6. Компоновка и отступы - -**Факт.** Стандартный egui spacing: между widget 8 pt по горизонтали и 3 pt по вертикали; window/menu margin 6. Локально приложение меняет spacing по задаче: play-dialog — gap 6, form-grid 8×6, начало секции +12 и после заголовка +2. Часы имеют inner margin 10×6 и радиус 4. - -- Библиотека: полка сверху, таблица в центре, фильтры справа; фильтры по умолчанию 280 pt, верхний предел 380 ([library.rs:602](../../apps/desktop/src/library.rs#L602)). -- Партия: `Panel::top` шапки; правая изменяемая панель и `CentralPanel` доски. Боковая панель нотации по умолчанию `(width*0.4).clamp(260,460)` с дополнительным ограничением места для доски. Минимумы: side 240, reference 320, board 220; полоса оценки 26 ([game_view.rs:749](../../apps/desktop/src/game_view.rs#L749), [game_view.rs:5004](../../apps/desktop/src/game_view.rs#L5004)). -- В узком/высоком окне панель партии может перейти под доску; выбор компоновки зависит от окна, а не появления анализа или смены вкладки. Подробное существующее правило: [narrow-windows.md](narrow-windows.md). -- Игра использует тот же каркас доски. Имя/часы верхней стороны сверху, нижней — снизу, нотация между ними, toolbar закреплён внизу ([game_view.rs:3359](../../apps/desktop/src/game_view.rs#L3359)). -- Диалог игры имеет ширину 460; тело скроллится при малой высоте, кнопки завершения выбора остаются видны. Не скроллить главный CTA вместе с длинным телом ([play.rs:1253](../../apps/desktop/src/play.rs#L1253)). - -**Рекомендация.** Связанные элементы группировать интервалами 6–8 pt, смысловые группы отделять 10–12 pt или стандартным separator. Не применять фиксированную пустую высоту как универсальную защиту от скачков. Закреплять действия вне растущего текста/скролла, а данные давать естественной высоты. Расчёт минимальной ширины должен учитывать реальный перевод и места под кнопки до размещения длинного имени. - -## 7. Клавиатура, фокус, названия - -**Факт.** В списке партий есть ↑/↓, PageUp/PageDown, Enter; собственные базы добавляют команды редактирования. В партии есть ←/→, Home/End, F (поворот), команды сохранения и Undo/Redo. Команды отделены от ввода текста и контекстных режимов; поэтому буквальные сочетания следует проверять в обработчике конкретного экрана, а не копировать без guards. Источники: [large_db.rs:2377](../../apps/desktop/src/large_db.rs#L2377), [game_view.rs:4779](../../apps/desktop/src/game_view.rs#L4779). Escape отменяет диалог настройки игры ([play.rs:1815](../../apps/desktop/src/play.rs#L1815)). - -**Рекомендация.** Tab/Shift+Tab — последовательный обход, Enter активирует ожидаемое действие сфокусированного элемента, Escape закрывает самый верхний popup/диалог прежде, чем уходить с экрана. Не перехватывать сочетание редактирования текста для управления доской. Иконки без слов требуют tooltip с понятным действием; полные обрезанные имена доступны при наведении. Не считать полную клавиатурную доступность всех старых экранов доказанной только наличием egui. - -## 8. Загрузка, сохранение, ошибки - -**Правила пользователя, 2026-11-05.** - -1. **Не показывать spinner при обычном старте главного экрана.** Восстановление библиотеки и её служебные фоновые проверки не должны превращать запуск в демонстрацию внутренних операций. -2. **Не показывать «Сохранение прогресса / Saving progress…» после каждого хода.** Обычная успешная фоновая запись проходит тихо; она не должна менять текст, высоту или состояние основного блока на каждом ответе. - -Эти правила не означают запрет всей обратной связи о длительной работе. **Рекомендация:** при явно запущенном пользователем импорте, скачивании движка или длительном анализе показывать осмысленное состояние, численный прогресс, если он известен, и отмену, если она поддерживается. Короткие внутренние операции не должны мигать индикаторами. - -**Факт.** В настройке игры скачивание весов использует ProgressBar ([play.rs:1978](../../apps/desktop/src/play.rs#L1978)); текущий соперник показывает «thinking…» текстом в своей строке состояния ([game_view.rs:3518](../../apps/desktop/src/game_view.rs#L3518)). Это предметная обратная связь, а не общий spinner на всё окно. - -**Рекомендация.** Ошибку показывать словами о результате действия, с конкретным доступным следующим шагом. Техническую причину — раскрываемыми подробностями, без обрезания единственного полезного сообщения. При ошибке записи нельзя показывать успешное сохранение или молча терять данные. Состояние загрузки не должно подменять старые данные новой позиции; а stale-анализ нельзя выдавать за текущий. Empty-состояние объясняет отсутствие данных и доступное действие, а не выводит набор нулей без контекста. - -## 9. Граница применения и приёмка - -Этот файл описывает существующую основу и рекомендует единые правила для дальнейшей работы. Он не утверждает, что весь UI уже унифицирован. Плотный toolbar 18 pt, игровые кнопки 28 pt, primary 30 pt и плитки выбора 32/48 pt — реальные разные роли; исправлять их до одного числа без анализа сценария не требуется. - -Для нового UI проверять не только попадание текста в прямоугольник: - -- Понятны ли задача экрана, единицы чисел и следующее действие без чтения внутреннего ТЗ? -- Соответствуют ли фон, текст, выделение и плотность основным экранам? -- Совпадают ли размеры и baseline действий одной группы? -- Сохраняются ли контекст, выбранная строка, фокус и геометрия доски при данных/ошибке/возврате? -- Работают ли длинные имена, пустое состояние, светлая/тёмная тема и выбранная минимальная ширина? -- Нет ли мигающей служебной активности при старте и на каждом ходе? - -Визуальную приёмку проводит отдельный reviewer на реальных снимках, с указанием состояния, размера окна и конкретного сценария. Код и геометрические тесты полезны, но не заменяют оценку понятности и соответствия эталонам. diff --git a/docs/design/engine-download.md b/docs/design/engine-download.md index 14303c1..20ce072 100644 --- a/docs/design/engine-download.md +++ b/docs/design/engine-download.md @@ -2,7 +2,7 @@ Статус: проект дизайнера, 2026-10-19, **не утверждён**. Основа — решение 14 в `../decisions.md` (Stockfish больше не в пакетах, кроме Flatpak и Arch) и требование владельца «просто, понятно, интуитивно понятно». Пересматривает поведение из решения 10: «встроенный» Stockfish остаётся только во Flatpak. -Опирается на текущий код: `apps/desktop/src/engines.rs` (`first_run_setup`, `suggestions`, `system_stockfish`), `settings_ui.rs` (вкладка «Движки»), `app.rs::toggle_engine` (сейчас без движка — тост и открытие настроек), `review.rs::dialog` (окно «Анализ партии», `egui::Modal`, 440 pt, кнопки справа налево), `game_view.rs::engine_panel` (переключатель «Анализ: вкл/выкл»). Скриншоты: (старые снимки удалены; актуальные — `docs/screenshots/`). +Опирается на текущий код: `apps/desktop/src/engines.rs` (`first_run_setup`, `suggestions`, `system_stockfish`), `settings_ui.rs` (вкладка «Движки»), `app.rs::toggle_engine` (сейчас без движка — тост и открытие настроек), `review.rs::dialog` (окно «Анализ партии», `egui::Modal`, 440 pt, кнопки справа налево), `game_view.rs::engine_panel` (переключатель «Анализ: вкл/выкл»). Скриншоты: `docs/screenshots/ru/settings.png`, `engine.png`, `analysis.png`. Размеры — логические точки egui; эталон 1920×1080 логически, минимум 900×600. diff --git a/docs/design/opening-cleanup-2026-11-05.md b/docs/design/opening-cleanup-2026-11-05.md deleted file mode 100644 index 1a7f38d..0000000 --- a/docs/design/opening-cleanup-2026-11-05.md +++ /dev/null @@ -1,146 +0,0 @@ -# Тренировка дебюта: переработка интерфейса после пользовательской проверки - -Дата: 2026-11-05. Статус: спецификация для реализации, не визуальная приёмка. - -## Задача и причина переработки - -На стартовом экране человек должен выбрать репертуар, понять, что уже знает и что пора повторить, и начать занятие. Статистика должна отвечать на эти вопросы словами пользователя, а не воспроизводить структуру LearningAggregate. - -Скриншот пользователя `/tmp/codex-clipboard-edzt9U.png` показывает реальные проблемы, пропущенные прежней приёмкой: `4294967295 полуходов`, счётчики «Итого / Новый» без единицы измерения, кнопки разных размеров в пяти местах, дублирование названия и числа вариантов. Прежний PASS означал геометрическую исправность и был недостаточным критерием качества продукта. Данная работа меняет информационную иерархию, а не только отступы. - -Основа визуального языка: библиотека партий и экран партии — обычные панели, таблицы и нотация, спокойный фон, синий цвет только для выбранного/основного действия. Без KPI-карточек, декоративных контейнеров и крупных процентов ради процентов. - -## 1. Стартовый экран - -Сохраняется единая рабочая область: доска слева; справа выбранный репертуар и библиотека. Смена строки не запускает тренировку. Возврат из редактора/статистики/занятия сохраняет выбранную строку, размер панели и прокрутку библиотеки. - -Правая панель сверху вниз: - -```text -sicilian - -За кого [Белыми] [Чёрными] -Порядок [По расписанию ▾] - -Изучено 0 из 23 ходов -Пора повторить: 0 · Ещё не изучали: 23 - -[ Тренироваться ] [ Параметры ] [ Статистика ] -───────────────────────────────────────────── -[ Создать ] [ Импорт PGN… ] -Название ECO Варианты -…библиотека… -``` - -При наличии ограничения выбранного репертуара рядом со сводкой допускается короткое «Часть репертуара» с tooltip о настроенном ограничении. Не печатать технический depth/plies, sentinel, вычисленную дату или формулу scope. Числа на этом экране относятся к реальной очереди занятия; число изученных нельзя делить на общий полный репертуар при ограниченной тренировке. - -### Расположение действий - -- Основные действия занятия — одна строка, ровно три равных по ширине кнопки. Высота 30 pt, промежутки 8 pt; ширина `(доступная ширина − 16)/3`. Надписи по центру, без переноса. Primary только «Тренироваться» / «Продолжить»; две другие нейтральные. -- Текст primary не содержит числа и не меняется на длинное «Добавить новые ходы». Если сроков повторения нет и есть новые ходы, действие по-прежнему начинает занятие с новым материалом. Это объясняется сводкой, tooltip и состоянием занятия. -- Не выносить Edit справа от заголовка, Details справа от статистики и маленькое ⋯ в третий угол. «Редактировать» доступно в меню строки репертуара рядом с Rename/Import/Export/Delete; это операции над материалом, не действия занятия. -- Параметры занятия открывают единый popup/диалог: порядок нового материала, контекст и скорость, затем отделённая группа «Сбросить прогресс…» и при необходимости «Начать обход заново…». Сброс подтверждается с описанием общих ходов; core-семантика не меняется. Не оставлять отдельный Reset Review Order под основной строкой. -- «Создать» и «Импорт PGN…» принадлежат библиотеке: отдельная строка под разделителем, одинаковая высота 28 pt и согласованная ширина не менее 120 pt. Не повторять их у доски. -- Число вариантов остаётся в столбце таблицы. Дубликат крошечным серым текстом возле CTA удалить. - -### Тексты и смысл - -| Сейчас | На экране | Пояснение при наведении | -|---|---|---| -| Total / Итого | В сводке: «Изучено X из Y ходов»; в расширенных таблицах: «Ходов для изучения» | Уникальные ответы выбранной стороны. Общие позиции считаются один раз. | -| Unseen / Новый | «Ещё не изучали» | Эти ходы ещё не встречались в тренировке. | -| Learning / Изучается | «Закрепляем» | Для закрепления нужны три самостоятельных правильных ответа подряд. | -| Learnt / Изучено | «Изучено» | Не менее трёх самостоятельных правильных ответов подряд. Знание требует последующих повторений. | -| Due / К повторению | «Пора повторить» | Срок очередной проверки уже наступил. | -| Uncertain | «Давно не повторяли» | Часть ранее изученных ходов, проверка которых сильно просрочена. Не добавляется к общему числу второй раз. | -| Confident % | «Актуальные знания» только в подробной статистике | Изученные ходы без сильно просроченной проверки. | -| Review individual moves | «По расписанию» | Повторяем ходы, срок проверки которых наступил, затем вводим новые. | -| Review in order | «По порядку» | Последовательный обход материала. | -| Least recent and unseen first | «Сначала новые и давно не повторённые» | Длинное пояснение допустимо в popup, выбранный текст может сокращаться. | - -Не менять глобальный перевод общего `Total`, который используется в других разделах: в тренажёре нужны собственные ключи. - -Состояния сводки занимают одинаковые две строки. При загрузке — прочерки и краткое «Обновляем прогресс…» без расширения панели. При нулевом материале — «Нет ходов для тренировки» и «Добавьте варианты через редактор или импорт PGN»; primary выключен. При Due=0 не писать «Всё изучено». При Unseen>0 нейтральное пояснение — «Следующее занятие начнётся с новых ходов», если требуется, в tooltip primary. - -## 2. Длина материала - -Ни «полуходы», ни числовой sentinel не должны появляться на обычном стартовом экране или в сводке. `u32::MAX` отображается только как «Без ограничения». - -В редакторе ограничение — второстепенная настройка «Длина вариантов», изначально свернутая. Переключатель «Без ограничения» должен быть отдельным checkbox; числовой ввод не активен, когда он включён. Снятие ограничения — явное действие, не побочное следствие открытия редактора. - -Нельзя молча округлить старый нечётный `max_plies` до числа полных ходов: это меняет материал занятия. В рамках текущей переработки предпочтительнее убрать числовой лимит из основного редактора, сохранив существующий конечный лимит и возможность явного снятия ограничения; его точная дальнейшая форма редактирования требует отдельного решения. Если команда сохраняет числовой legacy-контрол на данном этапе, он должен быть скрыт в дополнительных параметрах и честно именовать единицу. Не выдавать `20 plies` за `20 ходов`. Это исключение не оправдывает возврат технической строки в prep. - -## 3. Экран статистики - -Задача: показать прогресс выбранного материала и помочь понять, что повторять. Название экрана «Статистика тренировки», а не «Панель обучения». - -Шапка: слева «← К репертуару», далее название. Под ней одна строка фильтров «Репертуар [sicilian ▾] За кого [Чёрными ▾]». Значение глобального scope — «Все репертуары», без слова «объединение». Дедупликация объясняется в tooltip общего итога. Не дублировать ту же пару фильтров следующей текстовой строкой и не выводить «Рассчитано в…» как постоянную пользовательскую информацию. - -Основные вкладки: **Обзор · Динамика · Расписание · Ходы**. Дополнительные отчёты «Варианты» и «Серии ответов» открываются через компактное меню «Дополнительно» на той же строке, если их сохраняют в UI. При их открытии текущий отчёт имеет видимый заголовок; нельзя оставлять активной неверную основную вкладку. - -### Обзор выбранного репертуара - -Выбран конкретный репертуар — показываем только его сводку: - -```text -Изучено 8 из 23 ходов 35 % -[полоса прогресса] - -Пора повторить 4 -Ещё не изучали 10 -Закрепляем 5 -Давно не повторяли 2 -Следующее повторение завтра / — -``` - -Прогресс компактный и встроенный, без декоративной карточки. «Давно не повторяли» сопровождается «из числа изученных» в tooltip. Нет попыток — точность «—», не ноль. Когда есть Due, вместо пустой даты писать «Есть ходы для повторения» либо показывать только Due. Дополнительные метрики — под раскрывающимся «Как считается прогресс», где объяснение короткое и без идентификаторов API. - -Выбраны все репертуары — сравнительная таблица из **пяти** столбцов: «Репертуар», «Изучено» (X/Y), «Прогресс» (%), «Пора повторить», «Ещё не изучали». Нижняя строка «Всего без повторов». Название получает не менее 40% ширины. Не показывать таблицу всех репертуаров под фильтром одного — это противоречит выбранному контексту. - -### Динамика и сохранение - -Удалить кнопку «Сохранить статистику в историю» и постоянные успешные сообщения о snapshot. Автоматический механизм снимков остаётся. Во вкладке «Динамика» короткое пояснение: «Прогресс сохраняется автоматически при первом просмотре за день». Не обещать ежедневные фоновые снимки, которых нет. Пустая история: «Здесь появится изменение вашего прогресса». Ошибка сохранения — в этой вкладке с действием «Повторить», без служебных деталей на каждом экране. - -### Варианты: зачем и как - -Нынешняя таблица из десяти колонок слишком рано включает wide-режим; для пути остаётся 120–150 pt. Это превращает смысловой столбец в обрезанную строку и не помогает решить, что повторять. Сохранить core-агрегаты, убрать отчёт с основного пути. - -Если отчёт доступен через «Дополнительно → Варианты», его задача прямо написана: «Какие продолжения стоит повторить. Общие ходы могут встречаться в нескольких вариантах». На всех ширинах одна модель из четырёх колонок: - -1. «Начало варианта» — не менее половины ширины, SAN, полный текст доступен при выборе. -2. «Изучено» — X/Y, не два голых счётчика. -3. «Пора повторить» — N. -4. «Точность» — % / —. - -Под таблицей постоянная по размеру область выбранного варианта: полный SAN с переносом, три-четыре понятные метрики. Не пытаться поместить дату, девять чисел и длинный SAN в одну строку. Выбор строки должен давать видимое полезное следствие; если отчёт не предлагает осмысленного действия/деталей, лучше временно убрать его из пользовательского UI целиком, сохранив расчёты. Название «Ветки» заменить на «Варианты» — слово согласовано с библиотекой. - -## 4. Библиотека, плотность, редактор - -Библиотека остаётся таблицей, а не лентой карточек. Сейчас фиксированные 156 pt были ранее явно согласованы для пяти ECO; новая задача позволяет пересмотр, но это не обязательное условие исправления верхнего блока. Рекомендуемый следующий шаг, если нужен компактный список: высота по готовому содержимому, имя + 1–5 строк дебютов, 6 pt сверху/снизу, без пустого резерва под отсутствующие строки. Показывать готовый набор строк атомарно после индексации; при обновлении сохранять anchor выбранной строки. Не допускать постепенного растягивания каждой строки по мере фоновых ответов. Если это не реализовано надёжно, текущие 156 pt временно сохраняются; не маскировать нехватку места уменьшением шрифта. - -Редактор: дерево — основная область, детали выбранного хода снизу. Сохранить фиксацию дерева, левое выравнивание, отдельную прокрутку аналитики и одинаковую с prep геометрию доски. Команды редактирования одной группы одинаковой высоты. Не создавать вторую копию полной статистики в редакторе. - -## 5. Размеры и поведение - -- Базовый текст — существующий body приложения; заголовок репертуара — existing heading, без нового размера. -- Между полями 6 pt, между смысловыми группами 10–12 pt. Граница библиотеки одна, без декоративных заливок. -- Поля параметров выровнены сеткой. Не растягивать подписи и числа по разным краям широкой панели без причины. -- Длинные имена truncate + tooltip; ширина кнопок и место под них рассчитываются до текста имени. -- Стандартные выбранные состояния темы и primary приложения. Состояния «ошибка/подсказка/завершено» различаются текстом, не только цветом. -- Tab/Shift+Tab обходят имя/меню, параметры, CTA, вторичные действия и библиотеку последовательно. Enter активирует сфокусированную кнопку; Escape сначала закрывает popup, затем возвращает на предыдущий экран. Не запускать занятие просто от Enter во время редактирования имени. -- Пустое/загрузка/ошибка занимают те же смысловые области. Ошибки сохранения нельзя скрывать ради красоты; длинные детали раскрываются отдельно. - -## 6. Приёмка по задаче пользователя - -Нужен другой reviewer, не автор этого документа и не автор реализации. Реальные снимки RU 960×600 и 1400×900 в обеих темах, сравнение с библиотекой и партией. Помимо bbox он должен ответить: - -1. Понятно ли без tooltip, сколько ходов изучено и что делать сейчас? -2. Видны ли все три главные кнопки одной группой, одинаковых размеров и на одном baseline? -3. Отсутствуют ли u32MAX, «полуходы», «Итого / Новый», ручное сохранение истории и технические snapshot-сообщения на обычном пути? -4. При фильтре одного репертуара сводка действительно относится к нему? -5. Можно ли прочесть идентифицирующий SAN в отчёте вариантов и понять пользу его выбора? -6. Empty/new/learning/due/all-learnt, длинное имя, загрузка данных и возврат не ломают иерархию? -7. Сохранены ли главные действия при 960×600 без скролла, а библиотека получила заметную долю высоты? -8. Изменение layout не изменило PGN, SRS и существующие конечные ограничения молча? - -«Все надписи поместились» — необходимое, но недостаточное условие. Вердикт должен описывать сценарий, который стал понятнее, и конкретные оставшиеся трудности. diff --git a/docs/design/opening-trainer-concept-2026-11-26.md b/docs/design/opening-trainer-concept-2026-11-26.md deleted file mode 100644 index dcfd6ab..0000000 --- a/docs/design/opening-trainer-concept-2026-11-26.md +++ /dev/null @@ -1,67 +0,0 @@ -# Тренировка дебюта: новая концепция (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 deleted file mode 100644 index fafba24..0000000 --- a/docs/design/opening-trainer-ui-audit-2026-11-26.md +++ /dev/null @@ -1,140 +0,0 @@ -# Тренировка дебюта: аудит интерфейса по реальным снимкам (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 deleted file mode 100644 index c41177b..0000000 --- a/docs/design/opening-trainer-v2-spec.md +++ /dev/null @@ -1,470 +0,0 @@ -# Тренировка дебюта 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/design/opponent-prep.md b/docs/design/opponent-prep.md deleted file mode 100644 index 08164e2..0000000 --- a/docs/design/opponent-prep.md +++ /dev/null @@ -1,532 +0,0 @@ -# Подготовка к сопернику: экран отчёта по дебютам - -Статус: проект дизайнера, 2026-10-28, актуализирован 2026-11-02; ветка `opponent-prep`. **Решения владельца 2026-11-02 (фиксированные): сверка с книгой полностью удалена из подготовки; автоматический поиск ошибок движком после построения отчёта сохраняется без изменений.** Остальные проектные предложения не утверждены. Объём — по решениям владельца (`../research/opponent-prep.md` §9): **только дебюты** — что соперник играет (репертуар по цветам с названиями и первыми ходами) и где в дебютах ошибается (какие ошибки, в каких дебютах, в каких партиях). Без часов, фаз, трендов, стиля, онлайн-партий, досье и Android. Названия дебютов — по таблице `lichess-org/chess-openings`, по-английски при любом языке интерфейса, всегда с первыми ходами; ошибки — движком. - -Опирается на: концепцию аналитика (`../research/opponent-prep.md` §3.1–3.4, §5), техническую часть разработчика (`../research/opponent-prep-tech.md` §2–5, §7: крейт `crates/prep`, дерево на N = 20 полуходов, дедупликация позиций, кэш по позиции, формула времени), `reference.md` (таблица ходов и таблица партий, выбор базы, «Новинка», стек партий «⬅ К партии»), `board-search.md` (полоса Б/Н/Ч, чипы, мини-доска в подсказке, меню ⋯ доски), `large-databases.md` / `library-layout.md` (панель фильтров, шапка таблицы), `narrow-windows.md` (минимум окна 640×480, стопка на экране партии), `player-games.md` (список имён, тексты RU/EN), код `apps/desktop/src/review.rs` (диалог анализа: движок · качество · потоки · память · оценка времени; после первого запуска кнопка стартует сразу — флаг `chosen`), `notation.rs` (`assessment_color`, `assessment_text_color`), `large_db.rs` (группа «Игроки», контекстное меню строки партии), `library.rs` (контекстное меню карточки), `game_view.rs` (шапка партии, `previous` → «⬅ К партии»). - -Размеры — логические точки egui. Макеты: ширина 1400 — 14 точек на знак (100 знаков), 640 — 10 точек на знак (64 знака); значки в ASCII опущены там, где ломают выравнивание. Тексты — по-русски, в §9 — пары «ключ EN → RU» (ключ — английский текст, как везде в `i18n.rs`). Пример данных — Вафин Радель из базы «Гран-при РШШ» (271 партия: 138 белыми, 133 чёрными). - -## 0. Коротко - -1. **Вход — три двери, один диалог.** «Подготовиться к {имя}…» есть в панели фильтров (когда игрок выбран), в контекстном меню строки партии (по одному пункту на каждого игрока) и в меню ☰ / по правой кнопке на названии партии. Все три ведут в один диалог «Подготовка к сопернику» с базой, списком кандидатов с числом партий (похожие имена отдельной группой, объединение написаний — флажками) и цветом. Если имя уже точное (из фильтра с подсказкой или из строки партии), диалог открывается с готовым выбором — остаётся нажать Enter. -2. **Отчёт — отдельный экран на весь размер окна, как экран партии**, со стеком возврата «⬅ К подготовке» из открытой партии. Слева доска выбранной позиции, справа вкладки «Репертуар | Дебюты | Ошибки» и под ними список партий выбранного узла. В правую панель библиотеки (260–380) дерево с шестью колонками не входит; отдельное окно ОС противоречит однооконной компоновке проекта. -3. **Цвет — переключатель в шапке отчёта «Белые | Чёрные | Оба»**, не вопрос при входе. Дерево всегда имеет корни «Белыми · 138» и «Чёрными · 133»; переключатель показывает один корень или оба. По умолчанию — цвет из фильтра библиотеки, если он задан, иначе «Оба». Область работы движка следует переключателю (в диалоге можно поменять). -4. **Движок — автоматически после построения отчёта** (решение владельца, 2026-11-01), без диалога-объяснения. При фактическом старте один раз открывается вкладка «Ошибки»; там полоса «Проверено X из Y позиций» и «Остановить». Отметки появляются по мере оценки; остановка сохраняет сделанное и запрещает автоматический перезапуск, «Продолжить» запускает вручную. Смена глубины или периода снова разрешает автозапуск после перестроения. Параметры — только по «▾». -5. **Ошибка привязана к узлу дерева** (позиция + его ход): отметка `?!`/`?`/`??` стоит у хода в дереве, цветами нотации; «повторяющаяся ошибка» — это узел с отметкой и ≥ 2 партиями. Одна модель данных для дерева, таблицы дебютов и вкладки «Ошибки». -6. **Сводка — сетка без переносов.** Название цвета и правовыравненное число партий — отдельные колонки; счёт сохраняется хотя бы в компактном виде. Счётчики ошибок и процент партий — две соседние колонки с независимо измеряемой шириной; при нехватке места скрываются только «последняя», затем «соперники». Подробности и нулевые состояния — §3.5. - -## 1. Сценарии - -### 1.1. Тренер готовит ученика к завтрашней партии белыми против Вафина - -1. Библиотека, база «Гран-при РШШ» → «Фильтры» → «Игрок: вафин» → подсказка «Вафин Радель · 271». Под строкой цвета появилась кнопка «♟ Подготовиться к Вафин Радель…». -2. Нажал → диалог: база «Гран-при РШШ», кандидат «Вафин Радель · 271» отмечен, ниже «Похожие имена: Вафина Раяна · 10» (не отмечена), цвет «Чёрные» (ученик играет белыми — соперник чёрными). Enter. -3. Экран отчёта сразу показывает «Репертуар» во время сбора. Когда отчёт готов, движок стартует сам, без диалога, и один раз открывает «Ошибки»: «Проверено 412 из 1 306 позиций · ≈ 20 с [Остановить]». Пока идёт анализ, тренер возвращается в «Репертуар» — повторного автопереключения нет. -4. Корень «Чёрными · 133»: «1.e4 — 79 партий», под ним «1…c5 — 79 · 100 %», дальше «2.Nf3 d6 — 39», «2.c3 Nf6 — 17»… Щелчок по «2.c3 Nf6» — доска показывает позицию, снизу 17 партий; в дереве у «6…Nb6» уже видны «?» и «×3» от параллельно работавшего движка. -5. Вкладка «Ошибки»: «Повторяющиеся» — «после 6.Bc4 · 6…Nb6 ? · лучше 6…e6 · ×3 · +1 −2 · Sicilian Defense: Grand Prix Attack». Щелчок — доска показывает позицию до хода с двумя стрелками (сыгранный — оранжевый, лучший — зелёный). Enter — партия на этом ходу; «⬅ К подготовке» возвращает. -6. На доске «⋯ → Играть отсюда…» — ученик разыгрывает позицию после 6…Nb6 против Maia; «Открыть как партию» — тренер записывает линию с комментариями и сохраняет в базу ученика. - -### 1.2. Быстрый взгляд перед туром, не дожидаясь движка - -Турнирная база открыта, таблица партий. Правая кнопка на строке «Кузнецов — Вафин» → «Подготовиться к Вафин Радель…» → Enter в диалоге → отчёт за секунду. Движок сам начал проверку на вкладке «Ошибки», но тренер сразу открывает «Дебюты»: «Белыми: Sicilian Defense 37 % · French Defense 15 % · Caro-Kann 13 %…», раскрывает сицилианскую — варианты с первыми ходами и счётом. Ждать движок для вывода «он всегда 1.e4, на 1…c5 чаще 2.Nf3, но бывает Гран-при» не нужно. - -### 1.3. Повторный отчёт после обновления базы - -База онлайн-партий дописалась новыми партиями. Вход тот же; сбор дерева — мгновенно; оценки прежних позиций — из кэша. После перестроения движок автоматически проверяет 84 новые позиции: вкладка «Ошибки» показывает «Проверено 12 из 84 позиций · ≈ 4 с [Остановить]». - -## 2. Точка входа - -### 2.1. Три двери - -| Где | Элемент | Что передаёт в диалог | -|---|---|---| -| **Панель фильтров**, группа «Игроки», под строкой цвета («любым цветом · белыми · чёрными») | кнопка «♟ Подготовиться к {name}…» (`♟ Prepare against {name}…`); видна, когда игрок выбран из подсказки (`NameFilter.exact`); при свободном тексте без подсказки — кнопка «♟ Подготовиться к сопернику…» без имени (диалог покажет кандидатов по этому тексту). В узком окне панель — выдвижная, кнопка та же | база — текущая; игрок — `exact`; цвет — из фильтра («белыми» → Белые, «чёрными» → Чёрные, иначе Оба); остальные активные фильтры (годы, Эло, турнир) — как условия отчёта (§2.4) | -| **Контекстное меню строки таблицы партий** (`large_db.rs:2214`), после «Открыть» | два пункта: «Подготовиться к {white}…», «Подготовиться к {black}…» (имя в тексте пункта, без склонения). Один пункт, если имена совпадают или одно пустое | база — текущая; игрок — точное имя из записи; цвет — Оба | -| **Экран партии**: меню ☰ нижней панели и правая кнопка по названию партии в шапке | подменю «Подготовиться к сопернику ▸» с двумя пунктами-именами; по правой кнопке на названии — те же два пункта сразу | база — база партии (`source`); у партии без базы (вставлена, новая) — база не выбрана, диалог просит выбрать; игрок — точное имя; цвет — Оба | - -Клавиша в библиотеке: `Ctrl+Shift+P` — то же, что кнопка панели (с игроком из фильтра, если выбран; иначе пустой диалог). На экране партии клавиши нет. - -Почему не кнопка в шапке таблицы и не карточка на полке: вход всегда начинается с человека — имя либо уже в фильтре, либо в строке партии, либо в шапке партии. Отдельная кнопка «без имени» заставила бы искать игрока второй раз. - -### 2.2. Диалог «Подготовка к сопернику» - -Модальное окно 520 × по содержимому (как диалог анализа, `egui::Modal`). - -``` -┌ Подготовка к сопернику ────────────────────────────────────────┐ -│ База [Гран-при РШШ · 33 640 ▾] │ -│ Игрок [вафин ] × │ -│ ☑ Вафин Радель 271 партия │ -│ ☐ Vafin, Radel 6 партий │ -│ Похожие имена — скорее всего, другие люди │ -│ ☐ Вафина Раяна 10 партий │ -│ Отмечено: Вафин Радель, Vafin, Radel · 277 партий │ -│ │ -│ Цвет (•) Оба ( ) Белые — 138 ( ) Чёрные — 133 + 6 │ -│ [Отмена] [▌Открыть отчёт▐]│ -└────────────────────────────────────────────────────────────────┘ -``` - -- **База** — список баз полки (имя · число партий), как «База» в Справочнике; по умолчанию та, откуда пришли. Смена базы перезапрашивает кандидатов. База, которая ещё не открыта, открывается тут же со спиннером в строке («Открываю базу…»). -- **Игрок** — поле с тем же механизмом, что «Игрок» панели фильтров (`suggest_players`, слова без учёта регистра и порядка; точки в инициалах убираются — правка `words()`, `opponent-prep-tech.md` §2.2). Но список кандидатов **не выпадающий, а постоянный** под полем, с флажками: до 8 строк, дальше прокрутка. Первая строка отмечена сама, если совпадение по всем словам ровно одно; иначе ничего не отмечено, кнопка «Открыть отчёт» неактивна с подсказкой «Отметьте игрока». -- **Похожие имена** — отдельная группа под слабым заголовком «Похожие имена — скорее всего, другие люди»: имена, которые совпадают по началу слова, но не по слову целиком («Вафин» ⊂ «Вафина»), или отличаются одной буквой. Никогда не отмечаются сами. Автоматической склейки нет (решение исследования §5.7). -- **Объединение написаний** — просто несколько флажков. Строка «Отмечено: … · N партий» показывает сумму. Выбор запоминается на базу и имя (в данных программы, как просмотренные партии): в следующий раз те же флажки стоят сами. -- **Цвет** — радио «Оба / Белые — N / Чёрные — N» с числом партий; по умолчанию из входа (§2.1). Это начальное положение переключателя отчёта, его меняют в отчёте в любой момент. -- Enter — «Открыть отчёт», Esc — отмена. Фокус при открытии: в поле «Игрок», если игрок не задан; иначе на «Открыть отчёт». - -Диалог показывается всегда, даже когда всё известно: в нём видно число партий по цветам и похожие имена — то, из-за чего отчёты врут. Это один Enter. - -### 2.3. Что происходит после «Открыть отчёт» - -Экран отчёта открывается сразу. Сбор линий, дерева и имён — в фоне (`Background::spawn`): для сотен партий сбор заканчивается до первого кадра; для фильтра по Mega — секунды с прогрессом «Собираю партии… 37 %» на месте дерева. После готовности отчёта автоматически стартует поиск ошибок движком (§4), если все нужные позиции ещё не оценены. - -### 2.4. Условия из библиотеки - -Если при входе из панели фильтров были активны другие фильтры (годы, Эло соперников, турнир), отчёт строится **по отфильтрованной выборке**, и это видно в шапке отчёта чипами без `×`: «Годы: 2025–2026 · Эло ≥ 1700». Так тренер получает «последний год» и «против сильных» без новых элементов управления в отчёте. Убрать условие — вернуться в библиотеку и снять фильтр. Вход из строки партии и из шапки партии — всегда все партии игрока. (Вопрос 11.1.) - -## 3. Экран отчёта - -### 3.1. Где живёт - -| Вариант | За | Против | -|---|---|---| -| **А. Отдельный экран на всё окно, как экран партии** (шапка «⬅ Библиотека», стек возврата) | место для доски + дерева в 6 колонок + списка партий; партия из отчёта открывается поверх со стеком «⬅ К подготовке» — механизм уже есть (`previous`, `reference.md`); состояние библиотеки не трогается | ещё один тип экрана (третий после библиотеки и партии) | -| Б. Третий сегмент в библиотеке `[Фильтры │ Доска │ Подготовка]` | рядом с фильтром игрока, нулевой переход | правая часть — 260–480 точек: дерево с колонками не помещается; таблица партий библиотеки показывает все партии базы, а отчёту нужен свой список по узлу; в узком окне (< 880) панель и так идёт по очереди с таблицей | -| В. Вкладка в правой панели экрана партии, как «Справочник» | та же механика «таблица ходов + партии» | отчёт — не про текущую партию, а про игрока; открывать пустую партию, чтобы посмотреть отчёт, странно; панель 370–700 тесна для дерева + дебютов + ошибок | -| Г. Отдельное окно ОС | можно держать рядом с партией | в проекте одно окно; viewport-ы egui тянут за собой отдельные настройки, фокус, тайлинг; на ноутбуке второе окно некуда ставить | - -**Рекомендация — А.** Шапка — как у партии: «⬅ Библиотека», название, справа «⚙ Настройки». `Ctrl+W` — назад в библиотеку, к той же базе и фильтрам. Отчёт живёт, пока его не закрыли; повторный вход для того же игрока (та же база, те же написания) возвращает его как был (вкладка, узел, прокрутка, результаты движка). - -### 3.2. Компоновка, 1400 × 1000 - -``` -⬅ Библиотека │ Подготовка к сопернику: Вафин Радель · 271 партия · 01.2026 – 10.2026 · Гран-при РШШ ⚙ Настройки -[Белые │ Чёрные │▐ Оба ▌] Период [Все партии ▾] Дебют [10 ходов ▾] [Ошибки найдены ▾] -Белыми │ 138 │ 77 % (+103 =8 −27) │ соперники ≈ 1612 │ последняя 18.10.2026 │ 14 ?! · 11 ? · 5 ?? │ в 17 % партий -Чёрными │ 133 │ 58 % (+70 =14 −49) │ соперники ≈ 1655 │ последняя 18.10.2026 │ 30 ?! · 10 ? · 13 ?? │ в 71 % партий -──────────────────────────────────┬───────────────────────────────────────────────────────────────────── - ○ Ход чёрных · после 3.Bb5 │ [▐Репертуар▌] Дебюты Ошибки Ветви от [3 ▾] партий · Раскрыть всё -┌────────────────────────────┐ │ Ход Дебют Партий % Счёт Последняя -│ │ │ ▾ Белыми 138 77 % ▕███▒░▏ 18.10.2026 -│ │ │ ▾ 1.e4 136 99 77 % 18.10.2026 -│ │ │ ▾ 1…c5 Sicilian Defense · B20 50 37 70 % 18.10.2026 -│ доска 380 │ │ ▾ 2.Nf3 33 66 73 % 12.10.2026 -│ │ │ ▾ 2…Nc6 16 48 69 % 12.10.2026 -│ │ │ ▌3.Bb5 Sicilian Defense: Nyezhmetdinov-Ros… · B30 14 88 71 % 12.10.2026 -│ │ │ ▸ 3…g6 9 64 67 % 12.10.2026 -│ │ │ ▸ 3…e6 4 29 75 % 03.09.2026 -└────────────────────────────┘ │ ▸ другие ходы (1) 1 - 1.e4 c5 2.Nf3 Nc6 3.Bb5 │ ▸ 2…d6 12 36 75 % 05.10.2026 - Sicilian Defense: Nyezhmetdinov- │ ▸ 2.Nc3 17 34 65 % 18.10.2026 - Rossolimo Attack · B30 │ ▸ 1…e6 French Defense · C00 21 15 81 % 18.10.2026 - [Открыть как партию] [⋯] │ ▸ 1…c6 Caro-Kann Defense · B10 18 13 83 % 27.09.2026 - ├───────────────────────────────────────────────────────────────────── - │ Партии · после 3.Bb5 · 14 ✕ - │ Белые Эло Чёрные Эло Рез. Дата Дальше Турнир - │ Вафин Радель 1887 Ширшов С. 1802 1-0 12.10.2026 3…g6 4.O-O Bg7 Блиц 12, до 13 - │ Вафин Радель 1860 Гадисов М. 1744 ½-½ 03.09.2026 3…e6 4.O-O Nge7 Рапид 9, до 13 -``` - -Высоты: шапка 36; строка переключателей 32; сводка 2 строки по 20 (при «Белые» или «Чёрные» — одна строка выбранного цвета, вторая слабым); разделитель. Левая колонка — доска `min(H_панели − 120, 420)`, не меньше `BOARD_MIN` 220, ширина колонки = доска + 24; правая — остальное, не уже 560. Правая колонка делится по вертикали: вкладки сверху, список партий снизу, граница перетаскивается (по умолчанию список — 35 %, не меньше 4 строк). - -### 3.3. Шапка - -- Название: «Подготовка к сопернику: {name}» (`Preparing against {name}`); при нескольких написаниях — первое отмеченное и «+1 написание» (`+1 spelling`) с подсказкой-списком. Дальше слабым: число партий, период «MM.YYYY – MM.YYYY» (по датам партий; без дат — пусто), имя базы; чипы условий из библиотеки (§2.4). Сокращение в узком окне — как у шапки партии (`narrow-windows.md` §3.4): «⬅ Библиотека» и имя видны всегда, остальное с «…». -- «⚙ Настройки» — общие настройки программы, как везде. - -### 3.4. Строка переключателей - -Порядок слева направо: **цвет | период | глубина | кнопка доски в низком окне | движок**. - -- **Цвет** — сегментный переключатель `[Белые │ Чёрные │ Оба]` (`White · Black · Both`), как `[Фильтры │ Доска]`. Действует на дерево (какие корни показаны), таблицу дебютов, вкладку «Ошибки», список партий и на область движка. Сводка показывает оба цвета всегда (строка другого цвета слабым). -- **Период** — существующий список выбора партий. Смена перестраивает отчёт, после чего движок автоматически проверяет недостающие позиции новой конфигурации. -- **Дебют: 10 ходов ▾** — глубина дерева и анализа: 6 / 10 / 15 ходов (12 / 20 / 30 полуходов, по умолчанию 20 — `opponent-prep-tech.md` §3.1). Смена перестраивает дерево и меняет число позиций для движка; после перестроения движок запускается автоматически. -- **«♙ Доска»** — только в стопке при `H < 720`, между глубиной и контролом движка; открывает выдвижную доску по §6. В остальных компоновках кнопки нет. -- **Контрол движка** — §4. Во время работы на его месте компактная полоса прогресса и «Остановить»; после — строка состояния. - -### 3.5. Сводка - -Две строки `egui::Grid`, по одной на цвет; при выбранном одном цвете вторая строка остаётся слабой. Порядок колонок: **название цвета | партии | счёт | соперники | последняя | счётчики ошибок | процент партий с ошибками**. - -- **Название и число партий — отдельные колонки.** Число выравнивается по правому краю, поэтому разная длина названий не сдвигает следующие показатели. -- **Счёт** — очки игрока в процентах; +/=/− — с его точки зрения. Полный вид: `77 % (+103 =8 −27)`; компактный: `77 %`. При сокращении процент счёта сохраняется. -- **Ошибки — две соседние колонки.** В первой цветные счётчики в порядке `30 ?! · 10 ? · 13 ??`, во второй — `в 71 % партий`. Процент стоит на одной X в обеих строках независимо от разрядности и числа счётчиков. Ширины counts и percent рассчитываются независимо по реальному `Label`, с фактическим `gap = 4`; нельзя измерять их как одну приблизительную строку в общем `horizontal`. -- **Нули.** Типы с нулевым счётчиком пропускаются: например, `10 ? · 13 ??`. Если у одного цвета все три счётчика равны нулю, в его строке только «нет ошибок», а ячейка процента пустая. Если ошибок нет у всех показанных цветов, отдельная колонка процента не создаётся. -- **Скрытие при нехватке ширины:** сначала «последняя», затем «соперники». Название, число партий, счёт и ошибки не скрываются; счёт переходит в компактный вид. -- **Стопка (stacked):** ошибки в сводке не дублируются — они показываются только на вкладке «Ошибки». Остальные колонки следуют тем же правилам сокращения. - -### 3.6. Вкладка «Репертуар» — дерево - -Та же таблица, что таблица ходов Справочника (полосатые строки, обычный шрифт), но с отступами дерева. - -| Колонка | Что | Ширина | -|---|---|---| -| Ход | `▾`/`▸` + отступ 14 на уровень + SAN с номером («3.Bb5», «2…Nc6»); ход игрока — обычным, ход соперника — слабым; ⤳ после хода — к позиции приходили и другим порядком (подсказка — порядки) | гибкая, ≥ 180 | -| Дебют | имя по таблице у **первого** узла, где оно появилось (глубже — пусто, чтобы не повторять); «Family: Variation» + слабым ECO; сокращается с «…», полное — в подсказке | гибкая, ≥ 160, прячется второй | -| Партий | число партий игрока через эту позицию | 56 | -| % | доля от родителя | 40 | -| Счёт | очки игрока в процентах + полоса Б/Н/Ч 60 (как на доске поиска; подсказка «+10 =1 −3») | 110 | -| Последняя | дата последней партии (дд.мм.гггг; без дат — год или «—») | 84 | -| (после движка) | у хода игрока — значок отметки `?!`/`?`/`??` (пилюля как в нотации) сразу после SAN в колонке «Ход» и в подсказке «Ошибка: лучше 6…e6 (оценка 0,0 → −1,2) · в 3 партиях» | — | - -- **Корни** — «Белыми · 138» и «Чёрными · 133» (`As White`, `As Black`); при переключателе «Белые» виден один корень, раскрытый. Чередование уровней: под корнем «Белыми» первый уровень — его ходы, второй — ответы соперников, и так далее. -- **Раскрытие по умолчанию**: до узлов с ≥ 5 партиями включительно, но не глубже 6 полуходов; остальное свёрнуто. «Раскрыть всё» / «Свернуть» — ссылки в строке над таблицей (действуют на выбранный узел, без выбора — на корни). -- **Ветви от N партий** — выпадающий 2 / 3 / 5 (по умолчанию 3; «грубая → тонкая» детализация ChessBase). Дети с меньшим числом партий сворачиваются в одну строку «другие ходы (N)» (`other moves (N)`) в конце списка детей; раскрывается как узел и показывает их. -- **Выделение** — одна строка (полоса ▌ слева, как в таблицах библиотеки). Выбранный узел = позиция на доске + заголовок списка партий «Партии · после 3.Bb5 · 14». Щелчок по уже выбранному — ничего (не снимает). Щелчок по `▾/▸` — раскрыть/свернуть без смены выделения. Двойной щелчок — раскрыть/свернуть. -- **Мало партий**: в узлах с < 5 партиями «%», «Счёт» и полоса — слабым цветом, подсказка «Мало партий — проценты ненадёжны» (`Few games: percentages are unreliable`). -- **Переходы**: узел — по порядку ходов, статистика — по позиции (как рекомендует разработчик, §3.1 техчасти): два узла с одной позицией показывают одинаковые числа и ⤳; подсказка перечисляет порядки. -- Высота — вся вкладка, прокрутка; выбранный узел прокручивается в видимую область при навигации с клавиатуры. - -### 3.7. Вкладка «Дебюты» — таблица - -``` - Дебют Первые ходы Партий % Счёт Последняя Ошибок - ▾ Sicilian Defense B20–B99 1.e4 c5 50 37 70 % ▕██▒░▏ 18.10.2026 3 ? · 1 ?? - Nyezhmetdinov-Rossolimo Attack B30 1.e4 c5 2.Nf3 Nc6 3.Bb5 14 28 71 % 12.10.2026 1 ? - Grand Prix Attack B23 1.e4 c5 2.Nc3 Nc6 3.f4 11 22 64 % 18.10.2026 2 ? · 1 ?? - Open Sicilian B32–B99 1.e4 c5 2.Nf3 … 3.d4 19 38 74 % 05.10.2026 - без названия глубже 6 12 67 % 21.08.2026 - ▸ French Defense C00–C19 1.e4 e6 21 15 81 % 18.10.2026 2 ?! - ▸ Caro-Kann Defense B10–B19 1.e4 c6 18 13 83 % 27.09.2026 -``` - -- Две ступени: **семейство** (часть имени до двоеточия) → **варианты** (самое глубокое имя линии). Партия считается в одном варианте. Варианты без имени глубже семейства — строка «без названия глубже» (`no deeper name`). -- Колонки: Дебют (имя, у варианта — без повторения семейства), ECO слабым (у семейства — диапазон), Первые ходы (линия до именованной позиции, слабым, сокращается с «…» посередине — первые и последние ходы важнее середины), Партий, % (семейство — от цвета, вариант — от семейства), Счёт с полосой, Последняя, Ошибок (после движка: счётчики цветом отметок; пусто = ошибок нет; «…» пока считается). -- При переключателе «Оба» — колонка «Цвет» первой (`♙`/`♟` + «белыми / чёрными»), и семейства одного имени за разные цвета — разные строки. Сортировка по умолчанию — по числу партий; заголовки сортируют (Счёт, Последняя, Ошибок). -- Щелчок по строке — доска показывает именованную позицию, список партий — партии дебюта/варианта («Партии · French Defense · 21»). Двойной щелчок по семейству — раскрыть. Ссылка в подсказке строки «показать в дереве» — вопрос 11.6; в первой версии нет. - -### 3.8. Вкладка «Ошибки» - -При автозапуске эта вкладка открывается сама (§4). Во время работы её первая строка — полный `egui::ProgressBar` «Ищу ошибки: {done} из {total} позиций · ≈ {time}» с кнопкой «Остановить»; список результатов растёт ниже. После ручной остановки здесь же — «Проверено {done} из {total}» и «Продолжить». Пример завершённого состояния в стопке, где сводка по цвету находится на этой вкладке: - -``` - Ошибки найдены · Stockfish 19 · 1 306 позиций [▾] - Чёрными: неточностей 14 · ошибок 11 · зевков 5 — в 24 партиях из 133 (18 %) - - Повторяющиеся ошибки — одна и та же позиция, тот же ход - Позиция Сыграл Лучше × Счёт Дебют - ▸ после 6.Bc4, ход чёрных 6…Nb6 ? 6…e6 3 +1 −2 Sicilian Defense: Grand Prix Attack · B23 - ▸ после 4…Nf6, ход белых 5.e5 ?? 5.Nc3 2 +0 −2 Caro-Kann Defense: Advance Variation · B12 - ▸ после 7.Qd2, ход чёрных 7…O-O ?! 7…Nxd4 2 +1 −1 Sicilian Defense: Open · B56 - - По дебютам - ▾ Sicilian Defense: Grand Prix Attack · B23 11 партий · 2 ? · 1 ?? - 6…Nb6 ? лучше 6…e6 Кузнецов — Вафин 0-1 18.10.2026 - 6…Nb6 ? лучше 6…e6 Ширшов — Вафин 1-0 12.10.2026 - 9…f5 ?? лучше 9…Be7 Гадисов — Вафин 1-0 03.09.2026 - ▸ Sicilian Defense: Nyezhmetdinov-Rossolimo Attack · B30 14 партий · 1 ? - ▸ French Defense · C00 21 партий · 2 ?! -``` - -- **Повторяющиеся** — узлы дерева с отметкой и ≥ 2 партиями; порядок: по числу партий, затем по тяжести. Раскрытие строки показывает партии (как в «По дебютам»). «Счёт» — результат игрока в этих партиях. -- **По дебютам** — по вариантам (самое глубокое имя), внутри — ошибки по партиям: ход с отметкой, «лучше …» (первый ход лучшей линии, подсказка — линия и оценки), партия «Белые — Чёрные», результат, дата. Сортировка семейств — по числу ошибок с весом (?? = 3, ? = 2, ?! = 1), чтобы наверху было самое больное. Неточности показываются, но считаются слабее; выключатель «показывать неточности» — вопрос 11.4. -- **Щелчок** по строке ошибки — доска показывает позицию **до** хода, стрелки: сыгранный ход цветом отметки, лучший — зелёный (как стрелка лучшего хода на экране партии); под доской линия до позиции и строка «6…Nb6 ? — лучше 6…e6 · 0,0 → −1,2». **Enter / двойной щелчок** — партия на этом ходу (у повторяющейся — первая по дате, раскрытие даёт выбрать). -- Ошибки, попавшие за пределы глубины дебюта (строка «Дебют: 10 ходов»), не ищутся — подсказка строки прогресса и статуса указывает эту глубину. -- В стопке сводка ошибок по цветам показывается здесь, а не в §3.5; при «Оба» — два блока. В списках при «Оба» — колонка «Цвет». - -### 3.9. Доска - -- Виджет `board.rs`, без ввода ходов (щелчок по фигуре ничего не делает; ввод — через «Открыть как партию»). Ориентация — **по цвету игрока** (его фигуры снизу: смотрим его глазами; «Оба» — по цвету выбранного корня); `F` переворачивает, выбор держится до закрытия отчёта. -- Над доской — индикатор очереди хода и «после 3.Bb5» (как в панели доски поиска). Под доской — линия ходов до узла (поток токенов, щелчок по ходу — доска на этот ход, выделение в дереве не меняется), под ней имя дебюта + ECO для этой позиции (слабым), затем кнопки «Открыть как партию» (`Open as a game`) и `⋯`. -- Меню `⋯`: «Играть отсюда…» (`Play on from here…`, тот же диалог, что на экране партии; цвет по умолчанию — сторона на ходу), «Найти позицию в базе» (`Ctrl+Shift+F`, доска поиска библиотеки с этой линией), «Копировать FEN», «Копировать ходы (PGN)». -- Наведение на строку дерева (не выбранную) — синяя стрелка **следующего хода** на текущей доске, если наведённый узел — ребёнок выбранного; иначе ничего (чужая позиция — чужие стрелки). Наведение на строку списка партий — стрелка хода этой партии из позиции (как в Справочнике). -- Мини-доска 160×160 в подсказке — только в строках «Повторяющиеся ошибки» (позиция до хода с двумя стрелками): быстро пробежать список, не щёлкая. В дереве мини-досок нет — рядом большая. - -### 3.10. Список партий - -Таблица как в Справочнике: Белые · Эло · Чёрные · Эло · Рез. · Дата · Дальше · Турнир; плюс после движка колонка **Ошибки** (`Errors`): отметки его ходов в дебюте этой партии «7.? 12.??» (номер хода + значок цветом; пусто — без ошибок; «…» — ещё считается). Игрок — полужирным в своей колонке. - -- Заголовок: «Партии · 271» без выбора; с узлом — «Партии · после 3.Bb5 · 14 ✕»; с дебютом — «Партии · French Defense · 21 ✕»; с ошибкой — «Партии · 6…Nb6 ? · 3 ✕». `✕` снимает выбор (все партии цвета). При переключателе «Оба» — все партии игрока. -- Сортировка по умолчанию — новые сверху; заголовки сортируют. -- **Двойной щелчок / Enter** — партия в обычном экране **на ходе выбранного узла** (у ошибки — на ходе с ошибкой; без узла — на первом ходе). В шапке партии «⬅ К подготовке» (`⬅ Back to preparation`), `Ctrl+W` возвращает к отчёту как был. Отчёт остаётся в стеке так же, как партия из Справочника (`reference.md`, «Открытая из списка партия не закрывает текущую»). -- Открытая партия — обычная: анализ партии `Shift+A`, живой движок, комментарии. Отметки отчёта в нотацию не переносятся (разные кэши; вопрос 11.5). -- В узкой таблице колонки прячутся по очереди: Турнир, Дальше, Дата → Год, Эло (в ячейку имени слабым) — как в `board-search.md` §2.7. - -## 4. Движок: автоматический поиск ошибок в дебютах - -### 4.1. Автозапуск — решение владельца, 2026-11-01 - -Задача состояния — сразу начать оценку дебютных позиций текущими параметрами, оставив пользователю видимый прогресс и возможность остановить работу. - -- После построения отчёта поиск ошибок стартует **автоматически**, без диалога-объяснения и без требования сначала нажать «Найти ошибки». Используются текущие сохранённые параметры движка; флаг «параметры однажды выбраны» не является условием запуска. -- Во время сбора пользователь видит «Репертуар». При фактическом старте движка экран **один раз** переключается на «Ошибки» — это уже принятое поведение реализации (§12). Дальше пользователь может уйти на «Репертуар» или «Дебюты»; работа продолжается, а вкладка сама больше не переключается. -- Если все позиции уже есть в кэше, процесс не запускается и автопереключения вкладки нет: повторный вход сохраняет вкладку по §3.1, а «Ошибки» содержат готовый статус и результаты. Нулевое число партий — состояние §5, фиктивный прогресс и запуск процесса не нужны. -- Смена глубины или периода снова разрешает автозапуск: сначала завершается старый job и сохраняются его оценки, затем отчёт перестраивается, после чего движок автоматически проверяет недостающие позиции новой конфигурации. Это действует и после предыдущей ручной остановки. -- Уход/возврат на экран и открытие параметров автозапуск не вызывают. Ручная остановка запрещает автоматический перезапуск этой конфигурации, в том числе при повторном входе в ту же сохранённую подготовку; сброс запрета — только смена глубины/периода либо явное «Продолжить». - -### 4.1.1. Допустимые ошибки игрока (решение владельца, 2026-11-05) - -В результат входят только ошибки изучаемого игрока **до первой ошибки его соперника** -в каждой партии. Учитываются существующие категории ?!, ? и ??; новые пороги не вводятся. -Более ранние ошибки самого игрока остаются. Сыгранный лучший ход движка, как и раньше, -ошибкой не считается. До проверки предшествующих ходов соперника поздняя ошибка игрока -не показывается. Это фильтр списка ошибок, повторов и их агрегатов, а не дерева репертуара. -При одинаковой позиции из разных партий условие проверяется отдельно по каждой истории. -Старые отчёты пересчитываются из сохранённых оценок при загрузке. - -### 4.2. Контролы и параметры - -- На вкладке «Ошибки» во время работы первая строка — `egui::ProgressBar`: `Ищу ошибки: 812 из 1 306 позиций · ≈ 20 с` и рядом текстовая **«Остановить»**. Это основной, самый полный индикатор. Компактный дубль с теми же числами и Stop остаётся в строке переключателей, чтобы состояние было видно с других вкладок. -- Кнопка **«▾»** открывает существующий `engine_dialog` только по явному запросу — для просмотра/смены параметров и оценки времени. Он не появляется перед первым автозапуском, после смены глубины/периода или перед «Продолжить». Состав самого диалога эта правка не расширяет. -- Оценка времени по-прежнему считается по дедуплицированным позициям без кэша: `позиции_без_кэша × узлы / (nps_на_поток × потоки)`; одинаковые позиции считаются один раз. Оценка нужна в прогрессе и в диалоге параметров, но не задерживает старт. -- Если движок не установлен, автозапуск не открывает обязательный диалог и не начинает загрузку сам. На «Ошибках» видно «Сначала добавьте движок» и существующее действие скачивания Stockfish (`engine-download.md`). После явной установки существующий `start_after_engine` запускает поиск без дополнительного диалога-объяснения. - -### 4.3. Работа, остановка и ручное продолжение - -- Отметки появляются **по мере оценки** в дереве, таблице дебютов, списке партий и на вкладке «Ошибки» (строка «Повторяющиеся» пересортировывается не чаще раза в секунду; пока курсор над списком — не пересортировывается). Порядок оценки — по дереву в ширину: частые позиции и повторяющиеся ошибки видны первыми. -- **«Остановить»** сохраняет все уже полученные оценки. Вкладка показывает `Проверено 812 из 1 306 позиций · [Продолжить ≈ 12 с]`; частичные счётчики имеют подсказку «из проверенных позиций». Подсказка Stop: «Остановить поиск ошибок; уже оценённые позиции сохранятся». -- **«Продолжить»** — ручной запуск только недостающих позиций, без диалога и без потери кэша. Оно доступно и на «Ошибках», и в строке переключателей. После остановки никакой таймер, возврат на экран или смена вкладки не запускают движок сами. -- Один engine job на всю программу: пока идёт поиск ошибок, «Анализ партии» в открытой из отчёта партии неактивен с подсказкой «Идёт поиск ошибок в дебютах — дождитесь или остановите его в отчёте»; живой анализ (`L`) ставится на паузу. И наоборот: автозапуск подготовки ждёт доступности движка, а не создаёт конкурирующий процесс. Если ожидание требуется реализацией, на «Ошибках» показывается «Ожидаю освобождения движка…», без повторяющихся попыток запуска каждый кадр. -- Уход с экрана отчёта работу **не прерывает**: при возврате — актуальный прогресс, частичный результат после Stop либо готовый результат. Выход из программы во время работы — вопрос «Идёт поиск ошибок в дебютах. Выйти и остановить?»; сделанное сохранено в кэше. -- В узком окне полный прогресс и текстовая «Остановить» остаются на «Ошибках»; в строке переключателей допустимо только сокращение текста до `{done}/{total}` с полной подсказкой. Автозапуск не меняет существующие правила компоновки. - -### 4.4. Завершение, сбой и смена условий - -- После завершения прогресс заменяется на `Ошибки найдены · Stockfish 19 · 1 306 позиций`; ниже — полные списки ошибок и сводка. Процесс завершён, кнопки Stop нет, автоматического повторного прохода нет. «▾» остаётся доступна для параметров. -- Сбой движка — строка с предупреждением, «Подробности» и **«Повторить»**, как у анализа партии. Повтор только ручной; уже полученные оценки сохраняются. Ошибка не маскируется под «ошибок нет». -- Смена глубины/периода останавливает job старой конфигурации, сохраняет сделанное и запускает сценарий §4.1 для новой. Результаты старого job не применяются к новому отчёту. -- Кэш по позиции — `~/.cache/chesspenguin/prep/` (техчасть §7.3). При повторном входе с полным кэшем показывается готовый результат без нагрузки; с частичным кэшем после ручной остановки — состояние «Проверено X из Y» и ручное «Продолжить», а не автозапуск. - -## 5. Состояния - -| Состояние | Что видно | -|---|---| -| **Партий мало** (< 10 выбранным цветом) | под сводкой строка предупреждения: «Партий мало (7) — проценты и счёт ненадёжны» (`Few games (7): percentages and scores are unreliable`); проценты в узлах с < 5 партиями слабым (§3.6) | -| **Нет партий выбранным цветом** | дерево/таблица: по центру «Чёрными партий нет. Белыми — 138 · [Показать белые]» (`No games as Black. As White — 138 · Show White`); корень «Чёрными · 0» в режиме «Оба» показывается слабым без раскрытия; движок для пустого выбранного цвета не запускается, при «Оба» проверяется имеющийся цвет | -| **Нет партий вовсе** (условия библиотеки отсекли всё) | «Партий по условиям нет: {чипы}. [Открыть без условий]»; движок не запускается, прогресса `0/0` нет | -| **Сбор идёт** (Mega-фильтр) | на месте дерева «Собираю партии… 37 %» с полосой и «Отмена» (возвращает в библиотеку); шапка уже показывает имя; движок ещё не запущен | -| **Движок ещё не запущен** | штатно это только ожидание готовности отчёта или освобождения движка: на «Ошибках» соответствующий статус, без диалога. При невозможности автозапуска — причина и ручное действие; приглашение с обязательным первым диалогом больше не используется | -| **Движок считает** | на «Ошибках» полная полоса «Ищу ошибки: 812 из 1 306 позиций · ≈ 20 с [Остановить]», в строке переключателей компактный дубль; отметки и списки растут по мере оценки | -| **Движок остановлен** | «Проверено 812 из 1 306 позиций · [Продолжить]»; частичные счётчики с подсказкой «из проверенных позиций»; сам не перезапускается | -| **Готово** | строка состояния §4.4, Stop нет, повторного автозапуска нет | -| **Готово, ошибок нет** | вкладка «Ошибки»: «В первых 10 ходах ошибок не нашлось (неточностей 3). [Глубже: 15 ходов]» | -| **Нет движка** | на «Ошибках» «Сначала добавьте движок» и явное действие скачать Stockfish (`engine-download.md`); обязательный диалог и автоматическая загрузка не открываются | -| **База изменилась** (дописана, файл заменён) | отчёт пересобирается при возврате, оценки берутся из кэша; если ручная остановка не запретила автозапуск, новые позиции проверяются автоматически, иначе показывается «Продолжить» | -| **Игрок — несколько написаний** | «+1 написание» в шапке с подсказкой; в списке партий имя — как в записи | -| **Партии без дат** | «Последняя» — «—», период в шапке пропущен | -| **Партия с FEN или Chess960** | не входит в дерево; в подсказке счётчика шапки «не учтены: с заданной позиции — 2» | - -## 6. Узкие и низкие окна - -Правило `narrow-windows.md` §0: компоновку выбирает размер окна. `W`, `H` — под шапкой отчёта. - -- **Рядом** (как в §3.2), когда `W ≥ BOARD_MIN(220) + 24 + 560` = **804** и `H ≥ 600`: доска `min(H − 120, 420, W − 584)`, но не меньше 220; правая колонка — остальное. -- **Стопка** (`W < 804` или `H < 600`): верхний блок — доска 240 слева, справа от неё линия ходов, имя дебюта и кнопки (вертикально); под ним вкладки и список партий. При `H < 720` доска в стопке скрыта по умолчанию: в строке переключателей кнопка «♙ Доска» (`Board`) открывает её поверх правой нижней части как выдвижную панель 264 × 300 (с тенью, как фильтры в узком окне), закрытие — та же кнопка, `Esc` или щелчок вне. Так при 640 × 480 дереву остаётся ≈ 300 точек высоты — 12 строк. - -``` -640 × 1000 (стопка) 640 × 480 (доска скрыта) -⬅ Библиотека │ Вафин Радель · 271 · … ⚙ ⬅ Библиотека │ Вафин Радель… ⚙ -[Белые│Чёрные│Оба] [Все ▾] [10 х. ▾] [▶ Ошибки] [Белые│Чёрные│Оба] [Все ▾] [10 х.] [♙] [▶] -Чёрными 133 · 58 % Чёрными 133 · 58 % -┌──────────┐ ○ Ход белых · после 2…Nf6 [Репертуар] Дебюты Ошибки -│ │ 1.e4 c5 2.c3 Nf6 Ход Партий % Счёт -│ доска 240│ Sicilian Defense: Alapin · B22 ▾ Чёрными 133 58 % -│ │ [Открыть как партию] [⋯] ▾ 1.e4 79 59 60 % -└──────────┘ ▾ 1…c5 79 100 60 % -[Репертуар] Дебюты Ошибки ▸ 2.Nf3 39 49 63 % -Ход Дебют Партий % Счёт ▌2.c3 17 22 53 % -▾ Чёрными 133 58 % ────────────────────────────── - ▾ 1.e4 79 59 60 % Партии · после 2.c3 · 17 ✕ - ▾ 1…c5 Sicilian · B20 79 100 60 % Белые Чёрные Рез. Год -``` - -- **Строка переключателей** — порядок и наличие кнопки доски определяются §3.4; подписи глубины и периода сокращаются по измеренной ширине, компактный движок — по §4.3. Полные прогресс движка и Stop всегда доступны на «Ошибках». Отдельная задача 30 о пересечении контролов этим обновлением не закрывается. -- **Сводка** — при `W < 804` одна строка выбранного цвета (у «Оба» — две). Сначала скрывается «последняя», затем «соперники» (полные значения — в подсказке); счёт сохраняется в компактном виде. В стопке ошибки показываются только на вкладке «Ошибки». -- **Колонки дерева** прячутся по очереди: Последняя → полоса счёта (остаётся %) → Дебют (имя переезжает в подсказку хода). Никогда: Ход, Партий, %, Счёт-процент. Таблица дебютов: Первые ходы → Последняя → ECO → полоса. Вкладка «Ошибки»: Дебют → Счёт. -- **Диалоги** (§2.2, §4.2) при 640 × 480 — тело прокручивается, кнопки вне прокрутки (как `play-mode.md` §2.5). - -## 7. Клавиатура - -Правило как на доске поиска: клавиши без модификаторов действуют, когда фокус не в текстовом поле. Фокус один из двух: дерево/таблица вкладки или список партий; `Tab` переключает между ними, видимый фокус — полоса ▌ у выделенной строки ярче. - -| Клавиша | Действие | -|---|---| -| `↑` / `↓`, `PgUp` / `PgDn`, `Home` / `End` | строка в текущей таблице | -| `→` | дерево: раскрыть узел; раскрыт — к первому ребёнку. Таблица дебютов: раскрыть семейство | -| `←` | дерево: свернуть; свёрнут — к родителю | -| `Space` | раскрыть/свернуть без перемещения | -| `Enter` | в дереве/дебютах — фокус в список партий (первая строка); в списке партий и во вкладке «Ошибки» — открыть партию на ходе | -| `Ctrl+1` / `Ctrl+2` / `Ctrl+3` | вкладки Репертуар / Дебюты / Ошибки | -| `Ctrl+W` / `Ctrl+B` | цвет Белые / Чёрные (`Ctrl+W` здесь не «закрыть»: закрытие отчёта — «⬅ Библиотека» или `Esc` без выделения) — **вопрос 11.7**; запасной вариант: `Alt+1/2/3` для Белые/Чёрные/Оба | -| `F` | перевернуть доску | -| `Shift+A` | «Найти ошибки в дебютах» (та же клавиша, что «Анализ партии» — то же действие «позвать движок»); во время работы — «Остановить» | -| `Ctrl+Shift+F` | найти позицию доски в базе (доска поиска библиотеки) | -| `Esc` | закрыть меню/подсказку → снять выбор узла (список — все партии) → назад в библиотеку | -| `Ctrl+Shift+P` (библиотека) | «Подготовиться к…» с игроком из фильтра | - -Все действия, кроме стрелок наведения, доступны с клавиатуры; чтение экрана — у отметок текстовые подсказки с названием («Ошибка», «Зевок»). - -## 8. Цвета и значки - -Отметки — как в нотации и в отчёте анализа (`notation::assessment_color` / `assessment_text_color`, `review::judgement_color`): - -| Отметка | NAG | Заливка значка | Текст на светлом | Где | -|---|---|---|---|---| -| `?!` неточность | 6 | `#56b4e9` | `#1f72a8` | значок-пилюля после SAN (дерево, «Сыграл», колонка «Ошибки» списка партий); счётчики текстом | -| `?` ошибка | 2 | `#ffa459` | `#c25700` | то же | -| `??` зевок | 4 | `#fa412d` | `#d2301c` | то же | - -- Значок — пилюля с белым символом, как `move_glyph` в нотации; в счётчиках («3 ? · 1 ??») — текст цветом `assessment_text_color` по теме; `!!`/`!` здесь не ищутся и не показываются. -- Стрелки на доске: сыгранный ход — цвет его отметки (полупрозрачный), лучший — зелёный стрелки движка; наведение — синий полупрозрачный, как на доске поиска. -- Полоса счёта — светлотой (Б светлый, ничьи серый, Ч тёмный) с процентами внутри и подсказкой, без красного/зелёного (`board-search.md` §4.10). Счёт — всегда очки **игрока**, независимо от цвета; подпись колонки «Счёт», подсказка «Очки соперника в этих партиях». -- «Мало партий» — слабый текст. Ни одно состояние не передаётся только цветом: у всех есть число, символ или подсказка. - -## 9. Тексты (ключ EN → RU) - -| EN (ключ) | RU | -|---|---| -| `♟ Prepare against {name}…` | ♟ Подготовиться к {name}… | -| `♟ Prepare against an opponent…` | ♟ Подготовиться к сопернику… | -| `Prepare against ▸` | Подготовиться к сопернику ▸ | -| `Preparing against an opponent` (диалог) | Подготовка к сопернику | -| `Preparing against {name}` (шапка) | Подготовка к сопернику: {name} | -| `Database` (есть) | База | -| `Player` (есть) | Игрок | -| `Similar names — most likely other people` | Похожие имена — скорее всего, другие люди | -| `Selected: {names} · {n}` | Отмечено: {names} · {n} | -| `Tick a player` | Отметьте игрока | -| `+{n} spelling` / `+{n} spellings` | +{n} написание / +{n} написания (`i18n` склонение) | -| `Colour` | Цвет | -| `Both` · `White` · `Black` | Оба · Белые · Чёрные | -| `White — {n}` · `Black — {n}` | Белые — {n} · Чёрные — {n} | -| `As White` · `As Black` (корни дерева) | Белыми · Чёрными | -| `Retry` | Повторить | -| `Open report` | Открыть отчёт | -| `Opening: {n} moves` | Дебют: {n} ходов | -| `Collecting games… {p} %` | Собираю партии… {p} % | -| `{n} games · {score} % ({w}+ {d}= {l}−) · opponents ≈ {elo} · last {date}` | {n} · {score} % (+{w} ={d} −{l}) · соперники ≈ {elo} · последняя {date} | -| `{i} ?! · {m} ? · {b} ??` | {i} ?! · {m} ? · {b} ?? | -| `in {p} % of games` | в {p} % партий | -| `no errors` | нет ошибок | -| `Opening errors: {i} inaccuracies · {m} mistakes · {b} blunders — in {g} games ({p} %)` | Ошибок в дебюте: неточностей {i} · ошибок {m} · зевков {b} — в {g} партиях ({p} %) | -| `Few games ({n}): percentages and scores are unreliable` | Партий мало ({n}) — проценты и счёт ненадёжны | -| `Few games: percentages are unreliable` | Мало партий — проценты ненадёжны | -| `Repertoire` · `Openings` · `Errors` | Репертуар · Дебюты · Ошибки | -| `Branches from {n} games` | Ветви от {n} партий | -| `Expand all` · `Collapse` | Раскрыть всё · Свернуть | -| `Move` · `Opening` · `Games` · `%` · `Score` · `Last` | Ход · Дебют · Партий · % · Счёт · Последняя | -| `First moves` · `Errors` · `Played` · `Better` · `Position` · `Colour` | Первые ходы · Ошибок · Сыграл · Лучше · Позиция · Цвет | -| `other moves ({n})` | другие ходы ({n}) | -| `no deeper name` | без названия глубже | -| `Reached by another move order too: {orders}` | К позиции приходили и другим порядком: {orders} | -| `The opponent's points in these games` | Очки соперника в этих партиях | -| `Games · {n}` · `Games · after {move} · {n}` · `Games · {opening} · {n}` · `Games · {move} · {n}` | Партии · {n} · Партии · после {move} · {n} · Партии · {opening} · {n} · Партии · {move} · {n} | -| `Then` (есть) · `Event` (есть) | Дальше · Турнир | -| `Open as a game` | Открыть как партию | -| `Play on from here…` (есть) · `Find this position in a database (Ctrl+Shift+F)` (есть) · `Copy FEN` · `Copy moves (PGN)` | Играть отсюда… · Найти позицию в базе (Ctrl+Shift+F) · Копировать FEN · Копировать ходы (PGN) | -| `⬅ Back to preparation` | ⬅ К подготовке | -| `▶ Find opening errors` · `▶ Find opening errors ≈ {time}` | ▶ Найти ошибки в дебютах · ▶ Найти ошибки в дебютах ≈ {time} | -| `Options…` | Параметры… | -| `Opening errors` (диалог) | Ошибки в дебютах | -| `The engine evaluates the first {n} moves of every game of the opponent. The games are not changed.` | Движок оценит первые {n} ходов каждой партии соперника. Партии не меняются. | -| `Engine` · `Quality` · `Threads` · `Memory` (есть) | Движок · Качество · Потоки · Память | -| `For opening errors “Fast” is usually enough. “Normal” is for adult databases and takes 4 times longer.` | Для поиска ошибок в дебюте обычно достаточно «Быстро». «Обычно» — для взрослых баз, в 4 раза дольше. | -| `{n} positions, about {time}` (есть) | {n} позиций, около {time} | -| `identical positions are counted once; {n} already evaluated earlier` | одинаковые позиции считаются один раз; {n} уже оценены раньше | -| `Find errors` | Найти ошибки | -| `Finding errors: {done} of {total} positions · ≈ {time}` | Ищу ошибки: {done} из {total} позиций · ≈ {time} | -| `The engine evaluates positions to find inaccuracies, mistakes and blunders. It starts automatically after the report is built; evaluated positions are kept after Stop.` (hover контрола движка) | Движок оценивает позиции и находит неточности, ошибки и зевки. Запускается сам после построения отчёта; после Stop оценённые позиции сохраняются. | -| `Stop` · `Continue ≈ {time}` | Остановить · Продолжить ≈ {time} | -| `Stop the error search. Evaluated positions are kept.` | Остановить поиск ошибок. Уже оценённые позиции сохранятся. | -| `Waiting for the engine to become available…` | Ожидаю освобождения движка… | -| `No games to analyse` | Нет партий для анализа | -| `Checked {done} of {total} positions` | Проверено {done} из {total} позиций | -| `of the checked positions` | из проверенных позиций | -| `Errors found · {engine} · {quality} · {n} positions · {date}` | Ошибки найдены · {engine} · {quality} · {n} позиций · {date} | -| `More precisely…` · `Analyse {n} more positions ≈ {time}` | Точнее… · Доразобрать {n} позиций ≈ {time} | -| `Opening errors are being searched — wait or stop it in the report` | Идёт поиск ошибок в дебютах — дождитесь или остановите его в отчёте | -| `A game analysis is running — wait for it to finish` | Идёт анализ партии — дождитесь его конца | -| `Opening errors are being searched. Quit and stop?` | Идёт поиск ошибок в дебютах. Выйти и остановить? | -| `Add an engine first` | Сначала добавьте движок | -| `No errors in the first {n} moves ({i} inaccuracies).` | В первых {n} ходах ошибок не нашлось (неточностей {i}). | -| `Deeper: {n} moves` | Глубже: {n} ходов | -| `Repeated errors — the same position, the same move` | Повторяющиеся ошибки — одна и та же позиция, тот же ход | -| `By opening` | По дебютам | -| `after {move}, {side} to move` | после {move}, ход {side} (белых/чёрных) | -| `{played} — better {best} · {before} → {after}` | {played} — лучше {best} · {before} → {after} | -| `Mistake: better {best} ({before} → {after}) · in {n} games` | Ошибка: лучше {best} (оценка {before} → {after}) · в {n} партиях | -| `Inaccuracy` · `Mistake` · `Blunder` (есть) | Неточность · Ошибка · Зевок | -| `No games as {colour}. As {other} — {n} · Show {other}` | {colour} партий нет. {other} — {n} · Показать {other} | -| `No games match the conditions: {chips} · Open without conditions` | Партий по условиям нет: {chips} · Открыть без условий | -| `not counted: from a set position — {n}` | не учтены: с заданной позиции — {n} | -| `Board` (кнопка в стопке) | Доска | - -Имена игроков нигде не склоняются («Подготовиться к Вафин Радель…»); числа партий — через `i18n::games`. - -## 10. Что меняет разработчик (сводка для `apps/desktop`) - -1. `large_db.rs` `players_group`: кнопка «♟ Подготовиться к…» под строкой цвета; контекстное меню строки — два пункта; `LibraryAction::PrepareAgainst { path, names, side, filter }`. -2. `game_view.rs`: пункт ☰ «Подготовиться к сопернику ▸» и контекстное меню названия; `GameAction::PrepareAgainst`; «⬅ К подготовке» по тому же `previous`-механизму, что «⬅ К партии». -3. `prep_ui.rs`: книжные контролы, фоновый проход, колонки и результаты удалены из подготовки. Старые поля в JSON отчёта, сохранённой подготовки и настроек остаются пассивными legacy-данными: не вычисляются и не показываются, но не стираются обычным автосохранением. Обычный Справочник не меняется. -4. `prep_ui.rs`: после готовности отчёта автоматически вызывать `start_engine` без `engine_asked`/`prep.chosen`; автопереход на «Ошибки» только при старте. На «Ошибках» добавить полный прогресс и Stop. После ручной остановки хранить запрет автозапуска для этой конфигурации; «Продолжить» вызывает запуск напрямую. Смена глубины/периода сбрасывает запрет и запускает движок после перестроения. `engine_dialog` остаётся только по «▾». -5. `settings.rs` / сохранённая подготовка: `prep.chosen` больше не является разрешением запуска; состояние ручной остановки должно переживать уход и повторный вход, чтобы частичный кэш не запускал движок сам. Настройки глубины и периода сохраняются как прежде. -6. `app.rs`: уход с экрана не отменяет engine job; поздние ответы применяются только к своей конфигурации. Сохраняется один engine job на программу и вопрос при выходе во время анализа. -7. Сводка — по §3.5: отдельные title/games, games с выравниванием вправо, компактный score, соседние counts/percent. Ширины counts и percent измерять независимо через реальный `Label` с `gap = 4`; нулевые типы пропускать, при всех нулях не создавать колонку процента. Порядок скрытия — last → opponents; score/errors не скрывать, в стопке ошибки оставить только на вкладке «Ошибки». -8. Снимки для проверки: счётчики разной разрядности и стабильная X процента, пропущенные нулевые типы, все нули без процента, компактный score; автозапуск движка на «Ошибках», ручная остановка и «Продолжить» без диалога; смена глубины/периода; уход и повторный вход; нулевые партии и 640×480. Пересечение контролов проверяется отдельно по задаче 30 и здесь не считается исправленным. - -## 11. Открытые вопросы - -1. **Условия библиотеки в отчёте** (§2.4): брать активные фильтры (годы, Эло, турнир) как условия отчёта при входе из панели — да (рекомендация) или всегда все партии игрока? -2. **Цвет по умолчанию** — «Оба» при входе из партии/строки и цвет фильтра при входе из панели (рекомендация), или всегда спрашивать? Диалог показывает радио в любом случае. -3. **Качество «Быстро» по умолчанию** отдельной настройкой от анализа партии — утвердить (техчасть, вопрос 4). -4. **Неточности `?!`** во вкладке «Ошибки»: показывать всегда (рекомендация, слабее и ниже) или за выключателем «показывать неточности»? -5. **Отметки отчёта в открытой партии**: показывать оценки дебюта из кэша отчёта как слой в нотации (без анализа партии)? Требует общего кэша по позиции с `game-review` (техчасть, вопрос 5). Рекомендую позже. -6. **«Показать в дереве»** из таблицы дебютов и из «Ошибок» — ссылка, переключающая вкладку и выделяющая узел. Дёшево; добавить в первую версию? -7. **Клавиши цвета**: `Ctrl+W`/`Ctrl+B` занимают «закрыть» — предпочитаю `Alt+1/2/3` или вовсе без клавиш (переключатель всегда на виду). Решить. -8. **Мини-доска в подсказке** строк «Повторяющиеся ошибки» — оставить (рекомендация) или достаточно большой доски по щелчку? -9. **«Играть отсюда…» и «Открыть как партию»** с доски отчёта — в первую версию (рекомендация: это существующие действия) или после? - -## 12. Ревью реализации (f02f140, 2026-10-28) - -Проверено по снимкам разработчика (1400×1000 тёмная, 640×1000, 640×480) и своим: светлая тема (репертуар, ошибки), «Дебюты» при «Чёрные», диалог движка, ход движка, 804/803×900, 960×1050, диалог при 640×480, «Ошибки» и «Дебюты» при 640×1000, вход из панели фильтров. Снимки — `scratchpad/prep-design/*.png`. Не снято: выбранная ошибка со стрелками на доске (выбрать её можно только мышью — см. А6). - -Общее: архитектура экрана, диалог, три вкладки, список партий, движок, стопка и низкое окно — по дизайну; палитра отметок и пилюли — как в нотации, в обеих темах читаются. Замечания ниже — по приоритету: **А** мешает читать и понимать данные, **Б** расходится с визуальной системой, **В** узкие окна. У каждого — правка. - -### А. Данные и понимание - -1. **Сводка — одно длинное предложение.** После движка строка цвета становилась слишком длинной; при 960 и 804 она переносилась посреди фразы («Ошибок в / дебюте: …», `w960.png`, `w804.png`), и вторая строка читалась как новая запись. Актуальная правка — §3.5: `egui::Grid`, отдельные title/games с правовыравненным числом, компактный score, соседние counts/percent с независимым измерением через реальный `Label` и `gap = 4`. Счётчики ошибок — цветные, в порядке `?! · ? · ??`; нулевые типы пропускаются, при всех нулях остаётся только «нет ошибок». Скрытие — last → opponents; score/errors не скрываются, в стопке ошибки только на вкладке «Ошибки». -2. **Числа в полосе счёта спорят с «Счётом».** В строке «Белыми · 138» рядом стоят «78 %» (очки) и «75» внутри полосы (доля побед белых); у чёрных внутри светлого сегмента стоит доля побед **соперника** («Queen's Pawn Game · 56 % · [56]», `openings_black.png`). Два разных числа в одной ячейке без подписи — главный источник непонимания колонки «Счёт». Правка: в полосе 56 точек чисел не рисовать (`results_bar` с флагом без текста либо своя узкая версия); проценты — только в подсказке «+10 =1 −3». Полоса остаётся абсолютной (Б светлый слева, Ч тёмный справа), как на доске поиска. Заодно: при «мало партий» полоса не приглушается (`painter_alpha` вычислен и выброшен) — рисовать её с `gamma_multiply(0.5)` или не рисовать вовсе. -3. **Линия под доской нумерует чёрные ходы:** «1.e4 1…c5 2.Nf3 2…d6». Нигде в программе так не пишут. Правка: `short_label` только для первого хода и для белых ходов; чёрные — голым SAN («1.e4 c5 2.Nf3 d6»). Та же линия нужна в «Первые ходы» таблицы дебютов, где сейчас формат таблицы lichess «1. e4 c5» (с пробелом после номера) — привести к `line_text`. -4. **«Первые ходы» нет на 1400×1000 при «Оба»** (`openings.png`): колонка «Цвет» 90 + «Дебют» ≥ 200 не оставляют 160 для ходов, и между «Дебют» и «ECO» пустота. Это именно те данные, ради которых владелец просил «всегда с первыми ходами». Правка: «Цвет» — только значок `♙`/`♟` шириной 24 с подсказкой (слово «Белыми» 11 раз подряд — шум); минимум «Дебют» 180, «Первые ходы» 140; порядок скрытия как в §6. Альтернатива лучше, но дороже: вместо колонки — строки-заголовки «Белыми · 138» / «Чёрными · 133», как корни дерева. Также сокращение линии режет ход пополам и даёт двойное многоточие («…5 4. Bg2 Be7 5. …», `openings_black.png`): `shorten_middle` — по границам ходов и по измеренной ширине, без второго `truncate`. -5. **Имя дебюта в дереве «откатывается»:** под «2…d6 Sicilian Defense: Modern Variations» стоит «3.d4 Sicilian Defense» — таблица даёт менее точное имя глубже, и правило «показывать, когда меняется» печатает его как новое. Правка: не показывать имя, если оно — префикс имени родителя (семейство без варианта); лучше — в `prep` сделать имя узла «липким» (самое глубокое имя по пути), тогда и подсказка, и таблица дебютов согласуются. -6. **Вкладка «Ошибки» без клавиатуры и без строк.** Стрелки там ничего не выбирают (`keyboard` → только Enter), а щелчок ловит лишь подпись «Позиция» / имя дебюта, не строка (`egui::Grid` без ответа строки). В «По дебютам» счётчики ошибок стоят на разной высоте — не сравнить. Правка: обе части — `TableBuilder` со `striped`, `sense(click)` и выделением строки, как дерево; клавиши ↑/↓/→/← по общему списку строк (повторяющиеся + дебюты + раскрытые партии), Enter — открыть партию. Это же даст хук для снимка выбранной ошибки (`CP_KEYS`). -7. **Четыре строки одних и тех же чисел** на 1400 (`errors.png`): сводка (2 строки) и сразу под ней в «Ошибках» «Белыми: … / Чёрными: …». Правка: во вкладке строки цветов показывать только в стопке (там сводка их не несёт, §6); рядом — только строка состояния «Ошибки найдены · Stockfish 19 · Быстро · 2 947 позиций · Точнее…». -8. **Колонка «Дебют» в дереве теряет ECO:** длинное имя забирает всю ширину, ECO обрезается до «··» («Nyezhmetdinov-Rossolimo Attack ··», `repertoire.png`). Правка: ECO класть первым в `right_to_left`, имя — в остаток с `truncate`. -9. Мелкое: «2947 позиций» без разделителя тысяч (статус, диалог, прогресс) — `large_db::grouped`; «%» в таблице дебютов без подсказки (в дереве есть) — «Доля от партий цветом; у варианта — от семейства». - -### Б. Визуальная система - -1. **«▾» слева от «Ошибки найдены»** (все снимки): в `right_to_left` кнопка параметров добавлена второй и встала левее подписи — выглядит как сворачивалка. Правка: добавлять «▾» первой (окажется справа), чтобы статус оставался слева от неё, как в §4.4. -2. **Три порядка цветов:** диалог «Оба · Белые · Чёрные», диалог движка «Белые · Чёрные · Оба», переключатель «Белые · Чёрные · Оба». Правка: везде «Белые · Чёрные · Оба». -3. **«🗙» у заголовка списка партий** — крупная рамочная кнопка тяжелее заголовка. Правка: `widgets::small_close_button`, как в диалоге у поля «Игрок» и у чипов. -4. **Полоса счёта в светлой теме** почти сливается с фоном строки (`light_rep.png`) — общее свойство `results_bar`, не этого экрана; если править п. А2 своей версией полосы — дать светлому сегменту обводку 1 px `weak_text_color` в светлой теме. -5. Глубина «Дебют: 10 ходов» при W < 760 превращается в голое «10» (`narrow640.png`), хотя в строке остаётся ~150 точек. Правка: выбирать подпись по измеренной ширине («Дебют: 10 ходов» → «10 ходов» → «10 х.»), а не по порогу окна. - -### В. Узкие и низкие окна - -1. **Имена в списке партий уже `NAME_MIN` 110** при 640–804 («Вафин Рад…», «Конюшенко С…», `narrow640.png`, `w804.png`): Elo и «Дальше» остаются, имена ужимаются до 82–95. Правка (как §3.10 и `board-search.md` §2.7): сначала считать `player_w`; если < 110 — прятать «Дальше», затем Elo (в ячейку имени слабым), и только потом резать имена. -2. **640×480: дереву остаётся 6 строк** (`low640.png`) — минимум списка партий 4 строки + 60 и доля 35 %. Правка: при H < 600 минимум списка — 2 строки, доля 25 %; дерево получает ≈ 10 строк. -3. В стопке над доской нет подписи «Ход белых · после 2.Nf3» (`board_caption` не вызывается, `w803.png`): добавить первой строкой в колонку справа от доски. -4. «другие ходы (1)» на глубине обрезается в «другие ход…» при минимуме колонки 180 (`w804.png`): короче — «другие (1)». -5. Пороги 804/803 и 720 работают как задумано (`w804.png` — рядом, `w803.png` — стопка; `low640.png` — доска по кнопке); диалоги при 640×480 помещаются. - -### Что принимаю из отклонений разработчика - -- «⤳» → «⇄» — да, яснее. -- Имя дебюта в дереве только когда меняется относительно родителя — да, с поправкой А5 (не показывать менее точное имя). -- «Первые ходы» семейства — его позиция по таблице — да. -- Строки ошибок в сводке нет в стопке — да (§6 так и задумано). -- Строка ошибок в сводке простым текстом — **нет**, см. А1: `counts_text` уже есть, это три строки правки. -- Отложены: вход с экрана партии, мини-доска в подсказке, «показать в дереве», сортировка таблицы дебютов — да; «Точнее…» только во вкладке «Ошибки», а не в строке переключателей — да, строка и так тесная. -- Автопереход на вкладку «Ошибки» при запуске движка (в дизайне не было) — да, полезно. - -### Не проверено - -Выбранная ошибка (стрелки сыгранного/лучшего хода, строка «… — лучше … · 0,0 → −1,2» под доской), «Остановлено → Продолжить», «нет партий цветом», партия, открытая из отчёта («⬅ К подготовке»). Для снимков нужна клавиатура во вкладке «Ошибки» (А6) или хук `CP_PREP_SELECT`. - -## Изменения - -- 2026-10-28: первая версия. -- 2026-10-28: §12 — ревью реализации f02f140 (замечания А/Б/В, принятые отклонения, что не проверено). -- 2026-11-01: по тогдашним решениям владельца книга переведена на ручной запуск с прогрессом/Stop и без частичных результатов; движок — на автозапуск после построения отчёта и после смены глубины/периода, без первого диалога и без самоперезапуска после Stop. Обновлены §0–6, §9–11; общая вёрстка не пересматривалась. -- 2026-11-02: книжная сверка полностью удалена из актуального проекта; предыдущий пункт оставлен как история. Диалог, сценарии, контролы, дерево, состояния, i18n и примечания реализации приведены к экрану без неё. §3.5 дополнен согласованной сеткой summary: отдельные title/games и counts/percent, независимое измерение через реальный `Label` с `gap = 4`, нулевые состояния, last → opponents и ошибки только на вкладке «Ошибки» в стопке. Правила движка не изменены; задача 30 не закрывается. diff --git a/docs/design/repertoire-panel-layout-2026-11-27.md b/docs/design/repertoire-panel-layout-2026-11-27.md deleted file mode 100644 index c7b75e1..0000000 --- a/docs/design/repertoire-panel-layout-2026-11-27.md +++ /dev/null @@ -1,60 +0,0 @@ -# Правая панель «Тренировка дебюта»: ширина, таблица, карточка (2026-11-27) - -Задача экрана: выбрать репертуар и сразу начать занятие; приоритет — название, «что сегодня», главная кнопка; доска не должна страдать. - -## Снимки текущего состояния (изолированный профиль, сборка debug 2026-11-27 12:08) - -`XDG_CONFIG_HOME/XDG_DATA_HOME/CP_REPERTOIRE_DIR=/tmp/opencode/rp/*`, `CP_REPERTOIRE=library CP_REPERTOIRE_SELECT=Испан CP_SCREENSHOT_SIZE=WxH`. -Снимки: `/tmp/opencode/rp/s/lib-1280.png` (1280×800), `lib-1600.png` (1600×1000), `lib-1920.png` (1920×1000). Окружение Wayland, масштаб >1 (1280 логич. снято в 2000 px). - -Наблюдения: -- 1600 и 1920: панель упирается в потолок 460 логич. px; при 1920 слева/справа от доски ~270 px пустоты, а таблица тесная: «Полуславянская защита…», «Сицилианская защита: …» обрезаны. -- Колонка «Сегодня» (90) + отдельная колонка полосы (44) без заголовка: полоса визуально прижата к «новые: 10», т.е. читается как часть «Сегодня» — дефект 5 у владельца. -- «Пройдено» — колонка 64 px; жирный заголовок «Пройдено» ≈ 68–72 px → при меньшей ширине/другом шрифте режется до «Прой» (дефект 3). -- На стартовых коротких названиях обрезка заголовка карточки и «Повторить всё» на моих снимках не воспроизвелась; у владельца (панель ~620 физ. px ≈ 400 логич.) — да. Причины в коде ниже. - -## Откуда ширины (код) - -- `apps/desktop/src/opening_layout.rs:53` — `default_size((width * 0.4).clamp(260.0, 460.0).min(room))`: потолок 460 при любом окне. -- `opening_layout.rs:15` `SIDE_LEAST = 320`, `:54` `size_range(SIDE_LEAST..=most)`, `most = width - BOARD_MIN - 24`. Перетаскивание есть (`resizable(true)`), но ширина не сохраняется между запусками/экранами раздела (проверить: id `opening_side` хранит egui memory только в сессии). -- `apps/desktop/src/repertoire_ui.rs:56-58` — `TODAY_W 90`, `MINI_BAR_W 44`, `PASSED_W 64`; `:1682-1687` колонки: `remainder().at_least(80)`, 22, 90, 44, 64, 26. Фиксированная часть = 246 + 5 межколоночных промежутков (≈40) ≈ 286 px; на название при панели 400 остаётся ~95 px. -- `:1699-1706` заголовки: «Сегодня» над колонкой 3, колонка 4 (полоса) — пустая, «Пройдено» над колонкой 5. -- `:1557-1569` заголовок карточки: ширина «Вы играете белыми» считается `text_width(ui, &you, 14.0)+8`, а рисуется `RichText::weak()` шрифтом Body темы; при расхождении размера и без учёта `item_spacing.x` имя получает меньше/больше места, а `layout::line` (`opening_layout.rs:106`) режет «…». -- `:1589-1615` кнопки карточки: всегда один ряд; `grow` раздаёт только свободное, но если `room < main_need+lines_need+third_need+2·gap`, кнопки не сжимаются ниже `need`, и третья выходит за правый край карточки (обрезается клипом). `text_width(…,14.0)` также может не совпадать со шрифтом кнопки. - -## Решения - -### 1. Ширина панели -- По умолчанию: `clamp(width × 0.36, 380, 560)`, но не больше `room` (доска ≥ `BOARD_MIN`). Итог: 1280 → 461, 1600 → 560, 1920 → 560 логич. px. При 1920 доска остаётся ≥ высоты окна − 16, т.е. не уменьшается (сейчас там пустота). -- Минимум: `SIDE_LEAST` поднять до 360 (меньше таблица не помещается без обрезки двух чисел). Максимум без изменений: `width − BOARD_MIN − 24`. -- Перетаскивание: оставить; ширину, выставленную пользователем, сохранять в `Settings` (ключ, напр. `opening_side_width`) и применять как default на всех экранах раздела (тот же id → доска не прыгает). Двойной клик по разделителю — сброс к умолчанию (если egui позволяет; иначе пункт не обязателен). - -### 2. Таблица репертуаров (`repertoire_ui.rs:1682`) -Колонки (5 вместо 6): -1. Название — `remainder().at_least(120).clip(true)`, усечение «…» только при реальной нехватке, полное имя в tooltip. -2. Цвет (♔/♚) — `exact(22)`. -3. «Сегодня» — `exact(today_w)`, где `today_w = max(ширина заголовка, ширина «повторить 99», «новые: 10», «завтра»)` измеренная фактическим шрифтом строки (`ui.fonts(|f| layout_no_wrap(...))`) + 4; ожидаемо ≈ 76–84 вместо 90. Выравнивание вправо. -4. «Пройдено» — одна колонка: полоса 44 + промежуток 6 + число «0/22» вправо. `passed_w = max(ширина жирного заголовка, 44 + 6 + ширина «000/000»)` ≈ 100. Заголовок «Пройдено» выравнивается вправо над числом, полоса — слева в той же колонке (решает дефект 5: полоса под «Пройдено»). -5. `⋯` — `exact(26)`. -Фикс. часть ≈ 22+82+100+26 + 4 промежутка·8 ≈ 262; название при 460 ≥ ~180, при 560 ≥ ~280 — стартовые названия влезают целиком. -Правило: числовые колонки никогда не режутся; при минимальной панели 360 режется только название. Ширины считать один раз на кадр до `TableBuilder` (не по содержимому видимых строк — чтобы не было скачков при прокрутке/подсчёте). «…» (подсчёт) и «нет ходов» вписываются в те же ширины; если «нет ходов» шире — включить его в max для `passed_w`. - -### 3. Заголовок карточки (`:1557-1569`) -- Мерить «Вы играете белыми» тем же `FontId`, которым рисуется (Body), + `item_spacing.x`. -- Если `name_w + you_w > width`: сначала заменить метку на короткую (только король ♔/♚ с tooltip «Вы играете белыми»), и лишь затем усекать имя «…». Перенос имени на 2 строки не делать (фиксированная `CARD_H`, без скачков). - -### 4. Кнопки карточки (`:1589-1640`) -- Измерять потребность шрифтом кнопки (`TextStyle::Button`) + `2·button_padding.x`. -- Если три кнопки влезают — один ряд, как сейчас (главная растёт первой). -- Иначе — две строки: 1-я — главная на всю ширину; 2-я — «Варианты…» и «Повторить всё» поровну. Решение «одна/две строки» зависит только от ширины панели, не от состояния карточки; высоту карточки (`CARD_H`) для двухстрочного режима увеличить на 30+6 и держать её одинаковой во всех состояниях при этой ширине (в т.ч. когда третьей кнопки нет — пустое место), чтобы таблица не прыгала при выборе другой строки. -- `.truncate()` у кнопок оставить как страховку, но в норме обрезки быть не должно. - -## Критерии приёмки (ревьюер — не автор, по реальным снимкам) -Серия: окна 1280×800, 1600×1000, 1920×1000, а также панель перетянута до минимума 360 и до максимума; масштаб 1.0 и HiDPI; язык ru и en (de — самые длинные строки). -1. Ширина панели по умолчанию 461/560/560 логич. px (±2) на трёх окнах; доска на 1920 не меньше, чем до изменения. -2. После перетаскивания и перезапуска ширина та же; переход «Репертуары ⇄ Варианты ⇄ занятие» не сдвигает доску (снимки до/после, x левого края доски совпадает). -3. Таблица: «Сегодня», «Пройдено», числа «0/22», полоса никогда не обрезаны ни при одной ширине ≥360; полоса и число под заголовком «Пройдено», правый край заголовка = правый край числа (±1 px); заголовок «Сегодня» выровнен по правому краю значений. -4. При 560 стартовые названия («Полуславянская защита», «Сицилианская защита: …» полностью) без «…»; при 360 режется только название, tooltip даёт полное. -5. Заголовок карточки не усечён, если свободного места хватает; при нехватке сначала исчезает текст «Вы играете…», остаётся король. -6. Ни одна кнопка карточки не выходит за рамку; при узкой панели — две строки; высота карточки одинакова при переключении строк с разными состояниями (снимки 3 выбранных строк подряд, y шапки таблицы совпадает). -7. Подсчёт статистики («…» → числа) не меняет ширину колонок (серия снимков сразу после запуска и через 4 с). diff --git a/docs/design/repertoire-training.md b/docs/design/repertoire-training.md deleted file mode 100644 index fe93a3e..0000000 --- a/docs/design/repertoire-training.md +++ /dev/null @@ -1,998 +0,0 @@ -# Дебютные репертуары и тренировка по дереву - -**Дополнение после выпуска 2.2.0 (06.11.2026):** владелец поручил показывать -PGN-значки и рисунки в новом экране обучения после собственных и автоматических -ходов, используя вид обычного просмотра партии. Он также отменил ограничение -одним собственным ответом: изучаются все включённые варианты. Предпочтительный -ход меняет порядок, а не состав заданий. Другой ожидающий ответ из той же позиции -засчитывается именно сыгранному `(FEN4, UCI)`; повторённый/не запланированный -ответ репертуара обрабатывается нейтрально. Исходные PGN и экран обычного просмотра -партии от этой доработки не меняются. Это дополнение имеет приоритет над правилом -единственного main-answer в исторических разделах ниже. - -Статус: **финальный рабочий дизайн для desktop-реализации**, 2026-11-02. Основание — подтверждённое решение `docs/decisions.md` «Дебютные репертуары и тренировка по дереву (2026-11-02)». Этот документ заменяет сценарий немедленного «Учить дебют до этого хода» на desktop; старый Android-тренер не меняется. - -**Актуализация 2026-11-02:** скрытая целевая модель и `try again` из прежних разделов отменены после живого замечания владельца; пользовательский путь уточнён в §20. - -**Действующая редакция 2026-11-04:** §23 и `docs/chesstempo_opening_trainer_TZ.md`. Владелец подтвердил приоритет полного ТЗ над прежними упрощениями из §21. Единый workspace из §22 сохраняется; разделы до §23 оставлены как история проектирования и не описывают текущую модель там, где противоречат ТЗ и §23. - -Размеры ниже — логические точки egui. Подписи даны на русском; обязательные RU/EN/DE-строки — в §13. Открытых продуктовых вопросов и альтернатив для реализации нет. - -## 0. Задача и границы - -Пользователь собирает несколько самодостаточных PGN-репертуаров, ограничивает их область и глубину, а затем либо повторяет отдельные ходы одного цвета по очереди, либо воспроизводит ветки целиком за обе стороны. - -Обязательные инварианты: - -1. Репертуар — **PGN-дерево**: основная линия, все RAV, комментарии, NAG и исходный FEN сохраняются. Это семантический PGN-снимок, а не набор UCI и не ссылка на `NodeId` исходной партии. -2. Исходная партия, её база и импортированный файл никогда не изменяются. Добавление, импорт и тренировка пишут только данные библиотеки репертуаров и `training.json`. -3. Глубина по умолчанию — **20 полуходов от начала репертуара**. Глубина и `disabled` ограничивают тренировку, но не удаляют содержимое и не меняют PGN-экспорт. -4. `White`, `Black` и `Both` — три раздельных пространства статистики внутри каждого репертуара. Статистика разных репертуаров также не смешивается. -5. Транспозиции объединяются по FEN4 **только внутри одного репертуара**. Все исходные пути остаются в PGN и в просмотре. -6. Движок в тренировке не участвует. Все автоматические ходы и допустимые продолжения берутся из включённого дерева. -7. Desktop-first. На Android остаются прежний линейный тренер, его UniFFI API и legacy-записи `training.json`; web не получает кнопку до отдельного VFS-хранилища. -8. Все записи атомарны. Ошибка записи видна и не маскируется успешным результатом. - -Термины: - -- **Ход/цель** в одноцветном режиме — конкретный `(position FEN4, expected UCI)` выбранного цвета. -- **Путь** в `Both` — фактически сыгранная последовательность полуходов от начала области до листа, глубины или повторения позиции. -- **Область** — весь репертуар либо поддерево от выбранного хода. Выбранный ход входит в область. -- **Контекст** — путь от начала репертуара до начала области или текущей цели. Контекстные ходы не являются попытками пользователя. - -## 1. Информационная архитектура - -На экране баз непосредственно рядом с «📑 Подготовки» находится обычная кнопка «Тренировка дебюта». Без нового непроверенного значка. Она открывает библиотеку репертуаров, а не доску случайной тренировки. - -Три рабочих экрана, без последовательности мастеров и модальных окон: - -1. **Репертуары** — таблица библиотеки, создание, переименование, удаление, импорт, прежние line-run. -2. **Репертуар** — доска и полное дерево, область, глубина, режим, очередь, статистика, запуск. -3. **Тренировка** — ограниченный экран доски и сыгранного пути, построенный на визуальной основе текущего тренера. - -Допустимы только системный выбор PGN-файла, компактный выбор назначения из партии и контекстные меню. Создание, переименование, удаление и предпросмотр импорта выполняются inline. Единственное разрушительное подтверждение — удаление репертуара — тоже раскрывается строкой в таблице, а не отдельным окном. - -Возврат: - -- `Репертуары → Базы` возвращает прежний экран баз без изменения фильтров и выбранной базы. -- `Репертуар → Репертуары` сохраняет строку, прокрутку и раскрытую вкладку библиотеки. -- `Тренировка → Репертуар` возвращает ту же область, активный ход дерева, глубину, режим и очередь. -- Если репертуар открыли по ссылке из тоста добавления в партии, в его шапке есть «← К партии {название}». Возврат восстанавливает курсор, вкладку, прокрутку и несохранённые правки партии. Из тренировки возвращаются сначала в репертуар, затем по этой кнопке в партию. - -## 2. Экран библиотеки репертуаров - -### 2.1. Задача и приоритет - -Главное — выбрать репертуар и увидеть, что именно требует внимания в каждом режиме. Это рабочая таблица, а не набор карточек и не сводка с графиками. - -### 2.2. Макет 1400 × 900 - -```text -┌──────────────────────────────────────────────────────────────────────────────────────────────┐ -│ ← Базы │ Тренировка дебюта [+ Создать] [Импорт PGN…] ⚙ Настройки │ -├──────────────────────────────────────────────────────────────────────────────────────────────┤ -│ [Репертуары] [Прежние линии · 8] [Найти…] (если >8) │ -│ │ -│ Название Включено ходов Белые: к повт. Чёрные: к повт. Обе стороны ⋯ │ -│ ──────────────────────────────────────────────────────────────────────────────────────────── │ -│ Сицилианская, Найдорф 126 12 — 3 новых пути ⋯ │ -│ Каро-Канн, за чёрных 84 — 7 давно: 4 ⋯ │ -│ Испанская, рабочая 238 4 4 не было ⋯ │ -│ │ -│ Показаны все репертуары · 3 │ -└──────────────────────────────────────────────────────────────────────────────────────────────┘ -``` - -Правила таблицы: - -- Строка открывается одиночным щелчком по названию или Enter. Выделенная строка, hover и фокус — существующие состояния таблиц библиотеки. -- «Включено ходов» — число уникальных тренируемых рёбер в полном PGN без учёта текущей глубины; disabled и недостижимые из-за disabled не входят. Транспозиционные повторы `(FEN4, UCI)` считаются один раз. -- Прочерк в `White`/`Black` означает, что в режиме нет целей либо режим ещё не использовался; tooltip раскрывает причину. Ноль выводится именно как `0`, когда цели есть, но ни одна не due. -- «Обе стороны» не показывает due: у режима нет SRS. Здесь выводится полезный факт — `N новых путей`, `давно не было: N`, `не было` или `последний проход: {дата}`. Он не складывается с одноцветной статистикой. -- Меню `⋯`: «Открыть», «Переименовать», «Импортировать PGN в этот репертуар…», «Экспортировать PGN…», «Удалить…». -- Порядок по умолчанию — сначала строки с незавершённой сессией, затем по названию. Сортировка по колонкам доступна независимо для due White и due Black; общего рейтинга или суммы режимов нет. -- Длинные списки виртуализируются. Поиск появляется только при более чем восьми репертуарах и фильтрует по названию без изменения порядка PGN внутри них. - -### 2.3. Создание и переименование - -**Создать** вставляет первую строку с полем названия и кнопками «Создать» / «Отмена»: - -- пустое название после trim не принимается; -- названия уникальны без учёта регистра и повторяющихся пробелов, поскольку они используются в компактном выборе назначения; -- длина — до 120 Unicode-символов, полный текст всегда доступен в tooltip и на экране репертуара; -- Enter создаёт, Esc отменяет; фокус остаётся в поле при ошибке; -- новый пустой репертуар из библиотеки получает стандартную начальную позицию. Пустой репертуар, созданный из FEN-партии, наследует её исходный FEN; -- после успешной атомарной записи открывается экран пустого репертуара, не тренировка. - -**Переименовать** превращает название в той же строке в поле. ID, PGN, disabled, очередь и вся статистика не меняются. Enter сохраняет, Esc отменяет, клик вне поля не теряет молча введённый текст, а оставляет режим редактирования до явного выбора. - -### 2.4. Удаление - -«Удалить…» раскрывает под строкой полосу: - -```text -Удалить «Испанская, рабочая» и всю её новую статистику? Исходные PGN и прежние линии не изменятся. -[Отмена] [Удалить репертуар] -``` - -- Удаляются только самодостаточный PGN репертуара, его источники-ссылки, настройки и новая статистика всех трёх режимов. -- Исходные базы, импортированные файлы и legacy line-run не затрагиваются. -- До успешной записи строка не исчезает. При ошибке остаётся полоса ошибки с «Повторить». -- Если есть незавершённая тренировка этого репертуара, она сначала закрывается без записи завершения; уже засчитанные попытки остаются в удаляемой статистике и исчезают только вместе с явным удалением. - -### 2.5. Пустая библиотека и прежние линии - -Пустое состояние занимает центральную область, без декоративных карточек: - -```text -Репертуаров пока нет -Создайте пустой или импортируйте PGN. Можно также выбрать ход в любой партии -и нажать «Добавить в репертуар…» — добавится путь только до этого хода. -[+ Создать] [Импорт PGN…] -``` - -Вкладка «Прежние линии · N» показывается только при наличии legacy `LineStats`. Это отдельная таблица: - -`Линия · Прохождения · Ошибки последнего · Лучшее · Чистая серия · Последние · Дата`. - -- Подсказанные прохождения обозначаются `*`, как раньше. -- Никаких колонок «точность хода», «следующий ход» или per-move ошибок здесь нет: старый формат этого не знает. -- Legacy-записи не превращаются автоматически в новые репертуары, не получают `due_at` и не суммируются с новыми попытками. -- Android продолжает читать и записывать эти данные прежним способом. - -### 2.6. Ошибки библиотеки - -- Нечитаемый `training.json`: библиотека PGN открывается для просмотра и экспорта, но создание/изменение статистики и запуск тренировки останавливаются. Сверху постоянная полоса «Не удалось прочитать статистику: {путь}. Файл не заменён» и «Повторить». Пустое хранилище молча не создаётся поверх повреждённого. -- Ошибка записи: операция остаётся видимой как несохранённая, появляется полоса «Не удалось сохранить изменения · Повторить». Успешный тост запрещён. -- Один повреждённый репертуар не скрывает остальные: его строка остаётся с текстом «Ошибка PGN», открывается диагностика и экспорт сохранённого исходного текста, если он доступен. -- Импорт и построение индекса — фоновые операции с прогрессом и отменой. Отмена не оставляет новый репертуар или часть слияния. - -## 3. Добавление из партии - -### 3.1. Точка входа - -На desktop пункт меню хода и общего меню «Учить дебют до этого хода» заменяется на **«Добавить в репертуар…»**. - -- Доступен только на выбранном ходе. В начальной позиции — неактивен с причиной «Выберите ход, до которого добавить». -- Если на пути есть учебный null move `--`, пункт неактивен: «В пути есть пропуск хода (--)». Такой путь не превращается в обычные легальные ходы. -- Справа можно показывать название последнего совместимого репертуара, но не число прохождений: новая статистика не line-run. - -### 3.2. Один компактный выбор назначения - -Пункт открывает привязанную к ходу панель шириной 360, не отдельный мастер: - -```text -Добавить в репертуар -1.e4 c5 2.Nf3 d6 3.d4 cxd4 4.Nxd4 — 7 полуходов -(•) Сицилианская, Найдорф -( ) Испанская, рабочая -( ) Новый репертуар: [Сицилианская за белых____________] -[Отмена] [Добавить] -``` - -- Показываются только репертуары с совместимой начальной позицией. При более чем восьми — поле поиска внутри той же панели. -- По умолчанию выбран последний репертуар, если он совместим, иначе первый; «Новый репертуар» всегда доступен и наследует исходный FEN. -- Видна точная линия в компактной форме и число полуходов. Полный SAN — tooltip; прокрутка длинной строки не растягивает окно. -- Enter — «Добавить», Esc/клик вне — отмена. После закрытия фокус возвращается исходному ходу. - -### 3.3. Что именно добавляется - -1. Путь от исходной позиции до выбранного хода **включительно**, даже если часть пути находится внутри RAV. -2. Комментарии и NAG корня и узлов этого пути, включая комментарии непосредственно до/после выбранного хода. -3. Исходный FEN и порядок ходов пути. -4. **Не добавляются**: продолжение после выбранного хода, соседние ветки любого уровня, другие партии базы и служебные стрелки/оценки временной партии. -5. Добавление не запускает тренировку, не меняет исходную `revision`, не создаёт Undo в исходной партии и не меняет её файл. - -После успешной записи исходная партия остаётся на том же ходу. Тост: - -`Добавлено в «Сицилианская, Найдорф»: новых ходов: 4 · совпало: 3 · [Открыть]`. - -Если изменились только аннотации: `Путь уже был в репертуаре; добавлены аннотации: N`. При полном дубле: `Уже в репертуаре — изменений нет`. Эти сообщения не означают запуск или сброс статистики. - -### 3.4. Источник и возврат - -С репертуаром сохраняются навигационные сведения об источнике: файл, индекс записи, контрольное значение содержимого и UCI-путь. Они не являются хранилищем репертуара. - -- «Открыть источник» сначала проверяет файл и линию. При изменении/удалении базы выводится «Источник изменился или недоступен; репертуар сохранён» — случайная партия по прежнему индексу не открывается. -- Переименование или удаление источника не влияет на дерево, очередь и статистику. -- У одной ветки может быть несколько источников; просмотр показывает их списком, без копирования дерева. - -## 4. Импорт PGN и слияние - -### 4.1. Назначение - -- «Импорт PGN…» в библиотеке создаёт **один новый репертуар** из всего выбранного файла. -- «Импортировать PGN в этот репертуар…» на экране/строке добавляет весь файл в существующий. -- Multi-game PGN **не разбивается на репертуары по числу партий**: все записи сливаются в одно дерево, как линии одного репертуара. -- Имя нового репертуара по умолчанию — имя файла без расширения; при конфликте добавляется числовой суффикс, который можно сразу изменить inline. - -### 4.2. Предпросмотр без модального окна - -После системного выбора файла в библиотеке или над деревом раскрывается панель: - -```text -Импорт: repertoire.pgn -Записей PGN: 24 · новых ходов: 386 · совпадающих путей: 51 · ветвей: 73 -Комментарии и NAG: сохранить · максимальная глубина: 48 полуходов -При текущей глубине 20 в тренировку войдёт 214 целей из 386 -⚠ 2 ветки содержат «--»: сохранятся для чтения, в тренировку не попадут -[Отмена] [Импортировать в один репертуар] -``` - -Предпросмотр обязан показывать масштаб **до записи**: записи, новые/совпадающие ходы, число ветвей, максимальную глубину и объём при текущей глубине. Для нового репертуара в расчёте уже стоит 20 полуходов. Полные партии не объявляются автоматически «примерными» и не обрезаются. - -### 4.3. Правила слияния - -1. Сначала разбирается и проверяется весь файл; запись выполняется один раз после подтверждения. Частичный скрытый импорт запрещён. -2. Общий префикс совпадает по стартовой позиции и последовательности шахматных ходов, не по строке SAN. Порядок существующих детей не меняется; новые дети добавляются в порядке записей PGN и RAV. -3. Если дерево пустое, первая основная линия первой записи становится основной. Multi-game записи добавляют свои ответвления от общего корня; заголовки `White`, `Black`, `Event` не создают самостоятельные репертуары. -4. Точный повтор пути с теми же аннотациями — no-op: нет новых узлов, дублей комментариев или сброса истории. -5. Совпавшие узлы с новыми аннотациями не теряют ни старые, ни новые данные: - - отличающийся комментарий добавляется отдельным блоком в порядке импорта; - - одинаковый комментарий повторно не добавляется; - - NAG объединяются как набор без числовых дублей; разные оценочные NAG сохраняются и показываются оба; - - disabled/enable и ручная глубина существующего репертуара не сбрасываются. -6. Новые ветки по умолчанию enabled. Повторный импорт ранее отключённой существующей ветки **не включает её сам**. -7. Изменения PGN не удаляют learning-записи неизменных `(FEN4, UCI)`. Удалённая из нового импорта ветка не удаляется из существующего репертуара: импорт только добавляет и дополняет аннотации. -8. Все записи должны иметь совместимую исходную позицию. Разные FEN в одном файле не смешиваются молча: импорт останавливается с номерами записей и текстом «В одном репертуаре должна быть одна исходная позиция». Для пустого репертуара первый FEN задаёт корень. -9. `fullmove=0` нормализуется существующим правилом с диагностикой; старт чёрных и нумерация сохраняются. Счётчики halfmove/fullmove не участвуют в FEN4-транспозициях, но исходный FEN остаётся в PGN. -10. Учебный `--`, неподдерживаемые токены и неиграбельные участки сохраняются для чтения/экспорта и получают диагностику. Узлы после невосстановимого нелегального хода не угадываются; такой файл отклоняется целиком, а не обрезается молча. Играбельные ветки, изолированные корректно распознанным `--`, не попадают в очередь. -11. Legacy-кодировки проходят существующий импорт с замечаниями. Исходный файл не перекодируется и не перезаписывается; внутренний снимок может быть нормализованным UTF-8 PGN, но обязан сохранить дерево и содержимое аннотаций. - -После успеха новый репертуар открывается на дереве; при добавляющем импорте остаётся текущий экран и активный ход. Показывается сводка фактически записанных изменений, не тренировка. - -## 5. Экран одного репертуара - -### 5.1. Задача и приоритет - -Здесь пользователь читает аннотированное дерево, явно ограничивает объём и запускает выбранный вид повторения. Доска и дерево важнее статистики; статистика не превращает экран в dashboard. - -### 5.2. Макет 1400 × 900 - -```text -┌──────────────────────────────────────────────────────────────────────────────────────────────┐ -│ ← Репертуары │ Сицилианская, Найдорф [Импорт PGN…] [Экспорт PGN] [⋯] ⚙ Настройки │ -├───────────────────────────────────────────────────────────────────┬──────────────────────────┤ -│ │ Режим: [Белые|Чёрные|Оба] │ -│ │ Очередь: [По расписанию ▾] │ -│ ДОСКА │ Глубина: [20] полуходов │ -│ (активная позиция) │ Область: Весь репертуар ⌄ │ -│ │ В области: 86 целей │ -│ │ К повторению: 12 · новых: 34│ -│ │ [▶ Начать: 12 к повторению] │ -│ ├──────────────────────────┤ -│ │ [Дерево] [Статистика] │ -│ │ 1 e4 c5 │ -│ │ 2 Nf3 d6 │ -│ │ ├ 2…Nc6 ⌀ не учить │ -│ │ └ 2…e6 ⇄ 2 пути │ -│ │ 3 d4 cxd4 │ -│ │ … комментарии и NAG … │ -│ │ ────────────────────────── │ -│ │ Выбран 2…d6 · запланирован │ -│ │ Верных: 8/10 · следующий:… │ -│ ├──────────────────────────┤ -│ │ ⏮ ◀ ▶ ⏭ │ 🔃 │ ☰ │ -└───────────────────────────────────────────────────────────────────┴──────────────────────────┘ -``` - -Правая панель — существующая боковая панель партии, не набор самостоятельных карточек. Настройки тренировки закреплены сверху; дерево прокручивается независимо. Рамка только отделяет функциональные области. - -### 5.3. Выбор режима, области, глубины и очереди - -**Режим** — три сегмента: - -- `Белые` — target-ходы только белых, ответы программы только за чёрных; -- `Чёрные` — target-ходы только чёрных, ответы программы только за белых; -- `Обе стороны` — пользователь делает каждый полуход, автоматических ответов нет. - -Последний выбранный режим и очередь запоминаются отдельно для репертуара. Смена режима не переносит очередь, курсор обзора, due или статистику другого режима. - -**Область** — компактный selector над деревом: - -- `Весь репертуар`; -- `От хода {SAN}` после команды контекстного меню «Тренировать эту ветку» или кнопки «Сделать областью» у выбранного хода. - -Для ветки показывается путь и отдельная `×` для сброса к всему репертуару. Подводящий путь до родителя выбранного хода — автоматический контекст; сам выбранный ход проверяется. Активная позиция на доске, выделенный ход в дереве и назначенная область — разные состояния: область обозначена значком `▶` и текстовой строкой, не только цветом. - -**Глубина**: - -- числовое поле от 1 до 999 полуходов с кнопками `−` / `+` и отдельным пунктом меню «Без ограничения»; -- по умолчанию 20; значение сохраняется на репертуар; -- глубина 20 разрешает рёбра с номерами 1…20 от корня, а не 20 ходов от начала выбранной ветки; -- изменение глубины сразу пересчитывает цели и знаменатели, не удаляет статистику вне лимита; -- при FEN-старте глубина всё равно считается от корня репертуара, а не от номера полного хода в исходном FEN. - -**Очередь** зависит от режима: - -| Режим | Варианты | -|---|---| -| White / Black | `По расписанию`, `Подряд`, `Сначала новые и давние` | -| Both | `По дереву`, `Сначала новые и давние` | - -В `Both` нет SRS, due и досрочного повторения. Под выбором всегда есть короткое пояснение: для обзоров — `Сроки повторений не меняются`, для SRS — `Сначала ходы с наступившим сроком`. - -**Главная кнопка** формулирует фактический запуск: - -- `Начать: 12 к повторению`; -- если due=0 и есть непредставленные в SRS — `Начать: 10 новых` (или меньше, если осталось меньше); -- для обзора — `Начать обзор: 86 ходов` / `Начать проход веток`; -- если доступных ходов нет — неактивна, а причина находится на её месте, не только в tooltip. - -### 5.4. Дерево и действия над ветками - -Используется существующая нотация с вложенными вариантами, комментариями и NAG, только чтение ходов. В просмотре доступны все узлы, включая disabled и глубже лимита. - -Обозначения: - -- disabled: `⌀` + текст `не учить` у корня ветки; вся отключённая область дополнительно получает приглушённый текст, но остаётся контрастной и читаемой; -- глубже лимита: небольшой текст `>20` у первого исключённого хода; это не disabled; -- транспозиция: `⇄ N путей`, раскрытие показывает SAN-пути и позволяет перейти к каждому; -- активный ход — существующая заливка курсора; выбранная область — `▶` слева; раскрытая ветка — disclosure-стрелка. Эти состояния не сливаются. - -Контекстное меню хода: - -- «Показать позицию»; -- «Тренировать эту ветку»; -- «Не учить ветку» / «Вернуть в тренировку»; -- «Показать статистику хода»; -- «Открыть источник», если источник существует. - -**Не учить ветку** отключает выбранное ребро и недостижимое через него поддерево для будущих очередей и ответов программы. PGN, комментарии, NAG, экспорт и прежняя история сохраняются. Повторное включение возвращает прежние записи без дублей. - -Если та же позиция или ход достижимы другой enabled-транспозицией, логическая цель остаётся в очереди по этому альтернативному пути. Поэтому disabled — свойство PGN-ветки, а не молчаливая глобальная блокировка FEN во всём репертуаре. - -Редактирование ходов, promote/delete и массовые операции не входят в этот объём. «Экспорт PGN» выписывает всё дерево, включая disabled и хвосты глубже лимита. - -### 5.5. Пустой репертуар и подготовка дерева - -Пустой репертуар показывает исходную доску и вместо нотации: - -```text -В репертуаре пока нет ходов -[Импорт PGN…] -Или откройте партию, выберите последний ход нужной линии -и нажмите «Добавить в репертуар…». -``` - -Кнопки режима и глубины видны, запуск неактивен. После большого импорта дерево доступно для чтения, а пока строится FEN4-индекс, вместо запуска — `Готовим дерево… {прогресс}` и «Отмена». Тренировка не стартует на частично построенном индексе. - -## 6. Единые правила тренировки - -### 6.1. Ввод и позиция - -- На доске можно ходить только фигурами стороны, чей ход наступил. В `White`/`Black` ввод противоположной стороны недоступен; в `Both` доступны обе по очереди. -- Нелегальная попытка не создаёт шахматный ход, не считается ошибкой и не меняет статистику. -- Превращение всегда открывает существующий выбор фигуры, независимо от настройки автоферзя. Ферзь вместо коня — другой UCI и ход вне цели/вариантов. -- Ориентация: `White` — белыми вниз, `Black` — чёрными вниз, `Both` — как на экране репертуара. `F` переворачивает; автоматического переворота после полухода нет. -- Просмотр уже сыгранных ходов разрешён. Попытка хода из прошлого возвращает к текущему концу без ошибки. -- Движок, Справочник, редактирование, сохранение как партия и вставка PGN выключены. `L` и `Shift+A` дают прежний тост «Во время тренировки движок выключен». - -### 6.2. Ошибка и flash - -Легальный ход вне разрешённого набора: - -1. фигура на 400 мс встаёт на выбранное поле, клетки from/to получают существующую красную заливку ошибки; -2. звучит `Wrong`, счётчик неверных попыток увеличивается ровно на 1; -3. новый ввод на эти 400 мс блокируется; -4. позиция возвращается, красная заливка снимается, сообщение остаётся до правильного хода; -5. каждая повторная попытка снова считается. - -Сообщения различают модели: - -- одноцветный режим: `✗ Сейчас в репертуаре ожидается другой ход`; -- `Both`: `✗ Этот ход вне включённых вариантов`. - -Disabled-ход и ход глубже текущего лимита в активной тренировке считаются вне разрешённого набора. Не используется оценка «объективно хороший/плохой» — движка нет. - -### 6.3. Подсказка и спойлеры - -- После **третьей неверной попытки на текущем задании/позиции** появляется ссылка «Показать ход». До этого правильный ход не раскрывается. -- Стрелка появляется только по явному запросу. В одноцветном режиме она показывает target-UCI; в `Both` — первый enabled-ребёнок в каноническом PGN-порядке. -- После подсказки в `Both` любой enabled-ребёнок по-прежнему принимается, а не только показанный. -- Пользователь сам делает ход. Подсказка помечает задание и весь проход `с подсказкой`, сбрасывает чистую серию и не даёт чистого результата. -- До попытки скрыты будущие ветки, комментарии, NAG, авторские стрелки, следующие SAN и статистика, способная назвать ответ. В нотации — только контекст и фактически сыгранный текущий путь. -- Во время тренировки нельзя переключиться на полное дерево. После завершения открываются аннотации только пройденного пути; полное дерево доступно через «К репертуару». - -## 7. Одноцветный режим: White / Black - -### 7.1. Задание - -Единица — конкретный target-ход выбранного цвета. Очередь никогда не превращается в общий проход за обе стороны. - -Начало задания: - -1. Программа восстанавливает канонический путь к позиции **перед target-ходом**. Подводящие ходы обеих сторон, включая ходы цвета пользователя, показываются как контекст и не создают попыток. -2. Все автоматические ходы соответствуют enabled-дереву, области и глубине. При нескольких путях к FEN4 используется самый короткий enabled-путь; при равенстве — первый в PGN-порядке. -3. Верхняя панель сообщает `Белые · по расписанию`, номер задания в текущей сессии и `♔ ход белых` / `♚ ход чёрных`. SAN цели не показывается. -4. Если следующее задание продолжает текущий путь, программа доходит до него только ходами противоположной стороны и нужным контекстом. Если задание в другой ветке, переход к нему выполняется без имитации неправильного ответа на доске. - -### 7.2. Ответ пользователя - -- **Target-UCI:** правильный ответ. Ход засчитывается, статистика записывается. Если следующий ход принадлежит программе и есть enabled-ребёнок внутри глубины, программа делает один ответ из канонического продолжения; этот ответ не является попыткой и не меняет очередь. Если ответа нет, задание нормально завершается на раннем листе. -- **Другой enabled-ребёнок того же пользовательского цвета, но не текущая цель:** отдельный `try again`, не ошибка. Фигура возвращается после 250 мс, нейтральная рамка вместо красной, звука `Wrong` нет: - - `Этот ход есть в репертуаре, но сейчас повторяется другой · Попробуйте ещё раз`. - - Он не увеличивает mistakes, не меняет accuracy, streak, hint counter или due. Позже альтернатива остаётся самостоятельной целью очереди. -- **Легальный ход вне enabled-дерева, disabled-ребёнок или ход за глубиной:** обычная неверная попытка по §6.2. - -Никакой enabled-альтернативы, автоматически засчитанной как target, здесь нет: этим одноцветный режим принципиально отличается от `Both`. - -### 7.3. Завершение задания и сессии - -После target-хода показывается короткое `✓ Верно`; при ошибках/подсказке — `✓ Принято · будет повторено раньше`. Следующее задание не начинается, пока результат текущего не сохранён. - -Сессия заканчивается, когда исчерпана выбранная очередь/пакет новых либо пользователь вышел. Лист раньше глубины — нормальное завершение пути, не ошибка и не повод добавить ход извне дерева. - -Итог SRS/обзора показывает: - -`Заданий: N · правильных: N · неверных попыток: N · с подсказкой: N`. - -Для SRS дополнительно — `К повторению сейчас: 0` и действия из §9.3. Нет процента «дебют выучен». - -## 8. Режим Both: проход за обе стороны - -### 8.1. Независимая модель - -`Both` не использует target-SRS и не требует заранее выбранный ход. Пользователь делает **каждый полуход** от начала области до границы. Программа не отвечает ни за белых, ни за чёрных. - -На каждой позиции: - -- разрешённый набор — все enabled-дети канонической FEN4-группы внутри области и глубины; -- **любой** из них принимается, записывается как фактически сыгранный ход и ведёт по его ветке; -- отсутствие `try again`: не бывает «верный ход, но не тот путь»; -- любой легальный ход вне набора — ошибка по §6.2; -- disabled-ребёнок и продолжение за глубиной — вне набора. - -Верхняя панель показывает `Обе стороны · проход ветки`, `Полуход 7 из не более 20` и текущую сторону. Если лист наступит раньше, заранее обещать точное число полуходов нельзя. Нотация пополняется фактическим путём, а не заранее выбранной mainline. - -### 8.2. Лист, глубина и повторение позиции - -Проход успешно заканчивается в одном из случаев: - -1. нет enabled-детей — `Ветка завершена`; -2. сыгран последний разрешённый полуход глубины — `Достигнута глубина: 20 полуходов`; -3. каноническое продолжение привело к FEN4, уже встречавшемуся в этом проходе, — `Позиция повторилась · проход завершён`. Это защита от цикла при FEN4 без счётчиков, не ошибка. - -Пустая область или отсутствие enabled-детей **до первого пользовательского хода** не считается успешным проходом: показывается состояние настройки «Нет включённых ходов в этой области». - -### 8.3. Повтор пути и новый проход - -Итог содержит две разные команды: - -- **«Повторить путь»** — начать ту же область с тем же предложенным маршрутом. Это не превращает прошлый путь в фиксированную линию: на развилке любой enabled-ребёнок снова принимается. -- **«Новый проход»** — получить следующий предложенный маршрут по выбранной очереди веток. - -Итог: `Пройдено полуходов: N · ошибок: N · с подсказкой: да/нет`. В нотации фактического пути ошибки отмечаются `×N` у позиции, а не присваиваются произвольному «ожидаемому» SAN. - -Если предложенный маршрут A пользователь сменил на enabled-маршрут B, статистику получает B; A не отмечается пройденным. Это правило обязательно и для «По дереву», и для «Сначала новые и давние». - -## 9. Очереди и расписание - -### 9.1. Общие статусы - -Статусы видимы текстом и не опираются только на цвет: - -| Статус | Значение | -|---|---| -| `Новый` | Для этого режима ещё не было ни одной оценённой попытки с этим ходом/путём | -| `К повторению` | Только White/Black SRS: `due_at <= now` | -| `Запланирован` | Есть будущий `due_at`; рядом видна дата | -| `Вне расписания` | Ход уже встречался в обзоре, но SRS-срок ему не назначался | -| `Обзор` | Маркер текущей досрочной/последовательной сессии; не уровень mastery | -| `Давно не было` | Порядок по `last_seen`, без выдуманного порога в днях | -| `Не учить` | Исключено из текущих очередей; история сохранена | - -Нет статусов `Learnt`, `Mastered` или процента «выучено». Чистая серия — только факт серии, не доказательство долговременного знания. - -### 9.2. White/Black: три очереди - -**По расписанию (SRS)** - -1. Сначала все due выбранной области и глубины, по `due_at`, затем по каноническому PGN-порядку. Одна FEN4+UCI-цель появляется один раз. -2. Unseen не затапливают due. Новые вводятся отдельными явными пакетами **до 10 целей** в порядку depth-first PGN mainline-first. -3. В пакет введения входят `Новый` и `Вне расписания`; сначала новые, затем виденные без срока. -4. Успех отодвигает срок, ошибка приближает. Досрочные/последовательные обзоры сроки не меняют. - -Фиксированные правила v1, без экрана коэффициентов: - -- чистый правильный ответ на новой цели или после lapse — `due = now + 1 день`; -- следующий чистый правильный ответ — прежний интервал ×2, минимум 1 день, максимум 365 дней; -- каждая неверная попытка — `due = now + 10 минут`, чистая серия сбрасывается, цель помечается lapse; -- правильный ответ после ошибки в том же показе или после подсказки засчитывается как ответ, но оставляет `due = now + 10 минут`; следующий чистый успех после этого снова даёт 1 день; -- `try again` ничего в расписании не меняет; -- короткий срок не означает немедленный показ раньше других due. - -**Подряд (Review in order)** - -- Depth-first обход enabled-целей, mainline-first, без повторов транспозиций. -- Сроки SRS не меняются. Попытки, ошибки, подсказки и `last_seen` записываются. -- Место обзора запоминается отдельно для `(репертуар, режим, область)`. После последней цели итог предлагает «Новый проход» — курсор возвращается к первой. -- При изменении дерева/глубины курсор переносится на ближайшую следующую существующую цель; удалённая/disabled не показывается, дублей нет. - -**Сначала новые и давние (Least recent/unseen)** - -- Сначала все `Новый` в PGN-порядке, затем остальные по возрастанию `last_seen`; при равенстве — PGN-порядок. -- Сроки SRS не меняются. Это обзор, а не скрытое введение всего дерева в расписание. -- После цикла доступен новый проход по обновлённым `last_seen`. - -### 9.3. Когда due = 0 - -Никакого автоматического перехода ко всем unseen или будущим целям нет. - -Итог `К повторению сейчас: 0` содержит независимые действия: - -1. **«Добавить новые: 10 из N»** — явно ввести следующий пакет. Если N=0, кнопки нет. -2. **«Повторить будущие раньше»** — только запланированные цели, ближайший `due_at` первым. На всём таком проходе видна полоса `Досрочный обзор · сроки не меняются`; попытки и last_seen пишутся, `due_at` и интервалы остаются прежними. -3. **«Обзор подряд»** — переключиться на последовательный обзор области. -4. **«К репертуару»**. - -Если нет ни новых, ни будущих, остаются только обзор и возврат. Первый запуск нового репертуара использует ту же явную формулировку на главной кнопке `Начать: 10 новых`, поэтому отдельного пустого SRS-экрана в этой ситуации нет. - -### 9.4. Both: очередь путей, не целей - -- **По дереву:** depth-first предложение root-to-boundary маршрутов в PGN-порядке. Курсор цикла хранится отдельно для области. -- **Сначала новые и давние:** сначала пути, ни разу не завершённые в `Both`, затем пути по самому давнему фактическому завершению; при равенстве — PGN-порядок. -- Любое enabled-отклонение меняет фактический путь. Записывается он; предложенный, но не пройденный путь сохраняет прежний статус. -- Даты due, интервалы и пакеты новых одноцветного режима здесь не создаются и не изменяются. -- Список путей генерируется по мере необходимости; большое дерево не разворачивается целиком ради построения очереди. - -## 10. Транспозиции FEN4 - -1. Ключ позиции — нормализованные первые четыре поля FEN: фигуры, сторона хода, права рокировки и **легальное** en passant. Halfmove/fullmove не входят. -2. В PGN все узлы и пути остаются отдельными. FEN4-индекс — производный слой, не переписывание дерева в DAG. -3. Внутри репертуара и одного режима `(FEN4, UCI)` имеет одну learning-запись и одно место в очереди. -4. Кандидаты продолжения — объединение enabled-детей всех достижимых узлов FEN4-группы. Порядок: сначала дети первого узла в PGN depth-first, затем новые ходы из остальных узлов в том же порядке. -5. Для конкретного UCI выбирается одно каноническое продолжение: первое enabled-ребро в указанном порядке, после чего работа продолжается с FEN4-группой результата. Поэтому продолжение не дублируется, а проход не заканчивается просто из-за транспозиции. -6. Путь и путевые комментарии не теряются: в просмотре `⇄ N путей` раскрывает их. В тренировке контекст к цели — кратчайший enabled-путь, tie-break по PGN. -7. Disabled-ветка исключает свои рёбра, но не блокирует тот же логический ход, если он достижим через другой enabled-путь. -8. Статистика одинаковых позиций разных репертуаров не объединяется. `White`, `Black`, `Both` тоже имеют независимые записи. -9. Цикл по FEN4 в `Both` завершается по правилу §8.2; в одноцветном target-режиме бесконечного автоматического прохода нет. - -## 11. Статистика без ложного mastery - -### 11.1. Что видно на каждом уровне - -| Уровень | White / Black | Both | -|---|---|---| -| Текущее задание/позиция | Номер задания, ошибки сейчас, подсказка, режим очереди | Полуходы текущего пути, ошибки сейчас, подсказка | -| Ход | Попытки, correct, wrong, hints, `correct/(correct+wrong)`, чистая серия, last seen, last attempt, next due, последние неверные SAN | Сколько раз ход фактически сыгран, last played; ошибки и подсказки относятся к позиции перед ходом, а не к выдуманной единственной цели | -| Ветка | Включено целей, новых, due, запланировано, виденных; последние ошибки; disabled исключены из знаменателя | Завершения, чистые/с подсказкой, ошибки, последний проход, фактические пути, новые/давние | -| Репертуар | Отдельные числа White и Black: enabled в области, seen/total, due, unseen, unscheduled | Завершённые пути/всего доступных, новые, last completion; без due | -| История | Дата, режим, область, тип очереди, задания, correct/wrong/hints, завершена/прервана | Дата, область, фактический путь, полуходы, ошибки, подсказка, завершён/прерван | - -Правила представления: - -- Точность всегда подписана как `Верных: 8 из 10`, рядом может быть процент; голый процент без знаменателя запрещён. -- Подсказки показываются отдельно и не входят в чистые серии. -- Одноцветный `try again` не увеличивает ни правильные, ни ошибочные попытки; при желании показывается только в текущем сообщении, не в исторической accuracy. -- В `Both` неверный ход вне дерева записывается на текущую позицию с фактическим wrong UCI. Его нельзя присваивать первому enabled-ребёнку как ошибку этого ребра. -- Disabled и глубина меняют только текущий знаменатель. История не переписывается задним числом; в ней видна область/глубина на момент события. -- «Показано X из Y» не называется «Выучено X %». -- Расширенные графики, resistant-наборы и массовые операции отсутствуют. - -### 11.2. Вкладка «Статистика» на экране репертуара - -Без графического dashboard. Сверху — переключатель `Белые | Чёрные | Обе стороны`, затем обычные таблицы: - -1. `Сводка` — числа из таблицы §11.1 только выбранного режима. -2. `Ходы` — виртуализированная таблица с фильтрами `Все / К повторению / Новые / Давно не было / С ошибками / Не учить`; сортировка по сроку, last_seen и числу ошибок. -3. `История` — последние события выбранного режима, новые сверху, ограниченная страницами/виртуализацией. - -Выбор строки «Ходы» показывает позицию на доске и соответствующий узел/все транспозиционные пути в дереве. Это просмотр, не запуск и не раскрытие ответа в активной тренировке, поскольку экран статистики из тренировки недоступен. - -### 11.3. Незавершённое - -- Выход или «Сначала» не создаёт завершение пути/сессии. -- Уже оценённые новые per-move события сохраняются: они реально произошли. Незавершённый `Both` не увеличивает число завершений пути; незавершённая SRS-сессия не обнуляет уже записанные ответы. -- При возврате в пределах одного запуска приложения на экране репертуара видна полоса `Незавершённая тренировка: {режим} · {прогресс}` с «Продолжить» и «Начать заново». «Начать заново» отбрасывает только черновик текущего пути/показа, не историю. -- После перезапуска приложения черновик не восстанавливается; история содержит событие `прервана`, если уже были оценённые действия, и никогда не показывает его как завершённое. -- Старый line-run ведёт себя по-прежнему: незавершённое старое прохождение не добавляет `runs`. - -## 12. Экран тренировки и адаптивные макеты - -### 12.1. 1400 × 900 - -```text -┌──────────────────────────────────────────────────────────────────────────────────────────────┐ -│ ← К репертуару │ Сицилианская, Найдорф · Белые · По расписанию ⚙ Настройки │ -├───────────────────────────────────────────────────────────────────┬──────────────────────────┤ -│ │ ┌──────────────────────┐ │ -│ │ │ Задание 4 · ♔ белые │ │ -│ ДОСКА │ │ К повторению: 12 │ │ -│ │ └──────────────────────┘ │ -│ │ 1 e4 c5 │ -│ │ 2 Nf3 d6 │ -│ │ … только текущий путь … │ -│ │ ┌──────────────────────┐ │ -│ │ │ Ошибок: 2 │ │ -│ │ │ Показать ход (после 3)│ │ -│ │ └──────────────────────┘ │ -│ │ ⏮ ◀ ▶ ⏭ │ 🔃 │ ↻ │ ✕ │ -└───────────────────────────────────────────────────────────────────┴──────────────────────────┘ -``` - -Используются две функциональные рамки текущего тренера — задание сверху и состояние пользователя снизу. Не добавляются графики, KPI-карточки, цветные плитки или второй ряд панелей. - -В `Both` верхняя рамка: `Полуход 7 · ♚ чёрные` / `до глубины 20 или конца ветки`. Нижняя: `Ошибок: N` / сообщение или «Показать ход». - -Итог занимает место верхней/нижней функциональной области по образцу существующего `result_strip`; нотация остаётся видимой. Для due=0 итог раскрывается на высоту явных действий из §9.3, но не открывает модальное окно. - -### 12.2. Библиотека при 640 - -При 640 × 480 и 640 × 900 таблица остаётся основным содержимым; высокое окно добавляет строки, а не новые панели. - -```text -┌────────────────────────────────────────────────────────────┐ -│ ← Базы │ Тренировка дебюта [+ Создать] [Импорт] [⚙] │ -│ [Репертуары] [Прежние линии] │ -│ Название Б: к повт. Ч: к повт. ⋯ │ -│ Сицилианская, Найдорф 12 — ⋯ │ -│ Каро-Канн, за чёрных — 7 ⋯ │ -└────────────────────────────────────────────────────────────┘ -``` - -- Скрываются «Включено ходов», «Обе стороны» и итоговая строка; они доступны на экране репертуара. Название сокращается с многоточием, полное — tooltip. -- Создание/переименование и подтверждение удаления переносят текст на две строки, кнопки остаются видимыми без горизонтальной прокрутки. -- Длинные EN/DE-подписи действий могут переносить шапку на две строки; `+ Создать` и `Импорт` не обрезаются до непонятных значков. - -### 12.3. Репертуар при 640 × 480 - -Используется правило «рядом» из `narrow-windows.md`: доска слева не меньше `BOARD_MIN`, правая панель не уже 240. - -```text -┌───────────────────────────────┬────────────────────────────┐ -│ ← Репертуары │ Сицилианская… │ Режим: [Белые ▾] │ -│ │ Очередь: [По расписанию ▾] │ -│ ДОСКА │ Глубина: [20] · Вся ветка │ -│ │ 12 к повт. · 34 новых │ -│ │ [▶ Начать] │ -│ │ [Дерево] [Статистика] │ -│ │ 1 e4 c5 │ -│ │ 2 Nf3 d6 │ -│ │ ⏮ ◀ ▶ ⏭ │ 🔃 │ ☰ │ -└───────────────────────────────┴────────────────────────────┘ -``` - -Вместо трёх сегментов при недостатке ширины — dropdown режима; механика не меняется. Область выводится второй строкой с `×`, полный путь — tooltip. Числа не переносятся на кнопку запуска. Дерево и статистика прокручиваются, настройки остаются закреплены. - -### 12.4. Репертуар и тренировка при 640 × 900 - -По формуле `narrow-windows.md` используется стопка: доска сверху, нижняя панель с тем же содержимым. Нижняя панель получает не меньше 300 точек, если это возможно при `BOARD_MIN`; разделитель можно тянуть. - -- Настройки запуска занимают две строки: `Режим · Очередь` и `Глубина · Область`, затем сводка и главная кнопка. Дерево остаётся минимум с тремя видимыми строками и собственной прокруткой. -- В тренировке сверху доска, снизу задание, сыгранная нотация и состояние пользователя. Функциональные рамки не скрывают нотацию целиком; сообщение об ошибке может временно увеличить нижнюю рамку. -- При 640 × 480 остаётся компоновка «рядом», а не стопка: низкое окно не складывается. - -### 12.5. Переполнение и HiDPI - -- Раскладка выбирается по доступным `W/H`, а не по фактической ширине текста прошлого кадра. Медленное изменение окна не вызывает мигания. -- Длинные названия и пути сокращаются только там, где есть tooltip; ошибки, причины недоступности и кнопки действий переносятся полностью. -- Все критичные состояния проверяются при 100/125/150/200 % масштаба. Подсветка, фокус, disabled, ошибка и транспозиция различимы не только цветом. - -## 13. Подписи RU / EN / DE - -Все строки идут через существующую систему перевода; числа и формы множественного числа не склеиваются из отдельных слов. Как минимум добавляются следующие ключи и смысловые варианты: - -| RU | EN | DE | -|---|---|---| -| Тренировка дебюта | Opening training | Eröffnungstraining | -| Репертуары | Repertoires | Repertoires | -| Добавить в репертуар… | Add to repertoire… | Zum Repertoire hinzufügen… | -| Импорт PGN… | Import PGN… | PGN importieren… | -| Импортировать в один репертуар | Import into one repertoire | In ein Repertoire importieren | -| Белые / Чёрные / Обе стороны | White / Black / Both sides | Weiß / Schwarz / Beide Seiten | -| По расписанию | Spaced schedule | Nach Zeitplan | -| Подряд | Review in order | Der Reihe nach | -| Сначала новые и давние | Least recent and unseen first | Neue und älteste zuerst | -| К повторению | Due | Fällig | -| Новый | Unseen | Neu | -| Вне расписания | Unscheduled | Nicht eingeplant | -| Досрочный обзор · сроки не меняются | Early review · schedule unchanged | Vorzeitige Wiederholung · Zeitplan unverändert | -| Добавить новые: 10 из N | Introduce new: 10 of N | Neue hinzufügen: 10 von N | -| Повторить будущие раньше | Review future moves early | Künftige Züge früher wiederholen | -| Не учить ветку | Disable branch | Variante nicht lernen | -| Вернуть в тренировку | Enable for training | Wieder trainieren | -| Показать ход | Show move | Zug zeigen | -| Попробуйте ещё раз | Try again | Noch einmal versuchen | -| С подсказкой | With hint | Mit Hinweis | -| Повторить путь / Новый проход | Repeat path / New run | Pfad wiederholen / Neuer Durchgang | -| Незавершённая тренировка | Unfinished training | Nicht abgeschlossenes Training | -| Не удалось сохранить изменения | Could not save changes | Änderungen konnten nicht gespeichert werden | - -Названия режимов данных остаются `White`, `Black`, `Both`; переводится только UI. Статус не переводится как «выучено». Длинные немецкие строки являются обязательным fixture для проверки компоновки. - -## 14. Клавиатура, фокус и доступность - -### 14.1. Общая карта - -| Клавиша | Библиотека/репертуар | Тренировка | -|---|---|---| -| Tab / Shift+Tab | По всем действиям, полям, таблице/дереву | По доступным действиям; доска сохраняет ввод мышью | -| Enter | Открыть строку; подтвердить inline-редактирование; запустить, если фокус на кнопке | Только на итоге: основное «Далее»/«Новый проход»/«Повторить»; во время хода ничего | -| Space | Активировать сфокусированную кнопку/переключатель | То же | -| Esc | Закрыть popup/отменить inline; затем вернуться на предыдущий экран | К репертуару; незавершённое не засчитывается завершённым | -| ← → Home End | Навигация по позициям активного дерева | Просмотр уже сыгранного | -| ↑ ↓ | Строки таблицы; навигация нотации по существующим правилам | Как в текущем тренере | -| F | Перевернуть доску | Перевернуть доску | -| Ctrl+W | К экрану баз с соблюдением несохранённых данных | К экрану баз через подтверждение только реальных несохранённых данных | -| Shift+F10 / Menu | Контекстное меню выбранной строки/хода | Нет меню будущих ходов | -| L, Shift+A | В репертуаре движок не запускается | Прежний тост об отключённом движке | -| Ctrl+Z/Y/S/V/G, Ctrl+1…6 | Только обычные действия соответствующего экрана; в дереве репертуара редактирования нет | Ничего | - -Отдельной клавиши подсказки нет: она доступна по Tab только после появления. Delete не удаляет репертуар. - -### 14.2. Фокус - -- Видимый focus ring минимум 2 точки, контрастный в dark/light; selection и focus не совпадают только цветом. -- При открытии выбора назначения фокус — на списке репертуаров; после добавления/отмены — на исходном ходе. -- После создания/переименования фокус возвращается строке; после удаления — следующей строке или кнопке «Создать» в пустой библиотеке. -- Ошибка ввода не крадёт фокус у доски. Ошибка записи переводит фокус на «Повторить» только если пользователь уже взаимодействовал с кнопками, а не делал ход; иначе полоса получает доступное объявление без смены фокуса. -- Переход «рядом ↔ стопка» сохраняет фокус, активный ход, прокрутку и выбранную вкладку. - -### 14.3. Не только цвет - -- Ошибка — `✗` и текст, try again — отдельный текст без красного креста. -- Disabled — `⌀` и `не учить`, due/new — явные слова, транспозиция — `⇄ N путей`. -- Подсказанный результат — текст `с подсказкой`, а не только звёздочка/жёлтый цвет. -- Основной текст и важные значки — контраст не ниже 4,5:1; крупные элементы фокуса/рамки — не ниже 3:1 в обеих темах. - -## 15. Что визуально переиспользовать из старого тренера - -Обязательно сохранить: - -1. Расположение доски, правой/нижней панели и полосы под доской — вход в тренировку не «прыгает» относительно партии. -2. Доску, легальность, подсветку последнего хода, выбор превращения, стрелку подсказки и поведение ориентации. -3. Две рамки по образцу `clock_card`, панель инструментов `play_toolbar`, итог `result_strip` и строку просмотра прошлой позиции. -4. Read-only таблицу нотации только сыгранного, автоматическую прокрутку к последнему ходу и слой `×N` ошибок в итоге. -5. Красный flash двух полей на 400 мс, блокировку ввода, возврат фигуры с существующей анимацией не более 150 мс, звуки `Wrong` и `Success`. -6. Клавиши навигации, `F`, `Esc`, `Ctrl+W`, Enter только в итоге и тосты `L`/`Shift+A`. - -Не переиспользовать без изменения смысла: - -- линейный `Ход k из N` для SRS и заранее неизвестного пути `Both`; -- один `wanted(k)` для всех режимов; -- красную ошибку для другого enabled-хода в одноцветном `try again`; -- старое «Прохождение N · лучшее» как будто это per-move статистика; -- старый line-key для транспозиций или общий счётчик для White/Black/Both; -- немедленный запуск из контекстного меню партии. - -## 16. Прямые требования к UI-реализации - -1. Состояния маршрута разделены: `RepertoireLibrary`, `RepertoireDetail`, `RepertoireTraining`. Активная тренировка — ограниченная временная сессия, не редактируемый PGN-документ. -2. PGN остаётся источником дерева. FEN4-индекс, кандидаты и очереди — производные; в JSON нельзя ссылаться на временный `NodeId`. -3. Общий Rust-автомат различает `target exact`, `try again`, `outside enabled`, `illegal input`, `boundary`; UI не дублирует шахматные правила. -4. Все автоматические ответы изолированы выбором канонического enabled-ребёнка. Ни UI, ни движок не выбирают случайный или «лучший» ход. -5. Глубина, disabled, scope применяются одновременно к очереди, пользовательским кандидатам, ответам программы и знаменателям статистики. -6. Статистика имеет ключи режима и репертуара. Legacy line-run хранится и отображается отдельно; per-move данные из него не реконструируются. -7. Запись PGN/настроек/статистики атомарна. Перед записью исключается потеря изменений другого процесса; ошибка возвращается в UI. -8. При ошибке записи тренировка остаётся на текущем результате, следующее задание не начинается. Есть «Повторить»; выход с несохранёнными новыми событиями использует существующую защиту несохранённых данных. Молчаливого «продолжить как будто сохранено» нет. -9. Разбор импорта, слияние, FEN4-индексирование и большие очереди не блокируют UI. Отмена до commit не оставляет частичного результата. -10. Таблица библиотеки, дерево, таблицы ходов и история виртуализируются. Нельзя каждый кадр заново разбирать PGN или раскладывать все ветки целиком. -11. Дерево не разворачивается автоматически целиком после импорта: раскрываются основная линия и активный путь, остальные RAV сохраняют состояние раскрытия. -12. Кнопка и новые экраны включены только на desktop с `CAPS.training`. Android API/экраны и web-поведение не меняются; отсутствие новой кнопки там — ожидаемое поведение. -13. Все тексты локализованы RU/EN/DE, включая причины disabled, диагностику PGN, множественные числа и историю. -14. Цвета берутся из существующих `selection`, `error_fg_color`, `warn_fg_color`, `noninteractive.bg_stroke`; новой декоративной палитры нет. - -## 17. Приёмка для developer и tester - -### 17.1. Библиотека и контекст - -- [ ] «Тренировка дебюта» стоит рядом с «Подготовками» и открывает библиотеку; Android/web не получают сломанного нового входа. -- [ ] Создание, переименование, удаление, импорт и ошибки записи работают inline; нет цепочки модальных окон. -- [ ] Несколько репертуаров имеют независимые деревья, глубину, disabled, очереди и статистику. -- [ ] «Добавить в репертуар…» добавляет точный префикс, включая путь внутри RAV, комментарии/NAG/FEN; соседних веток и хвоста нет. -- [ ] После добавления тренировка не начинается; исходная партия, её курсор, revision, несохранённые комментарии и файл не меняются. -- [ ] Возврат по «Открыть» из тоста и затем «К партии» восстанавливает исходный контекст. Изменённый/удалённый источник не открывает случайную запись. - -### 17.2. PGN и объём - -- [ ] Multi-game PGN создаёт один репертуар; вложенные RAV, комментарии, NAG и FEN переживают сохранение и перечитывание. -- [ ] Повторный импорт полного дубля не создаёт узлов/аннотаций; новый комментарий/NAG на существующем пути не теряется и не затирает прежний. -- [ ] Добавляющий импорт сохраняет статистику и disabled существующих ходов; новые ходы enabled. -- [ ] Разные стартовые FEN, нелегальный ход, legacy-кодировка, fullmove=0, старт чёрных, `--`, усечённая запись дают либо корректное дерево с диагностикой, либо явный отказ без скрытого частичного импорта. -- [ ] Глубина по умолчанию 20 полуходов; изменение глубины меняет очередь/ответы/знаменатели, но не PGN и экспорт. -- [ ] Disabled остаётся читаемым и экспортируемым, не попадает в кандидаты и очередь; enable возвращает прежнюю статистику. -- [ ] Все disabled, пустой репертуар, глубина ниже начала выбранной ветки и отсутствие ходов выбранного цвета имеют отдельные понятные состояния и не запускают пустую доску как успех. - -### 17.3. Одноцветный режим - -- [ ] White и Black проверяют только свой target-ход; контекстные ходы не создают попыток; программа отвечает только enabled-ходами дерева. -- [ ] Другой enabled-ребёнок вне цели даёт отдельный `try again` без mistakes/due/accuracy; disabled и ход вне дерева — обычная ошибка. -- [ ] Нелегальный ввод не считается; превращения различаются; каждая повторная ошибка увеличивает счётчик. -- [ ] После третьей ошибки подсказка доступна по запросу, стрелка не появляется сама; hinted сбрасывает чистую серию. -- [ ] Лист раньше глубины завершает задание/путь нормально; нет ответа движком или хода за пределами лимита. -- [ ] SRS сначала берёт due; unseen вводятся пакетами до 10 только явно. При due=0 есть раздельные «Добавить новые» и «Повторить будущие раньше». -- [ ] Успех/ошибка/hint меняют сроки по §9.2; досрочный и последовательный обзоры пишут попытки, но не меняют due. -- [ ] «Подряд» помнит место и начинает новый цикл; «Сначала новые и давние» сначала unseen, затем ascending last_seen. - -### 17.4. Both - -- [ ] Пользователь делает каждый полуход; автоматических ответов нет. -- [ ] На развилке каждый enabled-ребёнок принимается; нет `try again` и заранее обязательной ветки. -- [ ] Ход вне дерева, disabled и за глубиной возвращается с ошибкой; после третьей можно запросить стрелку, но другой enabled-ход всё равно принимается. -- [ ] Лист, depth и FEN4-цикл завершают проход ровно один раз; «Повторить путь» не делает его фиксированной линией. -- [ ] Enabled-отклонение от предложенного маршрута записывает фактический путь, а незавершённый предложенный не отмечает пройденным. -- [ ] В `Both` нет due/SRS-статусов; его статистика не меняет White/Black. - -### 17.5. Транспозиции и статистика - -- [ ] `1.d4 d5 2.Nf3` и `1.Nf3 d5 2.d4` дают одну FEN4-запись внутри репертуара, одну цель в очереди и каноническое продолжение; оба PGN-пути видны. -- [ ] Очередь хода, права рокировки и легальное en passant различают позиции; счётчики не создают дубли. -- [ ] Disabled одного пути не скрывает логическую цель, доступную по другому enabled-пути. -- [ ] По ходу видны реальные attempts/correct/wrong/hints/last/due; в Both ошибки относятся к позиции, а не выдуманному expected SAN. -- [ ] Disabled не входит в текущий знаменатель; нет «% mastered». История режимов и репертуаров раздельна. -- [ ] Старые line-run видны на отдельной вкладке с исходными числами и без новых per-move колонок; незавершённое не становится завершением. - -### 17.6. Визуальная и системная матрица - -Каждый пункт проверяется в **RU, EN, DE**, **dark и light**, при **1400×900, 640×900 и 640×480**: - -- [ ] Библиотека: пусто, 3 и 50+ репертуаров, длинное название, legacy-вкладка, ошибка чтения/записи. -- [ ] Импорт: предпросмотр большого multi-game PGN, предупреждения, отмена, несовместимый FEN. -- [ ] Репертуар: пусто, большое ветвистое дерево, все disabled, нет ходов цвета, вся область глубже лимита, активная FEN4-группа. -- [ ] Тренировка: White, Black, Both; правильный ход, try again, ошибка flash, третья ошибка/подсказка, лист, depth, повторение позиции, due=0, итог, незавершённое, ошибка записи. -- [ ] Ничего не обрезано слева, тексты не накладываются, доска не меньше 220, панель не уже 240 в режиме «рядом», в стопке остаётся читаемая нотация. -- [ ] Клавиатура и focus ring проходят весь сценарий без мыши, кроме самого шахматного хода; Esc не теряет реальные несохранённые данные. -- [ ] Комментарии/NAG/будущие SAN/авторские стрелки не раскрывают ответ до положенного момента. -- [ ] Большой ветвистый PGN: разбор и индексирование не блокируют окно, отмена не оставляет частичную запись, прокрутка виртуализированного дерева и таблиц не разворачивает все пути. -- [ ] После перезапуска восстанавливаются PGN, disabled, глубина, настройки, отдельные очереди и вся новая/legacy статистика. Исходные PGN-файлы побайтово не изменились. - -## 18. Итог для реализации - -Разработчик строит не расширенный линейный «repeat game», а три связанных рабочих экрана вокруг самодостаточного PGN-дерева. Одноцветный режим проверяет конкретную цель и имеет SRS/обзоры; `Both` проверяет принадлежность каждого фактического полухода enabled-дереву и использует очередь путей. Общими являются доска, flash, подсказка по запросу, глубина, disabled, FEN4 и сохранность данных — но не модель задания и не статистика. - -Тестировщик получает однозначные контрастные сценарии: `try again` против ошибки, любой enabled-ход в `Both`, due=0 без автоматического потока новых, транспозиция без дубля, ранний лист, незавершённое, отдельные legacy line-run и полная матрица RU/EN/DE × dark/light × 1400×900/640×900/640×480. - -## 19. Уточнение компоновки после живой проверки (2026-11-02) - -По замечанию владельца о неровной вёрстке настройки репертуара объединены с деревом -в одной прокручиваемой панели. На широком и коротком окне она справа от доски; -на узком высоком — снизу с достаточной минимальной высотой для дерева. Доска -центрируется в оставшейся области. Глубина, режим и очередь образуют двухколоночную -сетку, остальные действия переносятся внутри своей строки. Библиотека использует -виртуализированную таблицу с постоянными колонками и обрезкой длинных названий -(полное название — tooltip). Подтверждение удаления располагается перед таблицей. - -Панель тренировки прокручивается целиком; заголовок репертуара, задание и очередь -хода не конкурируют за одну строку. Кнопки навигации имеют одинаковые размеры. -Основная линия дерева видна сразу, боковые продолжения раскрываются у родительского -хода. Выбор позиции через транспозицию раскрывает её путь. - -Индексация, подсчёт заданий и подготовка сессии имеют состояние загрузки и работают -в фоне. Во время подготовки параметры блокируются; возврат отменяет принятие её -позднего результата. Ожидающий подсчёт не дублируется при смене минуты. - -## 20. Действующий сценарий: пройти варианты - -1. Импорт PGN открывает репертуар. По умолчанию выбран режим «Пройти варианты», - цвет — белые (или сохранённый пользователем). Под выбором объясняется: - ветка проходится целиком, любой включённый ход принимается, соперник отвечает - автоматически. «Повторять отдельные позиции» — явный отдельный режим. -2. «Начать» открывает исходную позицию области. За чёрных программа сначала - делает ход белых. Заголовок «Продолжайте вариант», очередь хода и текст «Ваш ход: - сыграйте любой ход из репертуара. Затем ответит программа» объясняют действие. -3. На развилке можно выбрать любое продолжение. Программа принимает его и отвечает - из этой ветки; переноса к независимой цели в обычном прохождении нет. -4. «Не помню — показать ход» доступно сразу. Подсказка соответствует очередной - предложенной ветке, но не запрещает альтернативу. Ход вне включённых вариантов - отклоняется с объяснением и предложением воспользоваться подсказкой. -5. На завершении — счёт фактических пользовательских ходов/ошибок/подсказок. - Основная кнопка «Следующая ветка» и Enter начинают следующий проход. «Повторить - путь» воспроизводит фактически сыгранный маршрут автоответов. -6. В режиме отдельных позиций включённая альтернатива также принимается. Она не - получает ложную оценку за скрытую цель; несделанный целевой ход остаётся для - будущего повторения. Старое сообщение «сейчас повторяется другой» не выдаётся. - -Настройки очереди прежнего интерфейса однократно мигрируют в «Пройти варианты». -Статистика ходов отражает фактически сыгранные ответы; автоматические ходы не -считаются попытками. Практика не меняет существующие сроки SRS. Прохождения и -статистика веток за обе стороны обновляются и в новом основном режиме. - -## 21. Действующее упрощение: случайный круг вариантов (2026-11-03) - -Этот раздел заменяет прежние требования к видимому дереву, глубине, disabled, области, due-колонкам и выбору очереди. Остальные правила сохранности PGN, доски, ввода, ошибок, подсказок и статистики действуют. - -### 21.1. Библиотека и репертуар - -Библиотека — таблица `Название | Варианты | ⋯` в стиле основной таблицы партий: обычные текстовые ячейки, один клик выделяет строку, двойной открывает репертуар. Создание пустого репертуара выделяет его строку и оставляет пользователя в списке, не открывая доску. Кнопка настроек находится в правом углу шапки. Числовые заголовки и значения выровнены по правому краю. «Варианты» — количество маршрутов, доступных тренировке, а не число завершений: у нового репертуара с двумя маршрутами сразу показано `2`. Подсчёт выполняется в фоне; во время него виден индикатор, а не прочерк, похожий на ноль. - -На экране репертуара нет дерева ходов, ручных ограничений и кнопок импорта/экспорта. Порядок элементов: название; цвет `Белые | Чёрные | Оба`; число вариантов и основная кнопка «Начать тренировку»; компактная статистика. Импорт в существующий репертуар и экспорт доступны в меню `⋯` его строки в библиотеке. Глубина, область и выбор «проход / отдельные позиции» удалены, а не скрыты под дополнительным меню. Старые ограничения из JSON снимаются при загрузке, чтобы невидимо не менять содержимое тренировки. - -### 21.2. Случайный круг и начало не с первого хода - -- Для круга формируется случайная перестановка полных маршрутов. Каждый предлагается один раз; после последнего начинается новый круг с новой перестановкой. Повтор по желанию пользователя не считается следующим элементом очереди. -- Два маршрута могут иметь общий префикс: это разные варианты, а не ошибочное пересечение. Не повторяется именно полный маршрут. -- Круг строится только из исходных PGN-веток, без увеличения их числа через транспозиции. Начало выбирается случайно среди позиций исходной ветки, где есть продолжение для выбранной стороны. До неё проигрывается automatic context. До конца остаётся не меньше семи полуходов; если ветка короче, она начинается с исходной позиции. Пользователь не настраивает prefix/scope и не видит сырые UCI. -- White/Black получают первую задачу своего цвета; программа отвечает из выбранной ветки. Both получает любую позицию с продолжением и ходит за обе стороны. Пустой suffix и старт за пределами PGN недопустимы. -- Очередь строится в фоне и при первом запуске, и при Next. Для большого дерева используются последовательный подсчёт и выбор маршрута, а не список всех путей в памяти; состояние круга сериализуется совместимо со старой статистикой. Fingerprint PGN входит в ключ круга: изменение содержимого при неизменном числе маршрутов также начинает новый круг. - -### 21.3. Проход и результат - -Экран прохода сохраняет доску, ошибку, подсказку и число ошибок. На текущей позиции показываются существующие значки NAG (`!`, `?`, `!!`, `??`, `!?`, `?!`) и авторские стрелки/круги из `[%cal]`/`[%csl]` с теми же цветами, что при просмотре партии. При просмотре более ранней позиции пометки текущего узла скрываются, чтобы не относить их к другому ходу. Подсказка отображается вместе с авторскими стрелками. Автоматический префикс не считается пользовательскими попытками. Видимого «Дерева» будущих ходов нет. Текстовая нотация также полностью удалена: SAN, номера ходов, `×N`/`*` и отдельная scroll area не показываются и не резервируют место. Просмотр уже показанных позиций выполняется на доске прежним toolbar и клавишами; внутренний путь для этого и для механики сохраняется. - -После последнего реального полухода показываются результат и два равноправно доступных действия с разным приоритетом: - -1. Основная **«Следующая ветка»** (и Enter) выбирает следующий непройденный маршрут круга, с новым случайным началом. -2. **«Повторить путь»** повторяет фактически сыгранный маршрут, включая выбранные пользователем отклонения, автоответы и исходную стартовую позицию. Курсор очереди не двигается. - -«Назад к репертуару» остаётся отдельным действием. Ошибка сохранения не позволяет молча продолжить как будто данные записаны. - -### 21.4. Обязательная приёмка этого уточнения - -- Новый Spanish с двумя маршрутами и нулём завершений показывает `Варианты: 2`; после тренировок смысл числа не меняется. -- Старые `max_plies=20`, disabled и SRS-настройки не ограничивают новый запуск; PGN и история попыток сохраняются. -- На fixture минимум из трёх веток весь круг содержит каждый полный маршрут один раз; следующий круг снова содержит все. Изменение PGN корректно начинает новый круг. -- White, Black и Both получают легальный automatic context и ход нужной стороны; доска совпадает с фактической позицией session, текстовой нотации и её пустого контейнера нет. Repeat сохраняет точный путь и старт, Next не наследует старую случайную область. -- В RU/EN/DE, dark/light, 1400×900 и 640×480 нет удалённых контролов, обрезанных заголовков, наложений и недостижимых кнопок. Во всех режимах проверяются правильный ход, ошибка/подсказка, итог, Repeat, Next и Back. - -## 22. Единый экран репертуаров и тренировки (2026-11-03) - -Этот раздел заменяет раздельные экраны библиотеки и репертуара из §21.1, а также панель кнопок навигации по позициям. - -### 22.1. Одна рабочая область - -- «Тренировка дебюта» на экране баз сразу открывает рабочую область с доской, даже если библиотека пуста. Отдельных экранов списка репертуаров и описания репертуара больше нет. -- На широком окне доска слева, панель справа; на узком высоком панель переносится под доску. Выбранный репертуар показан компактной карточкой: название, цвет, число вариантов, «Начать тренировку» и статистика. Верхняя шапка и геометрия доски одинаковы в workspace и активной тренировке; при узком окне области вычисляются явными `board_rect`/`side_rect`, чтобы содержимое не меняло размер и центр доски. -- Таблица репертуаров находится в той же панели под карточкой. Во время тренировки она остаётся доступна под карточками задания/результата. Кнопки `⏮ ◀ ▶ ⏭` удалены; внутренняя история позиций и клавиатурный просмотр сохраняются. -- Один клик по строке выбирает репертуар и обновляет доску, не открывая другой экран. Запуск выполняется отдельной основной кнопкой. Создание, переименование, импорт, экспорт, удаление и поиск доступны в этой же панели и во время тренировки. Раздела «Прежние линии» нет: владелец удалил архивную таблицу из текущего интерфейса, старые файлы данных при этом не стираются. -- При первом входе, выборе и возврате из тренировки выбранная строка однократно прокручивается в видимую область. Последующая ручная прокрутка не сбрасывается. -- Смена репертуара или редактирование библиотеки завершает текущий показ тренировки и возвращает в рабочую область. При ошибке сохранения управление блокируется: несохранённые события нельзя потерять молча. - -### 22.2. Таблица и дебютные названия - -- Колонки: `Название | ECO | Варианты | ⋯`. Под названием репертуара в его ячейке показываются названия дебютов/вариантов, каждое с новой строки; соответствующие ECO-коды также перечисляются построчно. Все строки имеют одинаковую высоту **156 pt** с местом под пять названий: сверху 8 pt, слот названия 24 pt, интервал 12 pt, пять слотов по 20 pt с шагом 2 pt между ними, снизу 4 pt. Лишние названия скрываются за `…` в пятой строке, полный список доступен в её подсказке. Название репертуара — существующий strong 16 pt, названия дебютов и ECO — обычный proportional 14 pt, без `.small()`. Высота не зависит от числа загруженных названий и от DPI. -- Источник — встроенный `chess-openings` (таблица Lichess), а не обязательная большая база. Для каждого полного маршрута выбирается наиболее точная названная позиция `deepest`; повторы одинаковых пар ECO/название удаляются. Транспозиции распознаются по позиции. -- Число «Варианты» — полные ветки, явно записанные в исходном PGN. Транспозиции позволяют переключаться между ветками во время прохождения, но не увеличивают их количество и не добавляют новые элементы в случайный круг. -- Коды и названия вычисляются вместе с деревом в фоновой индексации. До готовности индекса и при отсутствии названия показывается нейтральный прочерк, интерфейс не блокируется. -- Пустая библиотека показывает обычную доску и элементы создания/импорта, а не отдельный пустой экран. - -### 22.3. Выравнивание и состояния фоновой работы - -- Везде в рабочей области используется подпись «Варианты», не «Пути». Карточка репертуара построена сетками: подписи и контролы «Цвет»/«Варианты» выровнены по колонкам; «Попытки», «Ошибки» и «Завершения» показываются отдельной сеткой статистики. Блок статистики всегда занимает одну высоту: до первой попытки показаны нули и прочерк вместо даты, строка завершений не появляется позже. Кнопка «Сбросить» после подтверждения очищает статистику и очередь только текущего репертуара и цвета; другие режимы и legacy-линии сохраняются. -- Число стоит слева непосредственно рядом со словом «Варианты». «Начать» и «Сбросить» имеют одинаковую ширину 120 логических точек и выравниваются по правому краю своих строк. Запуск использует общий акцентный `primary_wide`, «Сбросить» остаётся второстепенной кнопкой. -- ECO-код стоит точно напротив названия своей ветки, а не напротив названия репертуара. Коды и названия используют одинаковый размер 14 pt и слоты 20 pt с шагом 2 pt; пустой слот названия в колонке ECO повторяет отступы и высоту названия репертуара. -- Отдельной кнопки «Репертуары» нет. Переключения на «Прежние линии» и архивной таблицы также нет. -- Статусы различают действия: чтение файла — «Импорт PGN…» с отменой; построение индекса — «Индексация вариантов и названий ECO…»; запуск — «Подготовка тренировки…». Непонятное «Готовим дерево…» из интерфейса удалено. Для фонового статуса всегда зарезервирована одна строка 24 pt: после завершения работы она пуста, но кнопки и таблица не сдвигаются; длинный текст усечается с tooltip. - -## 23. Переход к модели ТЗ ChessTempo (2026-11-04) - -Этот раздел фиксирует поэтапный UX для новой модели из `docs/decisions.md`. ТЗ имеет приоритет над прежними упрощениями. Текущий workspace, доска, таблица библиотеки и визуальная система сохраняются; случайная Practice не становится четвёртым режимом SRS. - -### 23.1. Рабочая область по этапам - -- **MVP:** стандартный SRS для White/Black, один основной ответ, независимые попытки, базовые `T/Unseen/Learning/Learnt/Uncertain/Due`, проценты и `NextDueAt`. Primary CTA и KPI используют один scope. Редактор дерева и назначение main-ответа появляются внутри рабочей области, без мастера модальных окон. -- **Три режима:** один компактный dropdown `Повторения (SRS) / По порядку / Сначала новые и давние`. Review in Order и Least Recent используют тот же pipeline независимых ответов. Continue относится к восстановленной сессии, а не просто к наличию старой статистики. -- **Расширенная аналитика:** полная summary-таблица, ветвевые и глобальные проекции, истории и графики открываются отдельно. Библиотечная таблица не превращается в dashboard и не получает восемь KPI-колонок. -- **Reset:** общий LearningItem сбрасывается через preview N/M с именами затронутых репертуаров. `Reset Review Order` — отдельное действие, не меняющее SRS. Деструктивный фокус по умолчанию не получает Enter. - -Состояния CTA: Due>0 — `Повторить сейчас · N`; Due=0 и Unseen>0 — `Изучить новые`; Due=0 и Unseen=0 — завершить либо явно повторить досрочно с `NextDueAt`. Новый репертуар не получает ложное «всё повторено». При T=0 проценты `—`, Start недоступен. `ALL_LEARNT` допускает Due; `CONFIRMED_CURRENT` требует Due=0 и Uncertain=0. - -KPI — один спокойный блок в выбранной карточке, с полной подписью области и времени расчёта. `Uncertain` явно подмножество Learnt, Due — пересечение с Learning+Learnt. История старых Attempts/Completions не смешивается с состоянием знания. - -### 23.2. Тренировка и контекст - -- Доска остаётся центральной; библиотека под активным заданием не показывается. Текстовая нотация не возвращается. Название, scope, прогресс сессии и фиксированная панель состояния остаются на месте. -- Неверный легальный ход записывается один раз. После возврата позиции ожидаемый ход показывается стрелкой; повтор продолжает линию как `REPLAY_AFTER_ERROR` и не называется самостоятельным успехом. Повторные ошибки в этой фазе не создают новых независимых попыток. -- `PREVIEWED` виден до воспроизведения: серия и Accuracy не растут, требуется поздняя проверка без подсказки. Автоматический context записывает только служебное событие `AUTO_CONTEXT`, не создаёт независимых попыток и не меняет SRS. Если контекстный ход сам проверяется как reinforcement, он имеет явное состояние и записывается один раз. -- Автоматические ходы показываются последовательно `position_before → position_after`. Каждая новая автоматическая серия начинается со статичного prime-кадра из `from` первого шага: он не анимирует предыдущую позицию и не создаёт обратный slide; только следующий кадр запускает scheduler. При фиксированной скорости каждый шаг занимает `settings.animation.seconds()`: Off=0, Fast=0,12, Normal=0,25, Slow=0,5 с. При адаптивной скорости фактический slide и scheduler используют одну длительность `base / speed_factor` текущего шага, включая последний; переход before→after начинается в начале этого интервала. Два–три ответа/контекстных хода не телепортируются за один кадр. Во время autoplay ввод заблокирован, Pause/Stop доступны; Off разрешает мгновенный переход. -- До готовности board ввод невозможен. Результат появляется после завершения последнего визуального шага, а не только после изменения session. Сохранение ошибок блокирует переход как раньше. - -### 23.3. Компоновка и приёмка - -- Wide: доска слева, справа название/scope, сторона/режим, CTA, единый KPI, библиотека. Узкое окно не прячет primary action и не создаёт горизонтальную прокрутку. -- Высоты карточек и строк не зависят от появления индекса, статистики, ошибки или длины сообщения. Переходы Wrong→Reveal→Replay→Opponent→Next не двигают доску. -- Обязательные снимки 1400×900 (основной размер) и 960×600 (минимальный для визуальной приёмки): empty/new/mixed KPI, Due=0, все Learnt, три режима, wrong/replay, preview, autoplay 1/3→3/3, Pause/Continue, shared reset, save error, Continue/New session. Дополнительно серия кадров доказывает длительность анимации, один статический снимок её не доказывает. Размер 640×480 остаётся только в исторических технических тестах и не определяет дизайн. -- Независимый design reviewer сравнивает main/game и рабочую область, а оркестратор проверяет core AT-01…30 отдельно от визуальной приёмки. - -### 23.4. Details, сравнение веток и настройки контекста - -- `Details` находится в строке `Statistics` слева от `Reset`, обе кнопки вторичные высотой 26 pt. Открывается отдельная рабочая область вместо доски и боковой панели, не popover и не новая карточка в библиотеке. Начальные Scope/Side наследуют текущий выбор; Global доступен только явным переключением. Close/Escape возвращает к той же строке и фактической прокрутке без принудительного центрирования. -- `Context and move speed` — один default-collapsed ряд после основных настроек и `Reset Review Order`, но до `Statistics`. Перед ним 8 pt, после 6 pt; expanded body использует спокойную двухколоночную сетку 12×6 pt с переносами длинных подписей. В узкой панели выбранный блок ограничен примерно половиной высоты и получает собственную вертикальную прокрутку: CTA остаётся в начале, toolbar/header и строка библиотеки не исчезают. Вложенных карточек и горизонтальной прокрутки нет. -- В compact KPI не используется непонятное `T`: показывается `Total moves`/`Total`. Слабая строка `Learnt = Confident + Uncertain · percentages use Total` объясняет состав и знаменатель. Ноль попыток и пустой scope дают `—`, а не 0% или 100%. -- Dashboard разделён на Summary, Branches, History, Scheduled, Sequences и Moves. Summary содержит точную таблицу репертуаров и дедуплицированный Global total; Branches — T/Unseen/Learning/Learnt/Uncertain/Due/Accuracy/Learnt %/Last trained. На узком экране Branches показывает основные колонки и все детали выбранной ветки ниже, без уменьшения шрифта и горизонтальной прокрутки. -- History содержит линии Learning/Learnt/Uncertain по фактическим ежедневным снимкам; Uncertain — независимая линия-подмножество, не stack. Scheduled — шесть непересекающихся корзин; Sequences — три гистограммы, включая ноль. Точные таблицы остаются под графиками. Один snapshot — видимая точка; отсутствующие данные не синтезируются. -- Действие называется `Save statistics to History`, а не «снимок» без контекста. Первый просмотр scope в локальный день сохраняет снимок автоматически, повторное ручное сохранение того же date/scope идемпотентно. PGN и LearningItem не меняются. Фоновое обновление после записи не заменяет уже видимую таблицу коротким loading-body. -- Тренировочный KPI и CTA учитывают `max_plies`; полная History остаётся полной по настройке scope. Сравнение веток и линий использует все PGN-пути: общий LearningItem присутствует в каждой подходящей линии, дедуплицируется внутри ветки и не суммируется повторно в Global. -- Независимый reviewer проверяет collapsed/expanded, первый вход→loading→loaded→Details→Close, 1400×900 и 960×600, RU/EN/DE и dark/light. Отдельно фиксирует читаемость всех заголовков, отсутствие скачков после Save statistics to History и доступность выбранной строки библиотеки. Микро-окна не используются для визуального вердикта. diff --git a/docs/design/task-26-review-button-2026-11-27.md b/docs/design/task-26-review-button-2026-11-27.md deleted file mode 100644 index e0cc7a8..0000000 --- a/docs/design/task-26-review-button-2026-11-27.md +++ /dev/null @@ -1,88 +0,0 @@ -# Задача 26. Кнопка «Анализ партии» цветом блестящего хода (!!) - -Дизайнер, 2026-11-27, ветка `feature/starter-repertoires`. Код не менялся. - -**Задача экрана.** Новичок должен заметить в панели под нотацией кнопку, которая запускает разбор партии. После разбора кнопка не должна спорить с активной позицией в нотации. - -## 0. Что сейчас (реальные снимки) - -Снимал через `scripts/dev/headless-run.sh`, 1920×1080, scale 1. Профиль изолирован: `/tmp/opencode/d26/{cfg,data,cache}`, Stockfish 19 подключён ссылкой. Партия — копия `Alekhin.pgn`, № 1 (84 полухода) и № 2, `CP_PLY=20`. Сборка — `target/debug` текущего HEAD. Её копию из `target/design-26` я удалил. Полные снимки лежат в `/tmp/opencode/d26/s/`, вырезки — в `docs/design/task-26/`. - -| Снимок | Состояние | Что видно | -|---|---|---| -| `idle-d1.png`, `idle-d0.png` → `task-26/now-idle-d1-crop.png` | разбора нет | Последняя кнопка панели, иконка `📈`. Обычная заливка: тёмная `#3c3c3c`, светлая `#e6e6e6`. Прямоугольник 27×23 px, x 1818–1844, y 1046–1068. Кнопку легко не заметить | -| `run-d1.png`, `run-d0.png` → `task-26/now-running-d1-crop.png` | идёт разбор 29/84 | Кнопку заменяют ProgressBar (70 px, синий `#005c80`) и ×. **Дефект: они не помещаются и уходят на вторую строку.** Панель вырастает примерно на 24 px, нотация укорачивается. Когда разбор кончается, панель возвращается в одну строку: два скачка без действия пользователя | -| `task-26/graph-overlap.png` | идёт разбор | **Дефект:** счётчик «29/84» в правом верхнем углу графика налезает на подпись «Эндшпиль» (видно «Эндшпиль29/84») | -| `done-d1.png`, `cached-d*.png` | разбор готов, отчёт открыт | Кнопка стала переключателем `toggle_value`, заливка выбранного: тёмная `#005c80`, светлая `#90d1ff` | -| `hidden-d1.png`, `hidden-d0.png` | разбор готов, отчёт скрыт (Shift+A) | Переключатель рисуется **без рамки и без заливки**, хотя соседние кнопки залиты. Это лишнее отличие от остальных кнопок | -| сводка `task-26/now-states-strip.png` | все состояния подряд | — | - -Где задано в коде: -- кнопка — `GameView::review_button` (`apps/desktop/src/game_view.rs:1048`); -- место в панели — `next_group(ui, &["📈"], …)` (`game_view.rs:2296–2302`), резерв `70 + 22 + 10` во время разбора; -- состояние «неактивна» — `engine_busy`. Сейчас его ставит только поиск ошибок в дебютах (`app.rs:4081`), задача 27 добавит проход по партиям; -- цвет !! — `notation::assessment_color(Nag(3))` = `#26c2a3` и `assessment_text_color(Nag(3), dark=false)` = `#1a846f` (`notation.rs:791–818`). Тот же цвет у строки «Блестящий» в отчёте, у кружка на доске и у префикса «!!» из задачи 27 (§4.1 там). Решения согласованы: «!! = разбор» везде один бирюзовый. - -## 1. Решения - -1. **Пока партия не разобрана, кнопка залита бирюзовым, иконка `📈` тёмная (светлая тема — белая).** Это единственная цветная кнопка в панели. Площадь у неё маленькая (27×23), поэтому она привлекает внимание, но не спорит с главным акцентом — синим выделением текущего хода и активной вкладкой. Цвет другой (бирюзовый, а не синий), так что «выбрано» и «пригласить» не путаются. -2. **После разбора бирюзовая заливка не нужна:** приглашение выполнено. Остаётся обычный переключатель: - - отчёт открыт — стандартная заливка выбранного (синяя, как у вкладки «Отчёт»); - - отчёт скрыт — обычная кнопка (`#3c3c3c` / `#e6e6e6`), а бирюзовой становится только иконка. Так видно, что отчёт есть, и исчезает нынешняя кнопка без рамки. -3. **Во время разбора прогресс рисуется внутри той же кнопки 27×23.** Отдельной полосы и × больше нет, ширина и высота панели не меняются. Бирюзовая заливка растёт слева направо по дорожке обычного цвета. Щелчок по кнопке останавливает разбор; Shift+A и Esc в фокусе тоже останавливают, как прежний ×. Число «N/M» остаётся в графике (он открывается вместе с разбором) и в подсказке. Это заодно убирает перенос панели на вторую строку. -4. **Неактивная кнопка выглядит как штатная неактивная egui**, без бирюзового: недоступное действие не должно звать к себе. Подсказка остаётся прежней. Для задачи 27 нужна своя: «Идёт поиск замечательных ходов — дождитесь или остановите его». - -Почему не сплошная бирюзовая кнопка во всех состояниях: после разбора она стала бы самым ярким пятном на экране и забирала бы внимание у доски и нотации. Кроме того, «отчёт открыт» и «отчёт скрыт» тогда отличались бы только оттенком. - -## 2. Состояния и точные значения - -Макет: `docs/design/task-26/states-mock.png` — набросок по реальной вырезке панели; скругления упрощены. - -| Состояние | Тёмная: заливка / иконка | Светлая: заливка / иконка | Рамка | -|---|---|---|---| -| обычная (не разобрана) | `#26c2a3` / `#1b1b1b` (7,65:1) | `#1a846f` / `#ffffff` (4,59:1) | нет | -| наведение | `#3fd3b4` / `#1b1b1b` (9,18:1) | `#157461` / `#ffffff` (5,67:1) | `widgets.hovered.bg_stroke` | -| нажата | `#1fa88d` / `#1b1b1b` (5,78:1) | `#10614f` / `#ffffff` (> 7:1) | `widgets.active.bg_stroke` | -| фокус клавиатуры | как «обычная» | как «обычная» | `visuals.selection.stroke` (как у других кнопок) | -| идёт разбор, p % | слева p·ширины `#26c2a3`, справа `#3c3c3c`; иконка на бирюзовом `#1b1b1b`, на дорожке — обычный цвет текста кнопки | слева `#1a846f`, справа `#e6e6e6`; иконка белая / обычный цвет | как у обычной | -| разобрана, отчёт скрыт | `#3c3c3c` / `#26c2a3` (4,9:1) | `#e6e6e6` / `#1a846f` (3,68:1, иконке достаточно 3:1) | как у обычной кнопки | -| разобрана, отчёт открыт | `selection.bg_fill` `#005c80` / как сейчас | `#90d1ff` / как сейчас | как сейчас | -| неактивна (`engine_busy`) | штатная `add_enabled(false)` от обычной кнопки | то же | — | - -Контраст заливки с фоном панели (`#1b1b1b` / `#f8f8f8`) — 7,65:1 и 4,32:1, то есть больше 3:1 для элемента интерфейса. Светлый оттенок `#26c2a3` с белой иконкой даёт 2,25:1, поэтому в светлой теме его брать **нельзя**. - -Без опоры на цвет: в каждом состоянии кнопку выдаёт что-то кроме цвета. Не разобрана — подсказка «Анализ партии…». Идёт разбор — полоса заполняется. Отчёт открыт — нажатая кнопка-переключатель и открытый график. - -## 3. Требования к реализации - -- Размер обязательно тот же, что у `ui.button(RichText::new("📈").size(18.0))`. Брать его тем же расчётом, что и у соседних кнопок: galley иконки плюс `button_padding` и `interact_size.y`, никаких констант. Ширина и высота одинаковы во всех состояниях. `next_group` резервирует ширину одной кнопки: убрать ветку `70 + 22 + 2*5`. -- `egui::Button::fill()` в egui 0.36.2 отменяет эффект наведения (`widgets/button.rs:140`). Поэтому кнопку рисовать самим: `allocate_exact_size(size, Sense::click())`, затем по `response.hovered()`, `is_pointer_button_down_on()` и `has_focus()` выбрать заливку из таблицы. Скругление и рамку брать из `ui.style().interact(&response)`, чтобы кнопка совпадала с соседями. Прогресс — две заливки и иконка, нарисованная дважды через `painter.with_clip_rect`. -- Цвета не дублировать: заливку брать из `notation::assessment_text_color(Nag(3), dark)`. Три новых оттенка (наведение и нажатие для двух тем) — завести рядом с ней одной функцией, например `brilliant_button_fill(dark, state)`. -- Подсказки: при разборе — «Анализ партии: N из M. Щелчок или Shift+A — остановить». Остальные — как сейчас. Новые строки внести в `i18n.rs` на все языки. -- Shift+A ведёт себя как щелчок в любом состоянии, включая остановку разбора. Tab доходит до кнопки по порядку панели. -- Счётчик «N/M» в графике сдвинуть так, чтобы он не налезал на подпись «Эндшпиль» (отдельный мелкий дефект, `graph-overlap.png`). -- Задача 27: на время прохода выставлять `engine_busy`; кнопка становится неактивной, нужна своя подсказка. -- Android: аналог есть — пункт `review_menu` / `review_report_menu` в меню ⋮ экрана партии (`androidApp/.../ui/GameScreen.kt:1180`). Сейчас его **не делаем**. - -## 4. Критерии приёмки (ревьюер — не автор кода) - -Окна только через `scripts/dev/headless-run.sh`, профиль изолирован (`XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`), партии из копии `Alekhin.pgn`. На каждом снимке указывать файл, размер и состояние. - -1. Снимки 1920×1080, тёмная и светлая темы: не разобрана, наведение (по возможности), идёт разбор (`CP_REVIEW=1`, задержки 3 и 6 с), готово с открытым отчётом, отчёт скрыт (`CP_KEYS="Shift+A"`), неактивна (поиск ошибок в дебютах на вкладке «Отчёт»). Цвета пикселей заливки сверить с таблицей §2, допуск ±2 на канал (сглаживание). -2. **Нет скачков.** Прямоугольник кнопки (у нынешней сборки 27×23 при x 1818, y 1046) и верх панели совпадают до пикселя на сериях «не разобрана → разбор 3 с → 6 с → готово → скрыт». Панель всегда в одну строку. Высота нотации меняется только тогда, когда пользователь открывает или скрывает отчёт: график при открытии отчёта — уже существующее явное действие. -3. Кнопка по высоте и скруглению совпадает с соседними `💾` и `🏷`. Промежуток до разделителя тот же, что в остальных группах. -4. Узкое окно 960×600, тёмная тема: панель переносится так же, как раньше (`game-960-en` из задачи 42), а сама кнопка во время разбора не меняет размер. -5. HiDPI ×2 (если окружение позволяет): граница прогресса и иконка чёткие, иконка не обрезана. -6. Бирюзовый рядом с синим выделенным ходом в нотации и активной вкладкой не сливается с ними. На снимке «не разобрана» глаз сначала находит доску и выделенный ход, а кнопка — единственная цветная в панели. -7. Остановка щелчком и Shift+A во время разбора работает. После остановки кнопка возвращается в «не разобрана» или «отчёт» (если данные частично сохранены) без изменения размера. - -## 5. Что передать тестировщику - -- Shift+A во всех четырёх состояниях, Tab-фокус на кнопке, Esc и Enter при фокусе. -- Гонка: щелчок в момент завершения разбора не должен запускать разбор заново или терять отчёт. -- `engine_busy` от поиска ошибок в дебютах (и от прохода задачи 27): кнопка неактивна, подсказка верная, разбор не стартует по Shift+A. -- Повторное открытие разобранной партии из кэша сразу показывает состояние «отчёт». - -## Нерешённое - -- Число «N/M» уходит из панели в график и подсказку. Если владелец хочет видеть число прямо на кнопке, придётся расширить слот постоянно (примерно 44 px) во всех состояниях. Это нужно спросить у владельца. diff --git a/docs/design/task-26/graph-overlap.png b/docs/design/task-26/graph-overlap.png deleted file mode 100644 index d725680..0000000 Binary files a/docs/design/task-26/graph-overlap.png and /dev/null differ diff --git a/docs/design/task-26/now-idle-d1-crop.png b/docs/design/task-26/now-idle-d1-crop.png deleted file mode 100644 index 17de690..0000000 Binary files a/docs/design/task-26/now-idle-d1-crop.png and /dev/null differ diff --git a/docs/design/task-26/now-running-d1-crop.png b/docs/design/task-26/now-running-d1-crop.png deleted file mode 100644 index 2bc9ad4..0000000 Binary files a/docs/design/task-26/now-running-d1-crop.png and /dev/null differ diff --git a/docs/design/task-26/now-states-strip.png b/docs/design/task-26/now-states-strip.png deleted file mode 100644 index 8e1a12e..0000000 Binary files a/docs/design/task-26/now-states-strip.png and /dev/null differ diff --git a/docs/design/task-26/states-mock.png b/docs/design/task-26/states-mock.png deleted file mode 100644 index c2dc37b..0000000 Binary files a/docs/design/task-26/states-mock.png and /dev/null differ diff --git a/docs/design/task-27-brilliant-search-2026-11-27.md b/docs/design/task-27-brilliant-search-2026-11-27.md deleted file mode 100644 index 721546d..0000000 --- a/docs/design/task-27-brilliant-search-2026-11-27.md +++ /dev/null @@ -1,606 +0,0 @@ -# Задача 27. Поиск замечательных ходов (!!, !) по отфильтрованным партиям базы - -Статус: спецификация дизайнера, 2026-11-27. Код не менялся. Учтены решения владельца -от 2026-11-27 (`docs/dev/tasks.md`, задача 27): лимит ≤ 100 включительно; кнопка видна -всегда; при > 100 она неактивна и показывает подсказку; разобранные партии берутся из -сохранённого разбора; есть «Остановить», и всё разобранное до остановки сохраняется; -найденное отмечается значком в строке. Решение сочетается со спецификацией задачи 42 -(`docs/design/tasks-42-43-2026-11-27.md` §42.3, §42.9), которая сейчас реализуется. - -**Обновление 2026-11-27 (2).** Владелец принял вариант B и все пять рекомендаций §9, а также -добавил итоговое окно. Что изменилось в документе: - -| Решение владельца | Где отражено | -|---|---| -| Кнопка работает только по фильтру, пункта «в выбранных» нет | §4.7 (переписан), §6 (строка меню убрана) | -| Если в фильтре задан игрок, считаются только его ходы | §4.3 (значок и подсказка), §4.9, §5 п. 3 (индекс хранит отметки по цвету) | -| Старый разбор засчитывается без пересчёта | §4.3 (строка «устарел» — только подпись), §4.9 | -| Фильтра «только с !!» нет, есть сортировка по колонке «!!» | §4.3 | -| Игра с движком во время прохода запрещена, есть подсказка | §4.5, §6 | -| **Новое:** итоговое окно после прохода и после «Остановить» | **§4.9**; тосты «готово / остановлен / всё было» из §4.6 и §6 заменены окном | -| Задача 26 сделана: 📈 цветом `#26c2a3` / `#1a846f` | «!!» на кнопке задачи 27 — тот же цвет (§4.1), сквозная связь «!! = разбор» | - -## 0. Исходные снимки (текущий код, `target/debug/chesspenguin` от 2026-11-27 13:27) - -Снимал через `scripts/dev/headless-run.sh` с изолированным профилем -`/tmp/opencode/t27/{cfg-*,data,cache}`. Базы: копии `ruy.pgn` (49 партий), `alekhin.pgn` -(267) и Mega Database 2026 (11,7 млн, только чтение). Снимки лежат в `/tmp/opencode/t27/s/`, -макеты — в `docs/design/task-27/` (нарисованы поверх этих снимков). - -| Снимок | Размер | Состояние | Что из него следует | -|---|---|---|---| -| `ruy-ru-1920.png` | 1920×1080 | 49 партий, фильтра нет | Строка условий (22 px) есть всегда: «Условий нет — показаны все партии». Справа в ней пусто. Кнопка здесь была бы активна (49 ≤ 100) даже без фильтра | -| `alekhin-ru-1920.png` | 1920×1080 | 267, фильтра нет | Кнопка неактивна | -| `alekhin-f-ru-1920/960.png` | 1920 / 960×600 | «Годы: 1914–1914», найдено 7 из 267 | Шапка: «найдено 7 из 267». Один чип | -| `mega-f-ru-1920.png` | 1920×1080 | 3 условия, найдено 4 221 | Кнопка неактивна, нужна подсказка. Колонка 💬 (40 px) заполнена 💬🔀 | -| `mega-f2-ru-1920.png` | 1920×1080 | 3 условия, найдено 62 | Типичный рабочий случай: кнопка активна | -| `mega-f2-ru-960.png` | 960×600 | то же | Таблица 676 px. Колонки 💬, ECO, «Длина», «Турнир», «Тур» скрыты. **Колонка 💬 пропадает уже при ширине < 1000**, значит значок туда класть нельзя. Три чипа занимают до x≈424, справа свободно ~250 px | -| `ruy-en-960.png` | 960×600 | англ., без фильтра | «No conditions: all games are shown» до x≈211 | -| `docs/screenshots/review.png` | 2000×1125 | отчёт партии | Цвета: !! бирюзовый `#26c2a3`, ! зелёный `#81b64c` (`notation::assessment_color`). Значок на доске — бирюзовый кружок «!!» | - -Что видно на снимках: -- шапка базы измеряется по ширине и на узком окне уходит на вторую строку - (`narrow-windows.md §2.4`, `large_db.rs:1714+`); -- строка условий постоянна по высоте (`chips()`, `set_min_height(22.0)`). Справа она уже - занята блоком «в этом порядке ходов…» (поиск по позиции), а задача 42 ставит туда счётчик - выделения и прогресс записи; -- нижняя полоса панели фильтров («Сбросить фильтры (3)») видна только при открытой вкладке - «Фильтры». При вкладке «Доска», при `Pane::Hidden` и в ящике узкого окна её нет. - -## 1. Задача (одной фразой) - -Пользователь сузил базу фильтром или поиском по позиции до небольшого набора и одной командой -узнаёт, в каких из этих партий были блестящие (!!) и замечательные (!) ходы. Важность -информации: можно ли запускать (и почему нельзя) → идёт ли проход, сколько осталось и как -остановить → какие партии отмечены и чем. - -## 2. Путь пользователя и сохранение контекста - -1. База Mega → фильтры «Игрок: carlsen magnus», «Годы 2025–2026», «Elo ≥ 2780» → «найдено 62». - Справа в строке условий кнопка «!! Найти замечательные ходы» стала активной. При 4 221 - найденных она была видна, но неактивна, и подсказка объясняла почему. -2. Щелчок (или Shift+A) → диалог: «Движок разберёт 53 партии — примерно 14 минут. 9 уже - разобраны…» → «Начать». -3. На месте кнопки появляется строка прогресса «!! Проанализировано 12 из 62 · осталось ≈ 11 мин - ▕██░░▏ Остановить». Таблица не сдвигается. Значки появляются в строках по мере разбора. - Таблицу можно листать, сортировать, фильтровать. Партию можно открыть, а потом вернуться - (Ctrl+W / «← Библиотека»): фильтры, прокрутка и выделение остаются прежними (как сейчас). -4. Окончание (или «Остановить»): прогресс сменяется кнопкой и открывается итоговое окно - (§4.9) — суммы !!, !, ?!, ?, ??, средняя точность и список партий с !!. -5. Позже — то же самое при повторном открытии базы или после перезапуска программы: значки - читаются из сохранённых результатов. - -Набор партий фиксируется в момент нажатия «Начать». Если потом изменить фильтр, проход идёт -по зафиксированному списку, а значки появляются везде, где эти партии видны. - -## 3. Варианты размещения кнопки - -### Вариант A — в шапке базы, рядом с «найдено 62 из …» (`docs/design/task-27/A-header-1920.png`) - -``` -│ Mega Database 2026 · ChessBase, только чтение · найдено 62 из 11 743 083 ⓘ1 [!! Найти замечательные ходы] [🔍 Поиск…] [Фильтры][Доска] │ -│ [Игрок: carlsen magnus ×] [Годы: 2025–2026 ×] [Elo ≥ 2780 ×] │ -``` - -- \+ Связь с числом очевидна: «найдено 62» стоит прямо рядом с кнопкой. -- − Шапку измеряют по ширине (`narrow-windows.md §2.4`). На 960×600 уже сейчас имя базы - сокращено до «Mega Database 2…». Новая кнопка шириной 210 px сдвинет поле поиска и отправит - шапку на вторую строку, **таблица уедет вниз**. Задача 42 отказалась от шапки по той же - причине. -- − Прогрессу (~380 px) места в шапке нет совсем. -- − Кнопка оказывается среди «паспорта» базы (имя, формат, кодировка), а не среди условий. - -### Вариант B — справа в строке условий (рекомендуется) (`B1…B5`) - -``` -├ строка условий, 22 px ───────────────────────────────────────────────────────────────────────────────┤ -│ [Игрок: carlsen magnus ×] [Годы: 2025–2026 ×] [Elo ≥ 2780 ×] Выбрано: 3 · Снять [!! Найти замечательные ходы] │ -``` - -- \+ Кнопка **буквально стоит в конце списка условий**: «вот условия → по ним найти». Она - получается следствием фильтра, как просил владелец. Без фильтра в той же строке написано - «Условий нет — показаны все партии», и кнопка всё так же видна. -- \+ Строка есть всегда и высоту не меняет. Ни кнопка, ни прогресс, ни неактивное состояние - таблицу не сдвигают. -- \+ Механизм ухода чипов в «+N ещё» уже есть (меньше 140 px свободно → остаток в подсказке). - Места на кнопку и прогресс отдают условия, а не таблица. -- \+ Работает при любой вкладке правой панели (Фильтры / Доска / скрыта), в ящике узкого окна - и для поиска по позиции. Поиск по позиции тоже фильтр, его 62 партии — тоже выборка. -- − Строку делят три владельца: порядок ходов, выделение (42), поиск (27). На 960 px с тремя - чипами и выделением чипы сворачиваются до «Игрок: … +2 ещё». Это приемлемо, так - задумано в 42 (`B4`). -- − Кнопка 18 px в строке 22 px. Это маленькая кнопка того же размера, что `small_button` - в шапках. - -### Вариант C — в нижней полосе панели фильтров, над «Сбросить фильтры» (`C-filters-footer-1920.png`) - -``` -│ … Аннотации │ -│ ─────────────────────────── │ -│ [!! Найти замечательные ходы (62)] │ -│ [Сбросить фильтры (3)] │ -``` - -- \+ Кнопка физически стоит у фильтров. -- − Не видна при вкладке «Доска» (поиск по позиции тоже фильтрует), при скрытой панели и в - закрытом ящике узкого окна. Правило «видна всегда» нарушено. -- − Полоса шириной 280 px: в одну строку с «Сбросить» не помещается, нужна вторая строка. - Высота полосы растёт, панель фильтров теряет 30 px. -- − Прогресс в панели шириной 280 px получается тесным, а при закрытой панели его вообще - не видно. Пришлось бы дублировать его в таблице. -- − Неактивная кнопка с подсказкой внизу панели незаметна: взгляд туда не попадает. - -### Рекомендация — **B** - -Только этот вариант выполняет все условия сразу: кнопка видна всегда, остаётся следствием -фильтра, прогресс не сдвигает таблицу, на 960 px всё сохраняется. Минус варианта B — тесная -строка. Он решается правилами сокращения из §4.2, их уже применяет задача 42. - -## 4. Вариант B подробно - -### 4.1. Порядок в строке условий (справа налево) - -``` -[слот 27: кнопка или прогресс поиска] [в этом порядке ходов: n из m · только этот порядок] [слот 42: Выбрано / прогресс записи] [условия…] -``` - -- **Слот 27 — крайний справа, всегда.** Так кнопка не прыгает по горизонтали, когда - появляется счётчик выделения (Ctrl+щелчок) или блок порядка ходов (смена позиции на доске). - Это уточнение к §42.3: блок «порядок ходов» и слот 42 сдвигаются на ширину слота 27 влево. - Разработчику 42 нужно оставить в `chips()` место для слота справа. -- Промежуток между слотами — 12 px (`item_spacing.x` + 4). -- Кнопка — **обычная** маленькая кнопка (фон `widgets.inactive.weak_bg_fill`, как «Сбросить - фильтры»), а не основная (primary). Префикс «!!» — Ubuntu-B 13 px цветом - `assessment_text_color($3)` (бирюзовый, в светлой теме `#1a846f`). Это тот же знак, что в - отчёте и на доске (задача 26 делает кнопку разбора в партии того же цвета: связь - «!! = разбор» сквозная). Текст — обычный цвет кнопки. Основную синюю заливку не берём: - в большой базе кнопка почти всегда неактивна, а неактивная основная кнопка выглядит как - сломанная. -- Неактивное состояние — штатное `add_enabled(false, …)` (egui приглушает всю кнопку, - включая «!!»), подсказка — `on_disabled_hover_text`. - -### 4.2. Сокращения по ширине (измерять текстом, как в шапке) - -| Свободно под слот 27 | Кнопка | Прогресс | -|---|---|---| -| ≥ 400 px | «!! Найти замечательные ходы» | «!! Проанализировано 12 из 62 · осталось ≈ 11 мин ▕90 px▏ Остановить» | -| ≥ 220 px | «!! Найти замечательные ходы» | «!! 12 из 62 · ≈ 11 мин ▕60 px▏ Остановить» | -| меньше | «!! Найти ходы» (`B5`) | «!! 12 из 62 ▕60 px▏ Остановить» (`B4`) | - -Полный текст и, при сокращении, оставшееся время — в подсказке при наведении на слот. -Сначала сворачиваются чипы (до «+N ещё»), потом сокращается слот 27. Ширину слота прогресса -резервировать **по самому длинному значению** («100 из 100 · осталось ≈ 59 мин»), а текст -выравнивать по правому краю. Иначе полоса и «Остановить» будут дрожать при смене цифр -(шрифт Ubuntu пропорциональный). - -### 4.3. Значок в строке партии - -**Место — новая узкая колонка «!!» шириной 28 px сразу после «Рез.»** (`B1`, `B3`, `B4`). - -- Колонка 💬 не подходит: при ширине < 1000 px она скрывается (`show_marks`), а результат - поиска должен быть виден и на 960 px. Ширина 40 px там уже занята «💬🔀». -- Колонка № не подходит: там уже стоит ✓ «просмотрено», а в узком окне при поиске по позиции - колонка № скрывается. -- Новая колонка **показывается всегда**: в любой базе, на любой ширине, в том числе пока - в ней пусто. Поэтому появление первого значка ничего не сдвигает. На 960 px её 28 px берутся - из колонок имён (они `remainder`). На снимке `B4` имена при этом помещаются. -- Ячейки (по центру, Ubuntu-B 13 px): - -| Состояние партии | Ячейка | Цвет | Подсказка | -|---|---|---|---| -| не разбиралась | пусто | — | — | -| в очереди текущего прохода | пусто | — | — | -| разбирается сейчас | спиннер 12 px | текст | «Разбирается…» | -| есть !! (и, может быть, !) | `!!` | `assessment_text_color($3)` | «Блестящих ходов: 1 — 21.Rxf7!! (белые) / Замечательных: 2 — 14.Nd5!, 26…Qe7! (чёрные)» | -| только ! | `!` | `assessment_text_color($1)` | «Замечательных: 2 — …» | -| разобрана, !! и ! нет | `·` | `weak_text_color` | «Разобрана: блестящих и замечательных ходов нет» | -| не разбирается (Chess960, нет ходов, учебный `--`) | `—` | weak | «Не разбирается: {причина}» | -| разбор прежними настройками (`ReviewMeta::is_stale`) | как выше | как выше | + строка «Разбор прежними настройками движка» | - -- Читается без цвета: `!!`, `!`, `·`, `—` — разные знаки. На выбранной строке (заливка - `selection.bg_fill`) знаки рисуются цветом `selection.stroke.color`, как остальной текст: - бирюзовый на синем не читается, а форма знака сохраняется. -- Ходы в подсказке — не больше трёх на вид, дальше «и ещё N», нотация — по настройке - (латиница/русская/фигурки). -- Заголовок колонки «!!» сортирует: !! → ! → «·» → «—» → не разобранные. Внутри групп порядок - по номеру записи. Так без нового фильтра можно собрать найденное сверху (решение владельца: - отдельного фильтра нет). -- **Игрок в фильтре** (решение владельца): значок, сортировка и подсказка учитывают только - ходы игрока из условия «Игрок» с учётом «белыми / чёрными / любым». В подсказке первая - строка — weak: «Ходы игрока «carlsen magnus»». Сменился фильтр — значки пересчитываются - из индекса без движка. Если без фильтра у партии есть !! соперника, а у игрока — только !, - то при фильтре в строке стоит «!». Так и задумано. -- Пометка «Разбор прежними настройками движка» в подсказке — только информация. Такой - разбор засчитывается как готовый и в проходе не пересчитывается (решение владельца). -- Контекстное меню строки с отметками (одна партия) — новый пункт «Открыть на ходе 21.Rxf7!!» - (первый !!, иначе первый !). Он открывает партию на этом ходе со вкладкой «Отчёт». Щелчок - по ячейке ничего особого не делает: щелчок по строке — это выделение (задача 42), двойной - щелчок — открыть. - -### 4.4. Диалог перед запуском (`D-dialog-1920.png`) - -Тот же вид окна, что «Добавить в базу» (`chooser-ru.png`): без затемнения, ширина ≈ 520 px, -заголовок 17 px, weak-подзаголовок 12 px, кнопки справа внизу. - -``` -┌──────────────────────────────────────────────────────────────┐ -│ Найти замечательные ходы │ -│ Mega Database 2026 · 62 партии по условиям: Игрок, Годы, Elo │ ← weak -│ │ -│ Движок разберёт 53 партии — примерно 14 минут. │ -│ 9 уже разобраны: их отметки возьмутся из сохранённого разбора.│ -│ │ -│ Компьютер будет загружен (до 8 процессов Stockfish 19). │ -│ Работать с программой можно; остановить — в любой момент, │ -│ разобранные партии сохранятся. │ -│ [Отмена] [Начать] │ -└──────────────────────────────────────────────────────────────┘ -``` - -- **Оценка времени:** `Σ (полуходы_i + 1) × 0,94 с / P` по неразобранным партиям. 0,94 с — - это поиск на позицию в одном процессе вместе со вторым поиском для !!/!: 106 с / 113 позиций, - `decisions.md`, «Разбор на фиксированных параметрах». P — число процессов разбора, которое - `job.rs` выберет на этой машине. Длина берётся из индекса (`r.moves`). Округлять: < 1 мин → - «меньше минуты», < 60 мин → «примерно N минут», иначе «примерно 1 ч 20 мин». Во время - прохода «осталось ≈» пересчитывается по фактической скорости после 3 партий, а до этого — по - той же формуле. -- Счёт «уже разобраны» идёт в фоне (≤ 100 партий: прочитать ход, проверить кэш). Пока он не - готов, на месте первых двух строк стоит «Считаю, сколько партий уже разобрано…» со - спиннером, и «Начать» неактивна. Высота окна резервируется под две строки, чтобы окно не - прыгало. -- **Все 62 уже разобраны:** диалог не показывается, а сразу открывается итоговое окно (§4.9). - Это и есть способ снова посмотреть итог. -- **Подзаголовок:** «по условиям: …» — названия активных условий. Для поиска по позиции — - «по позиции на доске». Без условий — «все партии базы». -- Enter — «Начать», Esc — «Отмена». Фокус по умолчанию — на «Начать». -- Нет Stockfish 19 → сначала существующее предложение скачать - (`need_review_engine`, новый `Pending::BrilliantSearch`), затем этот диалог. - -### 4.5. Один engine job на программу - -| Что занято | Кнопка 27 | Подсказка / поведение | -|---|---|---| -| Идёт поиск ошибок дебюта в подготовке (`prep.running()`) | неактивна | «Движок занят: идёт поиск ошибок дебюта в подготовке — дождитесь или остановите его» | -| Идёт разбор одной партии («Анализ партии») | неактивна | «Движок занят: идёт разбор партии {белые — чёрные}» | -| Проход 27 идёт в **другой** базе | неактивна | «Идёт поиск в «{база}»: 12 из 62 — остановите его там» | -| Живой анализ в открытой партии | — | При «Начать» живой анализ выключается, как `PrepAction::EngineStarted` | -| Во время прохода пользователь открыл партию | — | Кнопка «Анализ партии» и включение живого анализа неактивны. Подсказка: «Идёт поиск замечательных ходов в «{база}»: 12 из 62. Остановить — в библиотеке». Если партия уже разобрана, её отчёт открывается из кэша | -| Во время прохода — подготовка / игра с движком | — | Запуск поиска ошибок дебюта и «Играть» неактивны (решение владельца). Подсказка: «Идёт поиск замечательных ходов в «{база}»: 12 из 62 — дождитесь или остановите его в библиотеке». То же для «Играть с этой позиции» в партии | - -Во время прохода в **других** базах слот 27 показывает не кнопку, а компактный прогресс -«!! В «Mega»: 12 из 62» (ссылка ведёт в ту базу) и «Остановить». Кнопку «Найти» в этой базе -искать не нужно, а остановить проход можно с любого места. - -### 4.6. Матрица состояний - -| Состояние | Слот 27 | Таблица / прочее | -|---|---|---| -| Пустая база | строки условий нет (экран «Нет партий», как сейчас) | — | -| Без условий, ≤ 100 партий (ruy, 49) | кнопка активна | колонка «!!» пустая или со значками | -| 0 найдено | кнопка неактивна: «Нет партий по этим условиям» | «Нет партий» | -| 1…100 найдено | кнопка активна; подсказка «Разобрать движком {n} и отметить найденные !! и ! (Shift+A)» | — | -| > 100 (4 221, 11,7 млн) | кнопка **видна, неактивна** (`B2`); подсказка «Отфильтруйте партии, чтобы их было не больше 100» и вторая строка «Сейчас: 4 221» | — | -| Фильтр ещё считается (большая база, прогресс в шапке) | кнопка неактивна: «Подождите — партии ещё отбираются» | как сейчас, `set_opacity(0.6)` | -| Движок занят | §4.5 | — | -| Диалог | §4.4 | — | -| Идёт проход | прогресс (`B3`, `B4`) | спиннер в разбираемой строке, значки появляются по одному | -| Нажато «Остановить» | «Останавливаю…» и спиннер на месте полосы, до остановки процессов (≤ 2 с) | — | -| Остановлено | кнопка; **итоговое окно** по разобранным (§4.9, вид «остановлен») | недоразобранная партия остаётся без значка | -| Готово | кнопка; **итоговое окно** (§4.9) | — | -| Готово, ничего не найдено | итоговое окно, нули приглушены, «Блестящих ходов нет» (§4.9) | везде «·» | -| Часть пропущена | в итоговом окне строка «Не разобраны: 1 (Chess960)» (§4.9) | «—» в строке | -| Ошибка движка (упал, таймаут) | красный `error_fg_color` на месте прогресса: «Движок остановился с ошибкой: {причина}. Разобрано 12 из 62» + `×` | разобранное сохранено | -| Файл базы изменился во время прохода | проход останавливается, тот же красный текст: «База «{имя}» изменилась — поиск остановлен. Разобрано 12 из 62» | значки разобранных партий привязаны к их ходам (§5) и остаются верными | -| Закрытие окна во время прохода | без вопроса: процессы гасятся (как при выходе из разбора), разобранное уже сохранено | — | -| Одновременно запись из задачи 42 | оба прогресса в своих слотах, при нехватке места — сокращённые формы | — | -| Узкое окно 960×600 | сокращения §4.2 | колонка «!!» видна (28 px) | -| HiDPI ×2 | 1 логический px = 2 физических; спиннер и полоса — painter, чёткие | проверить, не обрезается ли «!!» в 28 px | -| Светлая тема | `assessment_text_color(.., dark=false)`: `#1a846f`, `#5b8135` (контраст ≥ 4,5:1) | — | - -### 4.7. Связь с выделением задачи 42 (решено) - -Кнопка и Shift+A **всегда** работают по отфильтрованной таблице. Выделение на них не влияет, -и в пакетном меню §42.7 пункта для поиска нет (решение владельца). Итоговое окно (§4.9) только -выбирает строку обычным щелчком. Многострочное выделение оно не создаёт. - -### 4.8. Клавиатура и фокус - -| Клавиша | Где | Действие | -|---|---|---| -| Shift+A | библиотека, фокус не в поле ввода | то же, что кнопка (по аналогии с «Анализ партии» в партии, Shift+A). Если кнопка неактивна — тост с текстом её подсказки | -| Tab | строка условий | кнопка и «Остановить» — обычные фокусируемые виджеты с рамкой фокуса egui | -| Enter / Esc | диалог | «Начать» / «Отмена» | -| Esc | во время прохода | **не останавливает** (Esc снимает выделение и закрывает ящик, §42.6). Остановить — только явно: «Остановить» | - -Подсказки: у кнопки — §4.6; у «Остановить» — «Остановить поиск; разобранные партии -сохранятся»; у прогресса — полный текст и текущая партия «Сейчас: Carlsen — Nakamura, 2025». - -### 4.9. Итоговое окно (дополнение владельца 2026-11-27) - -Задача окна: одним взглядом показать, что нашёл проход по выборке, — сначала блестящие -и замечательные ходы, затем ошибки, затем общий уровень. Из окна можно сразу перейти к партиям с !!. - -Макеты: `docs/design/task-27/E1-summary-1920.png` (готово, 1920×1080, игрок в фильтре), -`E2-summary-960-stopped.png` (остановлено, 960×600). - -#### Когда показывается - -| Событие | Окно | -|---|---| -| Проход закончился | открывается само, вид «готово» | -| Нажато «Остановить», процессы остановлены | открывается само, вид «остановлен» по разобранным партиям | -| Ошибка движка или база изменилась во время прохода | красный текст на месте прогресса (§4.6). Окно по разобранным открывается по щелчку на этом тексте («Итог по разобранным»), само не открывается | -| Кнопка «Найти» нажата, а все партии выборки уже разобраны | открывается **сразу, без диалога**. Это и есть повторный показ (§4.4) | -| Кнопка нажата, разобраны не все | обычный диалог (§4.4). В диалоге появляется третья кнопка «Итог по разобранным ({k})», если k ≥ 1 | - -**Отдельной кнопки «Итог» в строке условий нет.** В строке и так тесно (§4.2), а итог всегда -считается заново из индекса для **текущей** выборки, поэтому его можно вызвать той же кнопкой. -Подсказка кнопки, когда всё разобрано: «Все {games} уже разобраны — показать итог (Shift+A)». - -#### Состав и порядок (сверху вниз) - -``` -┌───────────────────────────────────────────────────────────────────────────┐ -│ Итог · разобрано: 62 партии × │ ← заголовок 17 px -│ Mega Database 2026 · Игрок: carlsen magnus · Годы: 2025–2026 · Elo ≥ 2780 │ ← weak 12 px, условия -│ Считаются только ходы игрока «carlsen magnus»: белыми 31, чёрными 31 │ ← weak, только при игроке -│ │ -│ 2 Блестящий │ ← #26c2a3 -│ 9 Замечательный │ ← #81b64c -│ 71 Неточности │ ← #56b4e9 -│ 38 Ошибки │ ← #ffa459 -│ 11 Зевки │ ← #fa412d -│ 27 Средняя потеря сантипешек │ -│ 86% Средняя точность │ -│ ───────────────────────────────────────────────────────────────────────── │ -│ Партии с !! (2) │ ← strong 13 px -│ 21.Rxf7!! Carlsen, M. — Nakamura, H. · 1-0 · Chessable Masters · 19.02.2025 │ ← выбранная строка списка -│ 34…Nf3+!! Erigaisi, A. — Carlsen, M. · ½-½ · Chessable Masters · 19.02.2025 │ -│ Щелчок — выбрать строку в таблице, двойной щелчок — открыть на этом ходе │ ← weak 12 px -│ [Открыть партию] [Закрыть] │ -└───────────────────────────────────────────────────────────────────────────┘ -``` - -1. **Заголовок:** «Итог · разобрано: {games}» (`i18n::games`: «62 партии», «1 партия»); при - остановке — «Поиск остановлен · разобрано: {i} из {n}». Справа `×`. -2. **Подзаголовок:** база и условия выборки (как в диалоге §4.4) — чтобы позже, при повторном - показе, было понятно, к чему относятся числа. -3. **Строка про игрока** — только если в фильтре есть «Игрок»: «Считаются только ходы игрока - «{name}»: белыми {w}, чёрными {b}». Если задано «белыми» или «чёрными» — «…игрока «{name}» - белыми ({w} партий)». Партия, где игроку подходят обе стороны, учитывается за обе. Без игрока - строки нет, а считаются ходы обеих сторон всех партий. -4. **Таблица категорий** — тот же grid и стиль, что в отчёте партии (`review.rs:760+`): число - справа strong 15 px, название 15 px, цвет `judgement_text_color` (в светлой теме — - `assessment_text_color(.., false)`). При нуле строка приглушена `weak_text_color`, как в - отчёте. Порядок и названия берутся из отчёта, ключи `judgement_plural` те же: - !! → ! → ?! → ? → ??. Числа — суммы по разобранным партиям (с учётом п. 3). -5. **Средняя потеря сантипешек** и **средняя точность**: среднее по партиям (по сторонам), - а не по ходам. Это та же величина, что в отчёте, усреднённая по {k} сторонам. При игроке — - только его стороны. Фазовые строки («Дебют / Миттельшпиль / Эндшпиль») не показываются: - в сумме по разным партиям они мало что говорят, а окно стало бы вдвое выше. Подсказка у - «Средняя точность»: «Среднее по {k} партиям: от {min}% до {max}%». -6. **Разделитель** и **список «Партии с !! ({n})»**: одна строка на **ход** !! (у партии с двумя - !! — две строки). Порядок — как в таблице на момент прохода, внутри партии — по ходу. Слева - ход с номером (Ubuntu-B 13 px, бирюзовый, нотация по настройке, колонка шириной по - самому длинному ходу). Справа «Белые — Чёрные · рез. · турнир · дата» обрезается многоточием. - Высота строки 24 px. Список — `ScrollArea` высотой не больше 6 строк (144 px). Больше 6 — - прокрутка, окно не растёт. -7. **Подсказка по списку** (weak 12 px) и **кнопки** справа внизу: «Открыть партию» - (активна, когда в списке выбрана строка) и «Закрыть». Основной (синей) кнопки нет: окно - ничего не подтверждает. - -#### Список: щелчок и клавиатура - -| Действие | Результат | -|---|---| -| Щелчок по строке списка | строка списка выбрана (заливка `selection.bg_fill`). **В таблице за окном выбирается та же партия** (одна строка, как обычный щелчок в таблице; выделение задачи 42 сводится к ней), таблица прокручивается к ней. Окно остаётся открытым | -| Двойной щелчок / Enter / «Открыть партию» | открыть партию **на этом ходе** со вкладкой «Отчёт» (как пункт меню «Открыть на ходе», §4.3). Окно закрывается. Возврат (Ctrl+W) — в библиотеку с той же выборкой, партия выбрана в таблице, окно снова не открывается | -| ↑ / ↓ | по строкам списка, фокус в окне | -| Esc, `×`, «Закрыть» | закрыть окно; выборка, сортировка и выделение не меняются | -| Партия списка скрыта текущим фильтром (фильтр поменяли при открытом окне) | строка списка приглушена, подсказка «Скрыта фильтром»; щелчок только выбирает строку списка, двойной щелчок открывает партию | - -Окно **немодальное** (`egui::Window`, как «Добавить в базу», без затемнения), его можно -перетаскивать. Таблица за ним работает. Окно привязано к базе: при переключении базы на -полке оно закрывается. - -#### Варианты состояния - -| Состояние | Что меняется | -|---|---| -| Готово, есть !! | как на макете E1 | -| Готово, !! нет, но есть ! | список заменяется строкой weak «Блестящих ходов нет. Партии с ! — сортировка по колонке «!!»» и ссылкой «Отсортировать» (сортирует таблицу, окно остаётся) | -| Готово, нет ни !!, ни ! | строки 1–2 таблицы приглушены (нули), под разделителем — «Блестящих и замечательных ходов нет» | -| Остановлено (E2) | заголовок «Поиск остановлен · разобрано: 12 из 62»; под строкой игрока weak «50 партий не разобраны — «Продолжить» разберёт только их»; слева от «Открыть партию» кнопка «Продолжить», она открывает диалог §4.4 по оставшимся | -| Разобрано 0 (остановили на первой партии) | окно не открывается. Тост «Поиск остановлен: ни одна партия не разобрана» | -| Часть пропущена | weak-строка под подзаголовком: «Не разобраны: 1 (Chess960)». В числе «разобранных» её нет | -| Среди партий есть старые разборы | weak-строка «{k} из них разобраны прежними настройками движка». Числа учитываются (решение владельца) | -| Игрок в фильтре, но в партии он не найден по имени (другое написание) | партия считается без ходов игрока; строка «В {k} партиях игрок не найден по имени — их ходы не считались», подсказка — список номеров | -| 960×600 (E2) | окно шириной `min(600, окно − 40)`, высота не больше `окно − 80`. Список сжимается до 3 строк, текст партии обрезается многоточием | -| HiDPI | без особенностей. Числа и цвета — текст, проверить обрезку чисел из трёх цифр («100%», «128») | - -## 5. Требования к реализации (разработчику) - -1. **Слот 27 в `chips()`:** крайний справа, перед блоком порядка ходов и слотом 42 (§4.1). - Ширина измеряется текстом, сокращения по §4.2, резерв ширины прогресса — по максимальному - значению. Высота строки остаётся 22 px. -2. **Колонка «!!»:** `Column::exact(28.0)` после «Рез.», вне правил `show_*`, есть во всех - раскладках (войдёт в ключ `layout` для `id_salt`). Сортировка `SortKey::Marks` по §4.3. - Рисование — `RichText` Ubuntu-B 13 px или painter (спиннер — `egui::Spinner` 12 px). -3. **Индекс отметок на базу** (без него таблица на 11,7 млн строк не сможет показывать - значки: имя кэша разбора — хэш основной линии, `game-review::cache_name`, и вычислять его - для каждой видимой строки слишком дорого). Файл в кэше программы рядом с кэшем разбора: - `marks/.json`, где номер записи → {хэш основной линии, число !!, - и **по каждому цвету**: число !!, !, ?!, ?, ??, точность, средняя потеря, до 3 ходов !!/! с - номерами полуходов (для подсказки и списка итога — все ходы !!), `search` версия, - пропуск/причина}. По цвету — потому что при игроке в фильтре считаются только его ходы. - Сторона игрока в партии определяется тем же сравнением имени, что и фильтр «Игрок». При показе - используется запись, только если хэш совпадает с кэшем разбора. Если база - изменилась (fingerprint) — проверка хэша при следующем разборе, без массового пересчёта. - **Индекс пополняет и разбор одной партии**, открытой из базы («Анализ партии»). Иначе - разобранная вручную партия не получит значок. -4. **Проход:** фоновая задача; список номеров записей снимается в порядке таблицы на момент - «Начать». Для каждой партии: кэш разбора свежий → взять отметки; иначе — тот же - `game-review` job с фиксированными параметрами (`SEARCH_NODES`, процессы по `job.rs`). - После каждой партии кэш разбора и индекс сохраняются атомарно. Прогресс отправляется - через канал не чаще 10 раз/с. «Остановить» — `AtomicBool` + `stop` процессов, таймаут - 2 с, затем kill. Оценки `[%eval]` из PGN для прохода **не используются** (по ним !!/! не - ставятся, `decisions.md`). Партия разбирается движком, и в её PGN ничего не пишется. -5. **Взаимоисключение** с подготовкой и разбором одной партии (§4.5): общий флаг «engine job - занят» в `app.rs`, к нему подключить и `game.engine_busy`. -6. **Диалог** — по образцу `own_db::Chooser`, оценка по §4.4, фоновый подсчёт разобранных. -7. **Пункт меню строки** «Открыть на ходе …» (§4.3). Пакетного пункта нет (§4.7). -8. **Итоговое окно** (§4.9): `egui::Window` без затемнения. Считается из индекса для текущей - выборки (≤ 100 записей), в фоне не нужно. Пересчёт идёт при открытии и при смене фильтра, - пока окно открыто (числа в окне не меняются: окно держит выборку, по которой открыто; - меняются только пометки «Скрыта фильтром»). Открытие партии на ходе — тот же путь, что - «Открыть на ходе» в меню. Щелчок по строке списка — то же, что щелчок по строке таблицы, - плюс `scroll_to_selected`. -9. **Отладочные хуки для снимков:** `CP_BRILLIANT_SUMMARY=1` (открыть итоговое окно по - индексу сразу после старта); `CP_MARKS_DEMO=1` (заполнить индекс фиктивными - отметками для первых строк); `CP_BRILLIANT_RUN=1` (сразу запустить проход без диалога); - `CP_BRILLIANT_SLOW=1` (`fake_uci` с задержкой, чтобы снять прогресс); `CP_KEYS=Shift+A` - уже работает. - -## 6. Тексты ru / en - -| Смысл | ru | en | -|---|---|---| -| кнопка | !! Найти замечательные ходы | !! Find great moves | -| кнопка, коротко | !! Найти ходы | !! Find moves | -| подсказка, активна | Разобрать движком {games} и отметить найденные !! и ! (Shift+A) | Review {games} with the engine and mark the !! and ! moves found (Shift+A) | -| подсказка, > 100 | Отфильтруйте партии, чтобы их было не больше 100 | Filter the games down to 100 or fewer | -| подсказка, > 100, 2-я строка | Сейчас: {n} | Now: {n} | -| 0 партий | Нет партий по этим условиям | No games match these conditions | -| фильтр считается | Подождите — партии ещё отбираются | Wait: the games are still being filtered | -| занято, подготовка | Движок занят: идёт поиск ошибок дебюта в подготовке — дождитесь или остановите его | The engine is busy searching opening errors in a preparation: wait or stop it | -| занято, разбор | Движок занят: идёт разбор партии {game} | The engine is busy reviewing {game} | -| занято, другая база | Идёт поиск в «{db}»: {i} из {n} — остановите его там | Searching in «{db}»: {i} of {n}; stop it there | -| диалог, заголовок | Найти замечательные ходы | Find great moves | -| подзаголовок | {db} · {games} по условиям: {list} / по позиции на доске / все партии базы | {db} · {games} matching: {list} / by the board position / all games | -| строка 1 | Движок разберёт {games} — примерно {time}. | The engine will review {games}: about {time}. | -| строка 2 | {k} уже разобраны: их отметки возьмутся из сохранённого разбора. | {k} are already reviewed: their marks come from the saved review. | -| строка 3 | Компьютер будет загружен (до {p} процессов Stockfish 19). Работать с программой можно; остановить — в любой момент, разобранные партии сохранятся. | The computer will be busy (up to {p} Stockfish 19 processes). You can keep working and stop at any time; the reviewed games are kept. | -| считаю | Считаю, сколько партий уже разобрано… | Counting the games already reviewed… | -| кнопки | Отмена / Начать | Cancel / Start | -| прогресс | Проанализировано {i} из {n} · осталось ≈ {time} | Analysed {i} of {n} · ≈ {time} left | -| прогресс, коротко | {i} из {n} | {i} of {n} | -| прогресс, другая база | В «{db}»: {i} из {n} | In «{db}»: {i} of {n} | -| остановить | Остановить | Stop | -| подсказка остановить | Остановить поиск; разобранные партии сохранятся | Stop the search; the reviewed games are kept | -| останавливаю | Останавливаю… | Stopping… | -| пропущено | , пропущено {k} ({reason}) | , {k} skipped ({reason}) | -| подсказка кнопки, всё разобрано | Все {games} уже разобраны — показать итог (Shift+A) | All {games} are already reviewed: show the summary (Shift+A) | -| диалог, 3-я кнопка | Итог по разобранным ({k}) | Summary of the reviewed ({k}) | -| итог, заголовок | Итог · разобрано: {games} | Summary · reviewed: {games} | -| итог, заголовок при остановке | Поиск остановлен · разобрано: {i} из {n} | Search stopped · reviewed: {i} of {n} | -| итог, игрок | Считаются только ходы игрока «{name}»: белыми {w}, чёрными {b} | Only the moves of «{name}» are counted: as White {w}, as Black {b} | -| итог, игрок одним цветом | Считаются только ходы игрока «{name}» белыми ({games}) / чёрными ({games}) | Only the moves of «{name}» as White ({games}) / as Black ({games}) are counted | -| итог, имя не найдено | В {k} партиях игрок не найден по имени — их ходы не считались | The player's name was not found in {k} games: their moves were not counted | -| итог, не разобраны | Не разобраны: {k} ({reason}) | Not reviewed: {k} ({reason}) | -| итог, остались | {k} партий не разобраны — «Продолжить» разберёт только их | {k} games are not reviewed: «Continue» reviews only them | -| итог, старые разборы | {k} из них разобраны прежними настройками движка | {k} of them were reviewed with the previous engine settings | -| итог, категории | Блестящий / Замечательный / Неточности / Ошибки / Зевки — ключи отчёта (`judgement_plural`) | Brilliant moves / Great moves / Inaccuracies / Mistakes / Blunders — the report's keys | -| итог, потеря | Средняя потеря сантипешек | Average centipawn loss | -| итог, точность | Средняя точность | Average accuracy | -| итог, подсказка точности | Среднее по {k} партиям: от {min}% до {max}% | Average of {k} games: {min}% to {max}% | -| итог, список | Партии с !! ({n}) | Games with !! ({n}) | -| итог, подсказка списка | Щелчок — выбрать строку в таблице, двойной щелчок — открыть на этом ходе | Click selects the row in the table; double-click opens at this move | -| итог, скрыта | Скрыта фильтром | Hidden by the filter | -| итог, только ! | Блестящих ходов нет. Партии с ! — сортировка по колонке «!!» | No brilliant moves. Games with ! — sort by the «!!» column | -| итог, ссылка | Отсортировать | Sort | -| итог, ничего | Блестящих и замечательных ходов нет | No brilliant or great moves | -| итог, кнопки | Продолжить / Открыть партию / Закрыть | Continue / Open game / Close | -| остановлен, 0 разобрано (тост) | Поиск остановлен: ни одна партия не разобрана | Search stopped: no game was reviewed | -| занято, поиск (Играть, поиск ошибок дебюта) | Идёт поиск замечательных ходов в «{db}»: {i} из {n} — дождитесь или остановите его в библиотеке | Searching for great moves in «{db}»: {i} of {n}; wait or stop it in the library | -| ошибка движка | Движок остановился с ошибкой: {reason}. Разобрано {i} из {n} | The engine failed: {reason}. {i} of {n} reviewed | -| база изменилась | База «{db}» изменилась — поиск остановлен. Разобрано {i} из {n} | «{db}» changed; the search stopped. {i} of {n} reviewed | -| ячейка, !! | Блестящих ходов: {n} — {moves} | Brilliant moves: {n}: {moves} | -| ячейка, ! | Замечательных: {n} — {moves} | Great moves: {n}: {moves} | -| ячейка, · | Разобрана: блестящих и замечательных ходов нет | Reviewed: no brilliant or great moves | -| ячейка, — | Не разбирается: {reason} | Cannot be reviewed: {reason} | -| ячейка, устарел | Разбор прежними настройками движка | Reviewed with the previous engine settings | -| ячейка, идёт | Разбирается… | Being reviewed… | -| меню строки | Открыть на ходе {move} | Open at {move} | -| в партии во время прохода | Идёт поиск замечательных ходов в «{db}»: {i} из {n}. Остановить — в библиотеке | Searching for great moves in «{db}»: {i} of {n}. Stop it in the library | - -Числа — с группировкой (`grouped`), «{games}» — `i18n::games(n)`. Новые ключи нужно добавить во все языки `i18n.rs`, а не только ru/en. «Замечательный» = «!», -«блестящий» = «!!» (`decisions.md`). Английское «great» — как в отчёте («Great moves»). - -## 7. Критерии приёмки (дизайн-ревьюер — не автор кода) - -Окна — только через `scripts/dev/headless-run.sh`, профиль изолирован. Каждый пункт -подтверждается снимком с указанием размера и состояния. - -1. 1920×1080: ruy (49, без условий) — кнопка активна; alekhin (267) — неактивна, снимок - подсказки; Mega «carlsen, 2015–2026, ≥2600» (4 221) — неактивна, подсказка с «Сейчас: 4 221»; - Mega «…2025–2026, ≥2780» (62) — активна. **Верх таблицы и строка заголовков на всех - снимках на одной y**, высота строки условий 22 px. -2. 960×600 (ru и en): три чипа + кнопка; три чипа + «Выбрано: 3 · Снять» + кнопка (чипы - свернулись в «+N ещё», кнопка на месте). Шапка базы не перенеслась из-за 27. -3. Серия по горизонтали: Ctrl+щелчок по 2-й строке (появился счётчик 42), смена позиции на - доске (появился порядок ходов) — **x кнопки не меняется** (крайняя справа). -4. Колонка «!!» видна на 1920 и 960 и в базе без единого значка. Появление первого значка - (серия во время прохода, ≥ 3 снимка) не меняет ширины колонок и положения текста. -5. Значки читаются в тёмной и светлой теме и в оттенках серого (`!!`, `!`, `·`, `—` различимы - по форме). На выбранной строке знак виден. -6. Серия прохода (`CP_BRILLIANT_SLOW`): диалог → «Начать» → 0 из N → середина → «Останавливаю…» - → остановлено (итоговое окно E2); и запуск → готово → итоговое окно E1. На всех - снимках: таблица не сдвинута, полоса прогресса и «Остановить» не дрожат по x при смене - цифр (сравнить x «Остановить» на двух снимках). -7. Диалог: ширина и кнопки как у `chooser-ru.png`. Состояние «Считаю…» не меняет высоту окна - (снимок до и после подсчёта). -8. Занятый движок: подготовка ищет ошибки → кнопка неактивна, подсказка; во время прохода - открыть партию → «Анализ партии» неактивна с подсказкой; вернуться (Ctrl+W) — фильтры, - прокрутка, выделение и прогресс на месте. -9. Ошибка движка (`fake_uci` с падением): красный текст на месте прогресса, `×`, таблица на месте. -11. Итоговое окно (1920 и 960, ru/en): порядок и цвета категорий совпадают с отчётом партии - (сравнить с `docs/screenshots/review.png`); нули приглушены; строка игрока есть только при - фильтре «Игрок»; список > 6 строк прокручивается, окно не растёт. Серия: щелчок по строке - списка → в таблице выбрана та же партия и прокручена к ней (снимок), окно на месте; - двойной щелчок → партия на ходе !!, вкладка «Отчёт»; Ctrl+W → библиотека, окно закрыто, - партия выбрана. Повторно «Найти» при всех разобранных → сразу окно, без диалога. - Варианты «только !» и «ничего» — по снимку. -10. HiDPI (если окружение позволяет, иначе пометить «не проверено»): «!!» в 28 px не обрезан, - спиннер чёткий. - -## 8. Что передать тестировщику - -- Лимит: ровно 100 — активна, 101 — неактивна; при изменении фильтра во время прохода - проход идёт по зафиксированному списку. -- Кэш: партия, разобранная вручную, в проходе не пересчитывается (время ≈ 0, запросов к - движку нет) и сразу получает значок. Устаревший разбор (`SEARCH_VERSION`) не пересчитывается - (решение владельца). -- Игрок в фильтре: суммы итога и значки — только по его ходам. Сверка вручную на 3 партиях: - суммы итога = суммы строк игрока в отчётах этих партий. «белыми» / «чёрными» / «любым»; - партия игрока с самим собой; написание имени, не совпавшее с фильтром. -- Итог без игрока = сумма обеих сторон по отчётам; средняя точность = среднее по сторонам. -- Во время прохода «Играть» и поиск ошибок дебюта неактивны; после окончания — снова активны. -- Остановка: после «Остановить» процессов `stockfish` нет через ≤ 2 с; разобранные партии - есть в кэше и индексе после перезапуска; недоразобранная — без значка, без битого файла. - То же при kill программы во время прохода. -- Сохранность: исходный PGN, `.cbv`/`.cbh` не меняются (sha256/mtime до и после). В PGN своих баз - ничего не дописывается. -- Индекс: удаление партии из своей базы (номера сдвигаются) — значки у других партий не - «переезжают» на чужие строки (проверка хэша); внешнее изменение файла. -- Взаимоисключение: проход ↔ подготовка ↔ «Анализ партии» ↔ живой анализ; проход в базе A, - кнопка в базе B. -- Chess960, партии без ходов, FEN с fullmove=0, учебный `--` — «—» с причиной, проход не падает. -- `[%eval]` в PGN: проход всё равно запускает движок, отметки ставятся. -- Shift+A в поле поиска печатает «A», а не запускает проход. - -## 9. Решения владельца (2026-11-27) - -Все пять вопросов приняты по рекомендации: -1. Кнопка работает только по фильтру, пункта для выделенных нет (§4.7). -2. Если в фильтре задан игрок, считаются только его ходы (§4.3, §4.9). -3. Старый разбор засчитывается без пересчёта (§4.3). -4. Фильтра «только с !!» нет, есть сортировка по колонке «!!» (§4.3). -5. Игра с движком во время прохода запрещена, есть подсказка (§4.5). - -Дополнение — итоговое окно (§4.9). - -Открытых вопросов по итоговому окну нет. Решения дизайнера, которые владелец может -пересмотреть: -- фазовые точности в окне не показываются; -- в списке только !!, без !; -- отдельной кнопки «Итог» нет — итог открывает та же кнопка «Найти», когда всё разобрано. diff --git a/docs/design/task-27-selected-games-analysis-2026-11-27.md b/docs/design/task-27-selected-games-analysis-2026-11-27.md deleted file mode 100644 index 5b4112a..0000000 --- a/docs/design/task-27-selected-games-analysis-2026-11-27.md +++ /dev/null @@ -1,414 +0,0 @@ -# Пакетный анализ вручную выделенных партий — расширение задачи 27 - -Статус: спецификация дизайнера, 2026-11-27. Относится к задаче 46 в `docs/dev/tasks.md`. -Код не менялся; реализация и визуальная приёмка этим документом не заявляются. Учтены решение -владельца (`docs/decisions.md:546-553`) и требования аналитика -`docs/research/task-27-selected-games-analysis-2026-11-27.md`, особенно §3.1, §6 и §8–10. - -Документ заменяет только прежнее правило «кнопка работает только по фильтру» из §4.7 и §9 -`task-27-brilliant-search-2026-11-27.md`. Остальные правила задач 27 и 42 сохраняются. - -## 0. Что посмотрено в реальном интерфейсе - -Перед проектированием просмотрены изображения, а не только их названия: - -- `designExample/список баз и партий выбранной базы.png` и - `designExample/доска с панелью ходов и анализом движка.png` — исходные референсы: таблица и - чтение партии остаются центром продукта; новую «dashboard»-компоновку не переносим. -- `docs/screenshots/library.png` — главный экран с фильтром: компактная шапка, постоянная строка - условий, плотная виртуальная таблица и правая панель. -- `docs/screenshots/game.png` и `docs/screenshots/review.png` — экран партии и отчёт: обычные - тёмные поверхности, синее выделение, текстовые `!!`/`!`; новые цвета и контейнеры не нужны. -- Реальные снимки реализации `docs/qa/task-27-design/c-idle-ruy.png`, `c-sel-run.png`, - `c-run-series.png`, `c-dlg-cond.png`, `car-done.png`, `full-done.png`, `stopped.png` — кнопка и - прогресс уже занимают один крайний правый слот; счётчик выделения стоит левее и не двигает - таблицу; диалог имеет ширину 520 px; итог использует существующие строки отчёта. -- Реальные снимки задачи 42 `/tmp/opencode/rev42/s2/many.png`, - `/tmp/opencode/rev42/s/filter.png`, `/tmp/opencode/rev42/s2/prog.png` и - `/tmp/opencode/rev42/s2/game43.png` — выделение, скрытые фильтром записи, прогресс и возврат в - партию используют уже принятую визуальную систему. Измерения и ограничения этих снимков - зафиксированы в `docs/qa/task-42-design-review-2026-11-27.md`. - -Следствие: меняются только выбор источника и текстовые подписи существующих элементов. Доска, -нотация, колонка `!!`, счётчик задачи 42, ширина окон и визуальные токены не перепроектируются. - -## 1. Задача изменения — одной фразой - -Пользователь запускает **тот же** поиск `!!`/`!` либо по ручному выделению, если оно есть, либо -по текущему фильтру, если выделения нет, и до запуска явно видит состав и ограничения разбора. - -Приоритет информации: источник и допустимость запуска → число выбранных и скрытых → правило -«только ходы игрока», если оно активно → время/нагрузка → неизменный прогресс и итог. - -## 2. Термины и неизменные правила источника - -- **N** — число уникальных записей ручного выделения задачи 42 (`marked`), включая одну запись. - Сам по себе курсор на невыделенной строке не создаёт N. -- **F** — число записей последнего полностью рассчитанного текущего `view`: фильтр, быстрый поиск - и поиск по позиции входят сюда по прежним правилам. -- **k** — число выделенных записей вне этого `view`: `k = N − |selection ∩ view|`. Сортировка не - делает запись скрытой. -- **Источник** — `selection` при N>0, `filter` при N=0. Объединения `selection ∪ view` нет. -- Лимит применяется **до** исключения кэшированных и неподдерживаемых записей: N=1…100 либо - F=1…100. N=101 не откатывается даже к подходящему F=1. - -**Очистка и возврат к фильтру.** Esc и существующая ссылка «Снять» при N≥2 лишь сворачивают -выделение к строке курсора: остаётся N=1, поэтому следующий запуск всё ещё идёт по одной -выделенной партии. Полное N=0 даёт существующее переключение последней записи — Ctrl+щелчок по -ней или Ctrl+Space на ней. Только после N=0 восстанавливается filter-only. Новых жестов и обещаний -«Esc вернёт фильтр» не вводим; поведение самой ссылки задачи 42 не меняем. - -## 3. Пользовательский путь и сохранение контекста - -1. Пользователь выделяет A, B и C, затем меняет фильтр так, что B и C скрыты. Существующий - счётчик показывает «Выбрано: 3 (2 скрыто фильтром) · Снять»; кнопка `!!` остаётся на месте. -2. Щелчок по кнопке или Shift+A открывает прежний диалог, но его источник явно гласит - «Выбрано: 3 партии», отдельно «2 скрыто текущим фильтром». Невыделенная видимая D не - добавляется. При активном условии «Игрок» здесь же видно правило только его ходов (§6). -3. «Начать» запускает показанный набор. После этого можно изменить выделение, фильтр и сортировку, - открыть партию и вернуться Ctrl+W: текущее выделение и прокрутка ведут себя как прежде, а - состав и порядок идущего прохода не меняются (§7). -4. Завершение/остановка открывает существующий итог по снимку запуска. «Продолжить» относится к - оставшимся записям того же снимка, не к новому выделению. -5. Повторный вызов при том же составе использует кэш; если новой работы нет, сразу открывается - итог без предстартового диалога и без запуска Stockfish. - -Чтобы до «Начать» заменить показанный в диалоге состав, пользователь нажимает «Отмена» и вызывает -команду повторно после изменения выделения. Диалог не подменяет свой состав молча (§7.1). - -## 4. Одна кнопка: состояния, disabled и tooltip - -### 4.1. Общие правила - -- Вид, текст и место кнопки не меняются: `!! Найти замечательные ходы` либо существующая короткая - форма `!! Найти ходы`. Число и слово «выделенных» **в саму кнопку не добавляются**: это сохраняет - ширину слота. Источник различён текстом подсказки и диалога, не цветом. -- Сначала действуют существующие блокировки engine job/прохода в другой базе. Во время своего - прохода вместо кнопки — существующий прогресс, при остановке — «Останавливаю…». -- Если новый фильтр ещё считается, достоверного k ещё нет. При N=1…100 кнопка временно неактивна: - `Подождите — считаю, сколько выделенных партий скрыто текущим фильтром`. - Это ожидание только ради честного k, а не зависимость состава или лимита от F. При N>100 причина - переполнения известна сразу и имеет приоритет над ожиданием k. При N=0 остаётся прежнее - `Подождите — партии ещё отбираются`. -- Неактивная кнопка использует существующий `on_disabled_hover_text`. Shift+A вне поля ввода при - той же блокировке показывает тост с **тем же текстом причины**. В поле ввода Shift+A печатает `A`. - -### 4.2. Матрица приоритета (фильтр уже рассчитан, движок свободен) - -| N | F | Кнопка и источник | Что обязано произойти | -|---:|---:|---|---| -| 0 | 0 | disabled, фильтр | Прежнее `Нет партий по этим условиям` | -| 0 | 1…100 | активна, фильтр | Прежний filter-only диалог по всем F | -| 0 | >100 | disabled, фильтр | Прежние две строки `Отфильтруйте партии, чтобы их было не больше 100` / `Сейчас: {F}` | -| 1 | 0 | **активна, выделение** | Диалог N=1, k=1; анализируется скрытая запись. Пустая видимая выдача не скрывает команду | -| 1 | >100 | **активна, выделение** | Диалог N=1, k=0; большой F не блокирует допустимое выделение | -| 2…100 | 0 | **активна, выделение** | Все N скрыты и все входят; k=N | -| 2…100 | 1…100 | **активна, выделение** | Анализируются только выделенные; видимые невыделенные записи F не добавляются | -| 100 | >100 | **активна, выделение** | Ровно 100 допустимо; большой F игнорируется как источник | -| 101 и больше | 0 | disabled, выделение | Причина по N, а не «нет партий по условиям» | -| 101 и больше | 1…100 | disabled, выделение | Подходящий F **не подменяет** слишком большое выделение | -| 101 и больше | >100 | disabled, выделение | Одна причина по N; вторую ошибку про F не нагромождаем | -| стало 0 | любой готовый F | снова правила N=0 | Полное переключение последней записи возвращает прежний filter-only | - -Непустая база с F=0 и N>0 сохраняет строку условий и доступную кнопку. Полностью пустая база без -выделения сохраняет существующий экран «Нет партий». - -### 4.3. Точные короткие подсказки для selection - -**Активна, N=1…100:** - -```text -Выбрано: {games}. Разобрать их движком и отметить !! и ! (Shift+A) -``` - -Вторая строка при k>0: - -```text -Скрыто текущим фильтром: {k}; эти партии тоже входят. -``` - -При k=0 вместо неё: - -```text -Фильтр не меняет состав этого запуска. -``` - -Здесь `{games}` — существующее `i18n::games(N)`, например «1 партия», «3 партии», «100 партий». -Для filter-only активная подсказка остаётся прежней: -`Разобрать движком {games} и отметить найденные !! и ! (Shift+A)`. - -**Disabled, N>100 — для любого F:** - -```text -Выбрано: {games} — больше 100. -Оставьте не больше 100 выделенных; фильтр не используется. -``` - -Эта подсказка намеренно не предлагает Esc как «полную очистку»: после Esc останется N=1. При N=1 -подсказка особенно важна, потому что постоянного счётчика «Выбрано: 1» по правилам задачи 42 нет. - -## 5. Макет строки условий — без нового элемента - -```text -[условия…] [Выбрано: N (k скрыто фильтром) · Снять] [порядок ходов] [!! Найти замечательные ходы] - ↑ прежний крайний слот -``` - -- Существующий `right_slot` не меняет ни ширины, ни положения при смене `filter → selection`, - появлении k, переходе `кнопка → прогресс → кнопка`, ошибке или итоге. -- Строка условий остаётся высотой **22 логических px**. Верх таблицы, высота её заголовка и строки - не сдвигаются. Счётчик задачи 42 по-прежнему может отнимать место у чипов условий, но не меняет - высоту и не двигает крайний правый слот. -- Новых кнопок, выпадающего меню источника, переключателя «фильтр/выделение», второй панели или - отдельного пункта контекстного меню нет. - -## 6. Предстартовый диалог - -### 6.1. Selection-макет - -Тот же `egui::Window`, ширина содержимого 520 px, заголовок, фон, кнопки и отступы существующего -диалога. Пример согласованного счёта: N=12, k=9, кэшировано 3, новых 8, пропущено 1. - -```text -┌──────────────────────────────────────────────────────────────┐ -│ Найти замечательные ходы │ -│ Mega Database 2026 · Выбрано: 12 партий │ ← weak 12 px -│ 9 скрыто текущим фильтром │ ← weak 12 px, только k>0 -│ Считаются только ходы игрока «carlsen magnus». │ ← 12 px обычным текстом, если задан игрок -│ │ -│ Движок разберёт 8 партий — примерно 4 минуты. │ -│ 3 уже разобраны: их отметки возьмутся из сохранённого разбора.│ -│ 1 нельзя разобрать (пустой ход в основной линии) │ ← weak, если есть пропуски -│ │ -│ Компьютер будет загружен (до 8 процессов Stockfish 19). │ -│ Работать с программой можно; остановить — в любой момент, │ -│ разобранные партии сохранятся. │ -│ [Итог по разобранным (3)] [Отмена] [Начать] │ ← третья кнопка по прежнему правилу -└──────────────────────────────────────────────────────────────┘ -``` - -Для N=1 первая строка — `… · Выбрано: 1 партия`; при k=1 — `1 скрыто текущим фильтром`. Не писать -в selection-варианте «{F} по условиям» или «все партии базы»: это создало бы впечатление разбора -всего фильтра. Невыделенные записи фильтра нигде не прибавляются к N. - -### 6.2. Player-only должен быть заметен до запуска - -Существующее решение владельца не меняется: если в **условии «Игрок»** задан игрок, в отметках и -итоге учитываются только его ходы; быстрый поиск по имени сам по себе это правило не включает. -Для произвольного выделения это особенно важно: партия остаётся в проходе даже если игрока в ней -нет, но её ходы тогда не засчитываются. - -Поэтому в selection-диалоге добавляется одна текстовая строка того же смысла, что в итоге: - -- любой цвет: `Считаются только ходы игрока «{name}».`; -- ограничение цветом: `Считаются только ходы игрока «{name}» белыми.` / `… чёрными.`. - -Она использует обычный `text_color`, 12 px, без значка и нового цвета; weak здесь недостаточно для -единственного предупреждения о неочевидном ограничении. Tooltip строки: -`Условие игрока ограничивает считаемые ходы, но не исключает выбранные партии из разбора.` -В итоге сохраняется существующая подробная weak-строка с числом сторон; новой политики и отдельного -предупреждения-тоста нет. - -### 6.3. Filter-only и постоянная геометрия - -- Первая строка filter-only остаётся прежней: `{db} · {games} по условиям: {list}` / по позиции / - `… · все партии базы` с существующим исправленным разделителем. -- Под источник резервируется **три одинаковые текстовые строки** для обоих источников: (1) база и - состав, (2) место для k, (3) место для player-only. Пустые зарезервированные строки ничего не - рисуют. Поэтому `filter ↔ selection`, k=0/k>0 и наличие игрока не меняют высоту следующего - открытия диалога и не сдвигают его содержимое после открытия. -- Ниже сохраняется существующая зарезервированная зона под «Считаю…»/время/кэш/пропуски. Спиннер и - готовые числа по-прежнему не меняют высоту окна. Предупреждение о нагрузке и кнопки не двигаются. -- N, k и player-scope известны синхронно из снимка при открытии; они не появляются позже вслед за - фоновым подсчётом кэша. «Начать» неактивна только до готовности существующего подсчёта разборов. -- Enter — «Начать» после готовности, Esc — «Отмена». Предложение установить Stockfish 19 и все - существующие условия запуска сохраняются. - -## 7. Snapshot и последующие изменения выделения - -### 7.1. От показанного диалога к запуску — без скрытой подмены - -1. После готовности `view` команда создаёт **черновой снимок**: база/fingerprint, источник, - собственная копия упорядоченных ID, N, k, сортировка и фильтр/player-scope. Для selection - порядок — текущий компаратор таблицы для всех выбранных, включая скрытые, с tie-break по номеру - записи, как в задаче 42. Для filter — существующий порядок `view`. -2. Предстартовый диалог показывает именно этот черновой снимок. Изменения таблицы за открытым - окном не запускают фоновых пересчётов и не меняют его молча. Для нового состава нужны «Отмена» - и повторный вызов; так N/k/оценка никогда не описывают один набор, а «Начать» запускает другой. -3. «Начать» фиксирует **тот же** снимок как snapshot прохода. Повторного чтения живого `marked`, - `view`, сортировки или фильтра в этот момент нет. При немедленном полностью кэшированном итоге - snapshot команды сразу становится snapshot итога. - -### 7.2. Во время прохода - -Последующие Ctrl+щелчок, Ctrl+Space, Ctrl+A, Esc, смена фильтра/позиции/сортировки: - -- меняют только текущую таблицу, рамку курсора и существующий счётчик задачи 42; -- **не** добавляют/удаляют записи, не меняют их порядок, знаменатель прогресса, player-scope, - оценку оставшегося времени по исходной очереди и будущий итог; -- не запускают второй проход и не отменяют исходную запись, снятую из текущего выделения. - -Видимый текст прогресса не расширяется: - -```text -!! Проанализировано {i} из {M} · осталось ≈ {time} [полоса] Остановить -``` - -Здесь M — существующее число анализируемых записей snapshot, включая взятые из кэша и исключая -заранее пропущенные как неподдерживаемые. Поэтому M может быть меньше N/F; существующая строка -«{k} нельзя разобрать» объясняет разницу. Лимит 100 при этом уже проверен по исходным N/F. - -Tooltip прогресса для selection: - -```text -Источник: выбранные {games}; скрыто фильтром при запуске: {k}. -Изменения выделения и фильтра не меняют этот проход. -``` - -При k=0 первое предложение — `Источник: выбранные {games}.` Далее сохраняются существующие полный -прогресс и текущая партия. «Остановить» и красная ошибка используют тот же зафиксированный M. - -После завершения доступность кнопки заново вычисляется по **текущим** N/F. Это не меняет уже -открытый итог старого snapshot. - -## 8. Итог, остановка и повторный запуск из кэша - -- Компоновка существующего итогового окна не меняется. В selection-варианте его weak-подзаголовок: - `{db} · Выбрано: {games}`. Он не содержит F и не называет набор «партиями по условиям». - Tooltip подзаголовка при k>0 добавляет `Скрыто фильтром при запуске: {k}`; отдельной новой - строки и изменения высоты итога нет. -- Следующая существующая строка про игрока остаётся видимой: `Считаются только ходы игрока - «{name}»: белыми {w}, чёрными {b}` либо её вариант одного цвета. Она относится к snapshot, - а не к новому фильтру, выбранному после запуска. -- Заголовки «Итог · разобрано…» / «Поиск остановлен · разобрано…», суммы, список `Партии с !!`, - навигация и кнопки сохраняются. Изменение текущего выделения не переписывает этот итог. -- «Продолжить» получает только `rest` исходного snapshot, исходные порядок/about/player-scope. - Оно допустимо, даже если пользователь уже выделил другие записи или текущее N>100: это явное - продолжение показанного старого прохода, не новый анализ текущего выделения. -- Уже разобранные записи, включая разбор прежними настройками, не пересчитываются. При смешанном - кэше диалог показывает прежние числа «уже разобраны»/«движок разберёт», движок получает только - `left`. Если `left` пуст, предстартовый диалог пропускается и сразу открывается итог; новых - процессов Stockfish быть не должно. -- Повторный вызов после изменения выделения создаёт **новый** snapshot и заново проверяет кэш для - него; он не должен незаметно показать старый итог как итог нового состава. - -## 9. Остальная матрица состояний - -| Состояние | Требование | -|---|---| -| Счётчик кэша в диалоге | Прежний «Считаю, сколько партий уже разобрано…» со спиннером; N/k/player уже видимы, высота не меняется | -| Ошибка движка | Прежний красный текст и `×` в том же правом слоте; разобранное и состав snapshot сохраняются | -| База изменилась | Прежняя остановка и защита record ID; позднее снятие текущего выделения не меняет текст/итог завершённой части | -| F=0, но есть скрытое N≤100 | Команда доступна и запускает N; ранний выход «нет видимых партий» запрещён | -| Все записи пропущены | Существующий итог с причинами; фиктивный запуск движка не нужен | -| Большая база | N и k используют существующие кэшированные счётчики; N≤100 не требует анализа всего F. Числа группируются пробелами | -| Несохранённые изменения | Новых состояний нет: анализ не пишет исходные PGN/ChessBase и не меняет существующие вопросы редактора | -| Узкое окно | Существующие короткая кнопка, сворачивание чипов и truncation tooltip; новых переносов строки условий нет. Отдельный снимок по правилу экономии не нужен | -| HiDPI | Только существующий текст/egui-виджеты; новых растровых ресурсов нет. Логические 22 px и размеры шрифтов неизменны | -| Светлая тема | Цвета не вводятся и не меняются; отдельная визуальная проверка не нужна | - -## 10. Клавиатура, фокус и доступность - -| Клавиша | Поведение | -|---|---| -| Shift+A вне поля ввода и других окон | Тот же resolver источника, что у кнопки; при disabled — тост с той же причиной | -| Tab / Shift+Tab | Существующий порядок: кнопка поиска, «Остановить», затем элементы диалога/итога. Новых focusable-элементов нет | -| Enter в готовом диалоге | «Начать» показанный snapshot | -| Esc в диалоге | «Отмена», без запуска | -| Esc при N≥2 в библиотеке | Как прежде, свести к N=1; **не** обещать filter-only и не останавливать проход | -| Ctrl+Space на последней выделенной записи | Переключить её в N=0; следующий вызов снова использует F | -| Ctrl+A / Shift+диапазон во время прохода | Меняют только следующее текущее выделение, не snapshot идущего прохода | -| Enter / ↑ / ↓ / Esc в итоге | Без изменений | - -Рамка фокуса egui, заливка выбранной строки и отдельная рамка курсора сохраняются. Selection-источник, -скрытые записи, переполнение и player-only объясняются словами, а не только приглушением/цветом. -Тултипы не являются единственным местом критичной информации: N/k/player-only обязательно видны в -предстартовом диалоге. - -## 11. Требования разработчику - -1. **Единый resolver** для кнопки и Shift+A: N>0 → selection, N=0 → filter. Не использовать порог - N≥2 и не делать fallback N>100 → F. При N>0,F=0 не срабатывает ранний return пустой таблицы. -2. **Достоверный k.** Снимок создаётся только по завершённому актуальному `view`; ожидание показано - состоянием §4.1. Нельзя подставлять k=0 по неизвестному значению. k считается по ID записей, не - по видимым номерам строк или сортировке. -3. **Собственный snapshot.** Передать в существующие `StartDialog` → `PassJob` → stopped/summary / - «Продолжить» собственную копию ID, порядка, источника/N/k, fingerprint и player-scope. Живой - `marked`/`view` в фоновом проходе для изменения состава не читать. Черновой снимок диалога и - запускаемый список обязаны совпадать запись в запись. -4. **Player-only без потери скрытых записей.** Для каждого ID selection-snapshot стороны игрока - определяются тем же сопоставлением имени и `Side`, что в действующем фильтре. Нельзя получать их - только пересечением с полным результатом `db.query(filter)`: скрытая по году/Elo/другому условию - выбранная партия всё равно должна получить стороны P. Отсутствие P в записи ведёт к существующему - `player_missing`, а не к исключению записи. Без условия «Игрок» считаются обе стороны. -5. **Переиспользование.** Не дублировать алгоритм разбора, кэш, очередь, окна и индекс отметок. - Существующие `count`, кэш (включая stale), `PassJob`, остановка, atomic-save, ошибки и итог - работают над snapshot из другого источника без второго «массива анализа». -6. **UI.** Не менять ширину `right_slot`, строку 22 px и счётчик/копирование задачи 42. В диалоге - выделить фиксированные три строки источника (§6.3), сохранить существующую зону подсчёта и - предупреждение. В итоге меняется только текст существующего подзаголовка/tooltip. -7. **Тексты.** Добавить новые ключи во все языки существующего `i18n.rs`, не только ru/en; - использовать `i18n::games` и `grouped`. Не менять текст «Снять»/Esc так, будто они дают N=0. -8. **Отладочная проверяемость.** Использовать существующие `CP_SELECT`, `CP_FILTER_PLAYER`, - `CP_SEARCH`, `CP_KEYS`, `CP_BRILLIANT_SLOW`, `CP_BRILLIANT_STOP_AFTER`. Если ими нельзя снять - disabled-tooltip или изменить selection **после** старта, добавить минимальные debug-хуки для - этого и журнал ID/вызовов движка; пользовательских кнопок и системной эмуляции ввода не нужно. - -## 12. Независимому reviewer и tester - -### 12.1. Минимальная визуальная приёмка — только 1920×1080, тёмная тема, русский UI - -Reviewer — не автор этой спецификации и не автор реализации. Запуск только через -`scripts/dev/headless-run.sh`, изолированный профиль. Сравнение с главным экраном и партией — по -существующим реальным `docs/screenshots/library.png`, `game.png`, `review.png` и снимкам QA27/42; -новые размеры, светлая тема и новый снимок партии без найденного дефекта не нужны. - -Достаточно четырёх доказательных состояний; каждый вердикт сопровождается файлом, размером и -состоянием, а не фразой «всё ровно»: - -1. **Библиотека, N=3, k=2, активный игрок P.** Видны выделенные строки/рамка курсора, один счётчик, - одна кнопка в прежнем правом слоте. Зафиксировать y строки условий/верха таблицы и x слота. -2. **Предстартовый диалог того же состояния.** Одновременно читаемы «Выбрано: 3 партии», - «2 скрыто текущим фильтром», player-only, оценка времени, нагрузка и «Начать». После закрытия - раскладка за окном совпадает с кадром 1, сдвиг таблицы **0 px**; внутри диалога появление - готового подсчёта не меняет высоту. -3. **N=101 при F≤100.** Кнопка видна в том же слоте и неактивна; tooltip содержит именно причину - по выделению и не обрезан. Если разрешённым хуком hover снять нельзя, визуальный пункт - пометить «не проверено»; текст отдельно проверить через Shift+A, а не выдать PASS по коду. -4. **Идущий selected-проход после изменения selection/filter.** Видны старый знаменатель прогресса - и уже другой текущий счётчик. Против кадра 1 строка условий остаётся 22 px, верх таблицы — - **0 px**, правый слот — тот же; полоса и «Остановить» не дрожат по x при смене цифр. - -Итог визуально не пересматривать, если изменился только текст существующего подзаголовка: его -состав проверяется функционально. Новый снимок итога нужен только при изменении layout или дефекте. -Любой дефект записывать с местом, ожидаемой/фактической координатой и шагами воспроизведения. - -### 12.2. Функциональный чек-лист tester - -Полный обязательный набор — `docs/research/task-27-selected-games-analysis-2026-11-27.md` §5, -Ф1–Ф11. Особо не потерять: - -- границы 0/1/100/101 для обоих источников и обе конфликтные пары `F>100,N≤100` / `N>100,F≤100`; -- N=1,k=1 при F=0; Esc→N=1 остаётся selection, следующий Ctrl+Space→N=0 возвращает filter-only; -- точное совпадение показанных N/k и журнала запущенных ID, включая порядок скрытых записей; -- изменение selection/filter/sort после «Начать» и после остановки: неизменные проход, итог и - «Продолжить» исходного `rest`; новая выбранная X не вызывается движком; -- кэш: смешанный запуск считает только `left`; повтор всех готовых — ноль новых процессов и - неизменные файлы кэша; старый разбор засчитывается; -- player-only для видимой и скрытой записи, цвета «белыми/чёрными/любым», P отсутствует в записи, - смена P→Q после старта не меняет итог; быстрый поиск имени не включает player-only; -- достоверный k во время пересчёта фильтра: никакого молчаливого k=0; disabled tooltip и тост - Shift+A совпадают; -- ошибка/остановка/закрытие: процессы завершаются по существующему таймауту, готовый кэш читается - после перезапуска, исходные PGN/ChessBase сохраняют sha256/mtime; -- анализ не меняет «Новая база из выбранных»: N=101 запрещает только анализ, копирование задачи 42 - и полные PGN-деревья не затронуты; -- legacy CP1251/CP1252, fullmove=0, старт чёрных, учебный `--`, RAV/комментарии/NAG, повтор - позиции, `[%eval]`, Chess960/нечитаемая запись дают тот же результат, что filter-only. - -## 13. Явно вне объёма - -Новая кнопка или меню выбора источника; объединение фильтра и выделения; отдельная очередь/окно -для selection; новый фильтр `только с !!`; изменение порогов разбора и правил `!!`/`!`; изменение -копирования задачи 42, Esc/«Снять», доски, нотации, колонки `!!`, цветов, исходных PGN и политики -player-only. diff --git a/docs/design/task-27/A-header-1920.png b/docs/design/task-27/A-header-1920.png deleted file mode 100644 index f11bf5d..0000000 Binary files a/docs/design/task-27/A-header-1920.png and /dev/null differ diff --git a/docs/design/task-27/B1-ruy-1920-idle-badges.png b/docs/design/task-27/B1-ruy-1920-idle-badges.png deleted file mode 100644 index 902763e..0000000 Binary files a/docs/design/task-27/B1-ruy-1920-idle-badges.png and /dev/null differ diff --git a/docs/design/task-27/B2-mega4221-1920-disabled.png b/docs/design/task-27/B2-mega4221-1920-disabled.png deleted file mode 100644 index 7f3d3bc..0000000 Binary files a/docs/design/task-27/B2-mega4221-1920-disabled.png and /dev/null differ diff --git a/docs/design/task-27/B3-mega62-1920-running.png b/docs/design/task-27/B3-mega62-1920-running.png deleted file mode 100644 index f2cf008..0000000 Binary files a/docs/design/task-27/B3-mega62-1920-running.png and /dev/null differ diff --git a/docs/design/task-27/B4-mega62-960-running.png b/docs/design/task-27/B4-mega62-960-running.png deleted file mode 100644 index 7ec08f2..0000000 Binary files a/docs/design/task-27/B4-mega62-960-running.png and /dev/null differ diff --git a/docs/design/task-27/B5-mega62-960-idle.png b/docs/design/task-27/B5-mega62-960-idle.png deleted file mode 100644 index ed0d300..0000000 Binary files a/docs/design/task-27/B5-mega62-960-idle.png and /dev/null differ diff --git a/docs/design/task-27/C-filters-footer-1920.png b/docs/design/task-27/C-filters-footer-1920.png deleted file mode 100644 index 89db388..0000000 Binary files a/docs/design/task-27/C-filters-footer-1920.png and /dev/null differ diff --git a/docs/design/task-27/D-dialog-1920.png b/docs/design/task-27/D-dialog-1920.png deleted file mode 100644 index db45fc3..0000000 Binary files a/docs/design/task-27/D-dialog-1920.png and /dev/null differ diff --git a/docs/design/task-27/E1-summary-1920.png b/docs/design/task-27/E1-summary-1920.png deleted file mode 100644 index 1b14285..0000000 Binary files a/docs/design/task-27/E1-summary-1920.png and /dev/null differ diff --git a/docs/design/task-27/E2-summary-960-stopped.png b/docs/design/task-27/E2-summary-960-stopped.png deleted file mode 100644 index 92a1719..0000000 Binary files a/docs/design/task-27/E2-summary-960-stopped.png and /dev/null differ diff --git a/docs/design/tasks-42-43-2026-11-27.md b/docs/design/tasks-42-43-2026-11-27.md deleted file mode 100644 index 9e66779..0000000 --- a/docs/design/tasks-42-43-2026-11-27.md +++ /dev/null @@ -1,503 +0,0 @@ -# Задачи 42 и 43: выделение нескольких партий → новая база; обнаруживаемость стрелок - -Статус: спецификация дизайнера, 2026-11-27, ветка `feature/starter-repertoires`. Код не менялся. -Основа: аудит `docs/research/tasks-42-43-audit-2026-11-27.md`, решения владельца от 2026-11-27, -переданные оркестратором (ниже — «решение владельца»), и снимки текущего HEAD (`3cad881`). - -## 0. Исходные снимки (текущий HEAD, 1920×1080 и 960×600, headless-run, изолированный профиль) - -Профиль `/tmp/opencode/d4243/{cfg,cfg2,data}`, базы — копии `The Ruy Lopez - Move by Move.pgn` -(49, windows-1252), `Alekhin.pgn` (267) и `shapes.pgn` (1 партия со стрелками и кругами). -Каталог снимков: `/tmp/opencode/d4243/s/`. Файл `shapes.pgn` после всех запусков не изменился -(sha256 `242c86e4…5239f`). - -| Снимок | Размер | Что видно и что из этого следует | -|---|---|---| -| `lib-ru.png` | 1920×1080 | Таблица базы без выделения. Под шапкой есть **постоянная строка условий** высотой 22 px: «Условий нет — показаны все партии». Строка есть и без фильтров, поэтому в неё можно поставить счётчик выделения, и таблица не сдвинется. | -| `lib-sel-ru.png` | 1920×1080 | Одна выбранная строка (№ 3) — сплошная заливка `selection.bg_fill` по всей ширине; ✓ «просмотрено» стоит в колонке №. | -| `lib-960-en.png` | 960×600 | Узкое окно: таблица 680 px, строка условий на месте, колонки сокращены до «Year». | -| `chooser-ru.png` | 1920×1080 | Диалог «Добавить в базу»: подзаголовок «Berg, E. — Rudd, J.», список своих баз, «➕ Новая база…», «Сохранить как файл…», «Отмена / Добавить». Пакетный режим строится на этом же диалоге. | -| `newbase-ru.png` | 1920×1080 | Диалог «Новая база»: «Название», «Файл: …/ChessPenguin/», «Изменить папку…», «Отмена / Создать». | -| `game-shapes-ru.png` | 1920×1080 | Партия на ходе 1…e5 с `[%cal Gg1f3,Gf1c4]`: на доске две зелёные стрелки, а в нотации у `e5` **никакого признака** нет. | -| `game-shapes-en.png` | 1920×1080 | Ход 7.Qb3 с двумя красными стрелками: в нотации признака тоже нет. Вариант `7…Qd7 8.Qxb7` с `[%csl Ga8]` тоже без признака. | -| `game-960-en.png` | 960×600 | Узкий экран партии: доска вплотную к панели, свободных полей у доски нет; панель кнопок переносится на вторую строку (так было и раньше). | -| `settings-board-ru.png` | 1920×1080 | «Настройки › Доска и фигуры» — разделы «Набор фигур», «Запись ходов», «Доска»; про стрелки ничего нет. | - ---- - -# Задача 42. Несколько партий → новая база - -## 42.1. Задача экрана (одной фразой) - -В таблице базы пользователь собирает произвольный набор партий и одной командой получает из -них новую базу. Важность информации: какие строки выбраны → сколько их, в том числе невидимых -при текущем фильтре → идёт ли запись и чем она кончилась. - -## 42.2. Путь пользователя и сохранение контекста - -1. Библиотека → база «ruy» → щелчок по № 3, Ctrl+щелчок по № 7 и № 15. В строке условий - справа появляется «Выбрано: 3 · Снять». -2. Правая кнопка по любой выбранной строке → «Новая база из выбранных…» (или Ctrl+Shift+S → - пакетный диалог «Добавить в базу: 3 партии» → «➕ Новая база…»). -3. Диалог «Новая база» с подзаголовком «Из выбранных: 3 партии из «ruy»» → название - «Подборка» → «Создать и скопировать». -4. Запись идёт в фоне. В строке условий на месте счётчика видна строка прогресса - «Запись в «Подборка»: 1 из 3 ▕██░░▏ Отменить». Таблицу можно листать, партии — открывать. -5. Итог — тост «Подборка: скопировано 3, пропущено 0» с кнопкой «Открыть». На полке появляется - карточка «Подборка». **Пользователь остаётся в исходной базе**: фильтры, сортировка, - прокрутка и выделение те же. «Открыть» переключает полку на новую базу. -6. Возврат из партии (Ctrl+W / «← Библиотека») приводит к той же таблице с тем же выделением. - -Исходная база только читается (решение владельца). Файл источника не открывается на запись ни -на каком шаге. - -## 42.3. Компоновка и обоснование - -Новых панелей нет. Добавляются три вещи в уже существующие места. - -``` -┌ шапка базы ──────────────────────────────────────────────────────────────────────────────┐ -│ ruy · PGN, кодировка windows-1252 · 49 партий [🔍 Поиск…] [Фильтры][Доска]│ -├ строка условий (22 px, есть всегда) ─────────────────────────────────────────────────────┤ -│ Условий нет — показаны все партии Выбрано: 3 · Снять │ ← счётчик справа -├──────────────────────────────────────────────────────────────────────────────────────────┤ -│ № ▲ Белые Elo Чёрные Elo Рез. Длина ECO 💬 Турнир Тур Дата │ -│ 1 Carlsen, M. Topalov, V. 1-0 32 C84 … Nanjing 2010 │ -│ 2 McDonald, N. Savage, B. 1-0 55 C84 … British League 2011 │ -│ ✓ 3 Berg, E. Rudd, J. 1-0 30 C78 … Liverpool 2007 │ ← выбрано (заливка) -│ 4 … │ -│ 7 Gashimov, V. Kramnik, V. 1-0 39 C65 … Monaco (rapid) 2011 │ ← выбрано (заливка) -│ … │ -│┌15 Topalov, V. Van der Sterren, P. 1-0 55 C95 … Antwerp 1997┐│ ← выбрано + курсор -│└─────────────────────────────────────────────────────────────────────────────────────────┘│ (заливка + рамка 1 px) -``` - -Во время записи на месте счётчика (та же строка и высота, правый край): - -``` -│ Условий нет — показаны все партии Запись в «Подборка»: 1 240 из 5 000 ▕████░░░░▏ Отменить │ -``` - -Обоснование: - -- **Счётчик в строке условий, справа.** Строка постоянна (22 px, `chips()` в `large_db.rs`, - `set_min_height(22.0)`), значит появление и исчезновение счётчика не сдвигает таблицу. Это - важно на деле, а не для вида: при серии Ctrl+щелчков строка под курсором не должна уехать - на 22 px, иначе следующий щелчок попадёт в соседнюю партию. Шапка не подходит: её вёрстка - измеряется по ширине (`narrow-windows.md §2.4`), новый элемент перенёс бы её на вторую строку - в узком окне. Отдельная нижняя полоса не подходит: она уменьшила бы таблицу скачком. -- Счётчик стоит **правее условий, но левее** «в этом порядке ходов: n из m · только этот порядок» - (он тоже справа, `right_to_left`). Порядок справа налево: [порядок ходов] [выделение] - [условия…]. Условия уже умеют сворачиваться в подсказку, когда места меньше 140 px, поэтому - место под выделение отнимается у них, а не у таблицы. -- **Прогресс записи — в том же месте, что и счётчик.** Пользователь смотрит туда, где только - что был счётчик. Высота строки та же. На время записи счётчик выделения не показывается, - а выделение остаётся и после записи вернётся на место. -- **Команды — только в контекстном меню строки и в пакетном режиме существующего диалога.** - Кнопок в шапке нет (решение владельца: «в существующем диалоге / контекстном меню»). - Отдельной кнопки на полосе выделения тоже нет: «Снять» — единственная ссылка. - -## 42.4. Три состояния строки: выбрана, курсор, наведение - -Это три разных состояния, их нельзя сливать (как в нотации: активная позиция, выбранная строка -и раскрытая ветка). - -| Состояние | Вид | Откуда | -|---|---|---| -| Выбрана | Сплошная заливка `selection.bg_fill`, текст `selection.stroke.color` — **как сейчас у единственной выбранной строки** (`lib-sel-ru.png`) | `row.set_selected(..)` | -| Курсор (фокус клавиатуры, его открывает Enter, F2, «Доска» показывает его) | Рамка 1 px `selection.stroke.color` внутрь строки (`StrokeKind::Inside`), радиус 0. Рамка рисуется **только при N ≥ 2 или когда курсор стоит на невыбранной строке**. При N = 1 вид точно как сейчас | painter по `row.response().rect` | -| Наведение | Как сейчас (`hovered.weak_bg_fill`) | без изменений | - -Курсор отличим без опоры на цвет: рамка — это форма. Тот же приём, что у текущего хода -в вариантах (`move_chip`: заливка и 1 px `selection.stroke`). Ширина рамки не меняет геометрию -строки. - -## 42.5. Мышь - -| Действие | Выделение | Курсор | Якорь (anchor) | -|---|---|---|---| -| Щелчок | только эта строка | эта строка | эта строка | -| Ctrl+щелчок | переключить эту строку (добавить или снять) | эта строка | эта строка | -| Shift+щелчок | **заменить** диапазоном якорь…строка в порядке текущей таблицы | эта строка | не меняется | -| Ctrl+Shift+щелчок | **добавить** диапазон якорь…строка к выделению | эта строка | не меняется | -| Двойной щелчок | первый щелчок уже оставил одну строку; партия открывается (как сейчас) | — | — | -| Правая кнопка по **выбранной** строке при N ≥ 2 | выделение не меняется, открывается **пакетное** меню | эта строка | — | -| Правая кнопка по **невыбранной** строке | только эта строка, обычное меню одной партии | эта строка | эта строка | - -Якорь скрыт фильтром (Shift+щелчок после смены фильтра): якорем становится курсор, если он -виден. Иначе Shift+щелчок работает как обычный щелчок. Выделение протяжкой мыши в минимум -не входит. - -## 42.6. Клавиатура (когда фокус не в поле ввода; `egui_wants_keyboard_input() == false`) - -| Клавиши | Действие | -|---|---| -| ↑ ↓ PgUp PgDn | Курсор двигается (как сейчас, шаг страницы 20). Выделение становится одной строкой курсора, якорь переходит на курсор | -| Home / End | Курсор на первую или последнюю строку таблицы (нового нет, только эта пара клавиш) | -| Shift + ↑ ↓ PgUp PgDn Home End | Курсор двигается; выделение = диапазон якорь…курсор (заменяет) | -| Ctrl + ↑ ↓ | Курсор двигается, выделение не меняется (рамка без заливки) | -| Ctrl+Space | Переключить строку курсора (добавить или снять) | -| Ctrl+A | Выбрать **все строки текущей таблицы** (результат фильтра). В поле ввода Ctrl+A остаётся «выделить текст» | -| Esc | Цепочка (первое подходящее срабатывает и поглощает клавишу): поле ввода (как сейчас) → открытый на узком окне ящик фильтров → **при N ≥ 2 выделение сводится к строке курсора** → «только доска» отдаёт место таблице (`view.escape()`, как сейчас) | -| Enter | Открыть партию курсора (как сейчас) | -| F2 | Данные партии курсора (как сейчас) | -| Ctrl+Shift+S | N ≤ 1 — как сейчас (одна партия); N ≥ 2 — пакетный диалог «Добавить в базу: N партий» | -| Delete | N ≤ 1 — как сейчас; **N ≥ 2 — ничего не удаляется**, тост «Удалять можно по одной партии: снимите выделение (Esc)». Удалить одну строку курсора, когда подсвечено несколько, — опасная неожиданность | - -Подсказки при наведении: у «Снять» — «Снять выделение (Esc)». У счётчика со скрытыми строками — -«Скрытые фильтром партии тоже будут скопированы. Снять выделение — Esc». - -## 42.7. Контекстное меню - -**Одна строка (N ≤ 1):** как сейчас. В конец группы, перед «Отметить как просмотренную», -добавляется «Выделить все (Ctrl+A)» — так пользователь узнаёт, что выделять можно несколько. - -**Пакетное (правая кнопка по выбранной строке при N ≥ 2):** - -``` - Выбрано партий: 3 ← weak, не кнопка - ───────────────────────────── - Новая база из выбранных… - Добавить выбранные в базу… Ctrl+Shift+S - ───────────────────────────── - Выделить все Ctrl+A - Снять выделение Esc -``` - -«Подготовиться к …», «Данные партии», «Отметить», «Удалить» в пакетном меню не показываются: -они относятся к одной партии. Пока идёт запись, оба пункта записи неактивны, подсказка: -«Идёт запись в «Подборка» — дождитесь окончания». Две записи одновременно не запускаются. - -## 42.8. Диалоги - -**Пакетный режим диалога «Добавить в базу»** (тот же `own_db::Chooser`, вид как `chooser-ru.png`): - -- Заголовок «Добавить в базу: 3 партии» (`i18n::games(n)` — правильные формы числа). -- Подзаголовок (weak, одна строка, обрезается многоточием): «из «ruy» · порядок как в таблице: - № ▲». Ключ и направление сортировки — те же, что в заголовке колонки. -- Если часть выбранных скрыта фильтром — вторая weak-строка: «из них 9 сейчас скрыты фильтром». -- Список своих баз: выбор базы и «Добавить» дописывают пакет в эту базу (дубли пропускаются, - §42.10). Решение владельца про дубли («пропускаются со сводкой») имеет смысл именно здесь, - механика та же. **Если оркестратор считает это вне минимума**, строки баз в пакетном режиме - становятся неактивными с подсказкой «Пока только в новую базу» — вёрстка от этого не меняется. -- «➕ Новая база…» → диалог «Новая база» (ниже). «Сохранить как файл…» → тот же фоновый путь - в выбранный пользователем файл. -- При N ≥ 50 000 — weak-строка над кнопками: «Много партий: запись может занять несколько - минут, её можно отменить». -- Кнопка по умолчанию — «Добавить» (если выбрана база), Enter — она, Esc — «Отмена». - -**Диалог «Новая база»** (`newbase-ru.png`), вызванный из пакета: - -- Под заголовком weak-строка «Из выбранных: 3 партии из «ruy»». -- Основная кнопка «Создать и скопировать» вместо «Создать». Остальное без изменений: проверка - имени, «Изменить папку…», `create_new` — существующий файл не перезаписывается, причина отказа - показывается в диалоге, как сейчас. - -## 42.9. Матрица состояний - -| Состояние | Строка условий справа | Таблица | Меню / клавиши | -|---|---|---|---| -| Нет выделения (база только что открыта) | пусто | без заливки | как сейчас | -| N = 1 | **пусто** (счётчик «Выбрано: 1» — шум, одна строка видна и так) | одна заливка, вид как сейчас | как сейчас | -| N ≥ 2, все видны | «Выбрано: 3 · Снять» | заливки, рамка у курсора | пакетное меню | -| N ≥ 2, часть скрыта фильтром | «Выбрано: 12 (9 скрыто фильтром) · Снять» | видимые выбранные залиты | пакетное меню; в диалоге — строка про скрытые | -| Ctrl+A в Mega2026 (11,7 млн) | «Выбрано: 11 741 260 · Снять» | все залиты | диалог с предупреждением «Много партий» | -| Идёт запись | «Запись в «Подборка»: 1 240 из 5 000 ▕██░░▏ Отменить» | работает, выделение можно менять (пакет зафиксирован в момент запуска) | пункты записи неактивны | -| Отмена нажата | «Отмена…» и спиннер 14 px на месте полосы, до остановки потока | — | — | -| Отменено | счётчик выделения возвращается; тост «Копирование отменено: база «Подборка» не создана» (для своей базы — «…«X» не изменена») | — | — | -| Готово | счётчик выделения возвращается; тост «Подборка: скопировано 3, пропущено 1 (дубли)» + «Открыть»; карточка на полке | — | — | -| Часть записей не прочитана | тост «Подборка: скопировано 48, пропущено 2 — дубли 1, не прочитано 1 (№ 40)». Больше 5 номеров — «(№ 40, 41, 77 и ещё 12)» | — | — | -| Ошибка записи (нет места, нет прав, имя занято к концу) | красный текст `error_fg_color` на месте прогресса: «Не удалось записать «Подборка»: нет места на диске. Ничего не записано» + `×`; то же тостом. Подсказка — полный путь и текст ОС | — | — | -| Источник изменился во время записи (fingerprint) | то же, что ошибка: «База «ruy» изменилась во время копирования. Ничего не записано» | выделение снимается (номера записей больше не верны) | — | -| Источник перечитан после внешнего изменения (без записи) | — | выделение снимается, тост «Выделение снято: файл базы изменился» | — | -| Удаление записи в своей базе | — | выделение сводится к курсору (номера сдвигаются) | — | -| Пустая база | строки нет: экран «Нет партий» (как сейчас) | — | — | -| Узкое окно 960×600 | счётчик сокращается до «3 · Снять» (подсказка — полный текст), если меньше 140 px места условиям | рамка курсора видна | — | -| HiDPI (масштаб 2) | рамка 1 логический px = 2 физических; текст не обрезается | — | — | - -Скрытые фильтром строки при Ctrl+A не добавляются: Ctrl+A берёт только текущую таблицу. - -## 42.10. Фильтр, сортировка, порядок, дубли - -- **Сортировка** не меняет набор выбранных; меняется только порядок, в котором они видны. -- **Смена фильтра или позиции поиска не снимает выделение** (решение дизайнера). Причина: - подборку собирают из нескольких поисков (партии Карлсена, потом партии Каруаны). Сбрасывать её - от случайного касания поля дорого. Скрытые строки всегда видны в счётчике («9 скрыто - фильтром») и в диалоге; подсказка счётчика прямо говорит, что их тоже скопируют. Это - отличается от текущего правила для одной строки (`large_db.rs:630-637`: строка, ушедшая из - списка, перестаёт быть выбранной). Для **курсора** текущее правило остаётся: ушедший курсор - сбрасывается, и Enter не открывает невидимую партию. -- Выделение хранится отдельно у каждой базы (как фильтры и сортировка), переживает - переключение баз на полке и возврат из партии. Между запусками программы не сохраняется. -- **Порядок в новой базе — как в таблице** (решение владельца): все выбранные записи, в том - числе скрытые фильтром, сортируются текущим ключом и направлением сортировки таблицы. - Одинаковые значения упорядочиваются по номеру записи. Если все выбранные видны, это в точности - порядок строк на экране. Порядок фиксируется в момент нажатия «Создать и скопировать». -- **Дубли** (решение владельца): пропускаются без вопроса на каждую партию. Это и повторы внутри - выбора, и (для существующей базы) партии, которые в ней уже есть. Признак дубля — тот же, что - у текущей проверки (`store.rs`: игроки, дата, основная линия). В итоге — число пропущенных. - -## 42.11. Большие базы: требования к отзывчивости - -- Выделение — **битовое множество по номеру записи** (`Vec`, `total/64` слов; для Mega - ≈ 1,4 МБ) или `HashSet` при малом N. Отрисовка строки проверяет принадлежность за O(1); - на кадр — только видимые строки (таблица уже виртуальная, `TableBuilder`). -- Ctrl+A по 11,7 млн и Shift-диапазон по большой таблице — один проход по `view` без - перерисовки всех строк. Цель — не дольше одного кадра на 4 221 строке, ≤ 100 мс на 11,7 млн - (порог проверяет разработчик замером). -- Счётчики «выбрано» и «скрыто фильтром» **кэшируются** и пересчитываются только при изменении - выделения или `view`, а не на каждом кадре. -- Запись — отдельный поток: снимок списка записей → чтение (`raw_text` или `load_game().to_pgn()`, - как в `app.rs:1449-1455`) → временный файл рядом с целью → в конце атомарная публикация без - перезаписи (для новой: `hard_link`/`RENAME_NOREPLACE`, отказ при появившемся файле; для своей - базы — `write_atomic` старого содержимого с добавкой). Прогресс — через канал не чаще - 10 раз/с; отмена — `AtomicBool`, проверяется на каждой записи. Отмена или ошибка: временный - файл удаляется, новая база **не создаётся**. Пустая база на полке не остаётся. -- Закрытие окна во время записи: поток отменяется, временный файл удаляется, источник не - тронут. Отдельного вопроса нет: атомарная публикация гарантирует, что половины файла не будет. - -## 42.12. Тексты ru / en - -| Ключ (смысл) | ru | en | -|---|---|---| -| счётчик | Выбрано: {n} | Selected: {n} | -| счётчик со скрытыми | Выбрано: {n} ({k} скрыто фильтром) | Selected: {n} ({k} hidden by the filter) | -| ссылка (сводит выделение к строке курсора, как Esc; ключ `Deselect`, т. к. «Clear» уже переведено «Очистить») | Снять | Deselect | -| подсказка ссылки | Снять выделение (Esc) | Clear the selection (Esc) | -| подсказка счётчика со скрытыми | Скрытые фильтром партии тоже будут скопированы. Снять выделение — Esc | Games hidden by the filter will be copied too. Esc clears the selection | -| меню, заголовок | Выбрано партий: {n} | Games selected: {n} | -| меню | Новая база из выбранных… | New database from selected… | -| меню | Выделить все (Ctrl+A) | Select all (Ctrl+A) | -| меню | Снять выделение (Esc) | Clear selection (Esc) | -| пункт неактивен | Идёт запись в «{name}» — дождитесь окончания | Writing to «{name}» — wait until it finishes | -| диалог «Новая база», скрытые | из них {k} сейчас скрыты фильтром | {k} of them are hidden by the filter now | -| диалог, много | Много партий: запись может занять несколько минут, её можно отменить | Many games: writing may take a few minutes; you can cancel it | -| новая база, подзаголовок | Из выбранных: {games} из «{src}» | From the selection: {games} from «{src}» | -| новая база, кнопка | Создать и скопировать | Create and copy | -| прогресс | Запись в «{name}»: {i} из {n} | Writing to «{name}»: {i} of {n} | -| прогресс, ссылка (общий ключ `Cancel`) | Отмена | Cancel | -| отмена идёт | Отмена… | Cancelling… | -| итог | {name}: скопировано {n}, пропущено {m} | {name}: copied {n}, skipped {m} | -| итог, причины | {name}: скопировано {n}, пропущено {m} — дубли {d}, не прочитано {u} (№ {list}) | {name}: copied {n}, skipped {m} — duplicates {d}, unreadable {u} (No. {list}) | -| итог, кнопка | Открыть | Open | -| отменено, новая | Копирование отменено: база «{name}» не создана | Copying cancelled: «{name}» was not created | -| ошибка | Не удалось записать «{name}»: {reason}. Ничего не записано | Could not write «{name}»: {reason}. Nothing was written | -| источник изменился | База «{src}» изменилась во время копирования. Ничего не записано | «{src}» changed while copying. Nothing was written | -| выделение снято | Выделение снято: файл базы изменился | Selection cleared: the database file changed | -| Delete при N≥2 | Удалять можно по одной партии: снимите выделение (Esc) | Games are deleted one at a time: clear the selection (Esc) | - -Принято при реализации (минимум владельца, 2026-11-27): пакет только в новую базу — пакетного режима -диалога «Добавить в базу», строк «Добавить выбранные…» и «Пока только в новую базу» нет; Ctrl+Shift+S при -N ≥ 2 сразу открывает «Новая база». Ошибка записи — красная строка с `×` на месте прогресса и тост. - -Числа — с группировкой, как в «найдено 4 221 из 11 743 083» (`grouped`). «{games}» — -`i18n::games(n)`. - ---- - -# Задача 43. Как узнать о стрелках и кругах - -## 43.1. Задача (одной фразой) - -Пользователь, который читает или анализирует партию, узнаёт без документации, что правой -кнопкой на доске рисуются стрелки и круги и что они сохраняются. Ходы с такими пометками видны -в нотации. Важность: сам ход → его оценка (NAG) → признак пометок. Признак не спорит с ходом -за внимание. - -## 43.2. Где показывать подсказку и почему не «под доской» - -Владелец просил подсказку «у доски». Снимки показывают, что отдельного места рядом с доской нет: -доска занимает всю высоту (`game-shapes-ru.png`: 60…1072 px), боковые поля есть только в широком -окне, а на 960×600 доска стоит вплотную к панели (`game-960-en.png`). Надпись поверх доски -закрывала бы клетки и мешала бы рисовать. - -**Решение:** информационная полоса **вверху панели нотации**, прямо у правого края доски. Это -тот же компонент, что полоса «Комментарии на другом языке (английский) [Перевести] ×» -(`chooser-ru.png`, `translate_ui.rs:1790-1840`): высота строки, перенос текста, `small_close_button`. -Новый вид не вводится. Текст полосы — обычного цвета, как у полосы перевода, не weak -(ревью 2026-11-27, Д2: weak давал контраст 2,6:1, а подсказку показывают всего три раза). - -``` -┌ панель нотации ─────────────────────────────────────────────┐ -│ Анализ: выкл Движок не выбран ⚙ │ -│ [Нотация] Справочник │ -│ Стрелки и круги: правая кнопка мыши на доске — протяните ×│ ← полоса, обычный текст, -│ или щёлкните. Сохраняются в партии. │ переносится по ширине -│ ┌ Intro ──────────────────────────────────────────────────┐ │ -│ 1 e4 e5 ↗ │ ← признак пометок -│ 2 Nf3 d6 │ -│ 3 d4 ◯ … │ -``` - -## 43.3. Когда показывать и как не надоедать - -| Правило | Значение | -|---|---| -| Где | Только обычный просмотр и анализ партии, где доска интерактивна и фигуры пишутся в партию (`game_view.rs:1441-1447`: нет просмотра линии, Maia, тренировки). В игре, тренировке, подготовке, на досках без ввода — не показывать | -| Когда появляется | При открытии партии, до первой отрисовки нотации (полоса не «въезжает» во время чтения) | -| Просмотр линии движка | Полоса, уже показанная в партии, остаётся на месте приглушённой (высота та же, `×` активен), чтобы нотация не прыгала; впервые в просмотре не появляется (ревью Д1) | -| Одна полоса за раз | Если видна полоса перевода, подсказка в этой партии не показывается (и не засчитывается) | -| Исчезает навсегда | (а) пользователь нарисовал мышью любую стрелку или круг (б) нажал `×`. Признак `settings.hints.board_shapes = done` | -| Исчезает сама | После показа в **3** разных открытиях партии без реакции. Счётчик в настройках; одна партия, открытая повторно в той же сессии, не считается и подсказку сохраняет — в том числе третья засчитанная | -| Закрытие внутри партии | Полоса не исчезает сама во время работы с партией (никаких таймеров): высота панели меняется только от действия пользователя (`×` или рисования). При рисовании полоса пропадает **после отпускания кнопки**, а не во время протяжки | -| Подсказка текста | Цвета и снятие — в подсказке при наведении на текст полосы, не в самом тексте | - -Постоянное место справки (подсказка исчезает, знание должно где-то остаться): в «Настройках › -Доска и фигуры», в разделе «Доска», сразу под его заголовком, перед образцами досок (иначе она ниже видимой части окна, ревью Д3) — одна weak-строка -(`settings-board-ru.png`, по образцу «Только вид на экране. В PGN…»): -«Стрелки и круги — правая кнопка мыши на доске; Shift — красный, Alt — синий, Shift+Alt — -жёлтый. Сохраняются в комментарии хода ([%cal], [%csl])». - -## 43.4. Признак у хода с пометками - -- **Что:** маленький значок, **нарисованный painter'ом**, а не символом шрифта. Причина: - стрелки есть только в моноширинном шрифте egui (`assets.rs:169`), а у глифа другая высота - строки. Painter даёт чёткий значок при любом масштабе. Значок 10×10 логических px: стрелка - (отрезок 1,5 px и треугольный наконечник) — если у хода есть хотя бы одна стрелка; иначе - кружок 1,5 px диаметром 9. Цвет — `weak_text_color()`, на текущем ходе — - `selection.stroke.color` (как текст хода). **Цвет самих стрелок значок не повторяет**: - зелёный и красный спорили бы с цветами NAG (`Qb3!` зелёный, `b5?` оранжевый на `game.png`). -- **Где в таблице основной линии:** сразу после хода и NAG, `x = text_right + 4`, по - вертикальному центру ячейки. Если есть таблетка ошибок `×N` (`notation.rs:319-337`), значок - стоит после неё. Ячейка фиксированной ширины (≤ 160 px, `CELL_MAX`) и высоты (`ROW_H = 26`), - поэтому строка не меняется ни по высоте, ни по положению хода. Самая длинная запись - `Qxb8+!!` с таблеткой и значком помещается в 160 px; проверить на «Фигурках» и русских буквах. -- **В вариантах** (`move_chip` в потоке): значок внутри чипа справа от текста, ширина чипа - +14 px. Поток может перенестись только при добавлении или снятии фигуры, то есть по действию - пользователя. При открытии и переходах по ходам ничего не меняется. -- **Корень (до 1-го хода):** если есть текст начального комментария — значок у правого края - его блока. Если комментарий состоит только из команд — признака нет (ограничение минимума, - на начальной позиции фигуры видны на доске). -- **Подсказка при наведении на ячейку хода** (вместе с существующими): «Стрелки: 2 · круги: 1 - — видны на доске на этом ходу». -- Признак строится по `[%cal]`/`[%csl]` в `comments_after` узла. Разбор кэшируется на версию - партии (после каждого `annotate` — пересчёт), а не повторяется на каждом кадре. -- Стрелки движка признака не дают (они не в PGN). - -## 43.5. Матрица состояний - -| Состояние | Полоса | Признак | -|---|---|---| -| Первое открытие партии | видна | у ходов с пометками | -| Рисование мышью (протяжка) | видна до отпускания, затем исчезает навсегда | появляется у текущего хода сразу после отпускания | -| Повтор фигуры (снятие последней) | — | исчезает | -| Ctrl+Z / Ctrl+Y | — | следует за партией | -| Просмотр линии движка | остаётся приглушённой, высота та же | у ходов партии остаётся; у ходов PV признака нет | -| Игра с Maia, тренировка | нет | нет (фигуры временные) | -| Партия из базы только для чтения | видна (рисовать можно, сохранение — в свою базу по Ctrl+S, как сейчас) | да | -| Видна полоса перевода | нет | да | -| Узкое окно 960×600 | текст в 2–3 строки, `×` в правом верхнем углу полосы | да | -| HiDPI | значок чёткий (painter), линия 1,5 логических px | — | -| Тёмная и светлая тема | weak-цвет темы; на текущем ходе — цвет текста выделения | — | - -## 43.6. Клавиатура - -Новых клавиш нет. Рисование остаётся мышью: правая кнопка, Shift — красный, Alt — синий, -Shift+Alt — жёлтый; Ctrl+Z отменяет. `×` полосы — обычная кнопка (Tab, Enter/Space). -**Риск:** в части окружений Linux Alt+перетаскивание занято оконным менеджером. В -Hyprland и GNOME по умолчанию это Super, но в некоторых сборках Xfce и KDE — Alt. Тестировщик -проверяет в доступных окружениях. Если Alt перехвачен, это ограничение, а не дефект приложения. - -## 43.7. Тексты ru / en - -| Смысл | ru | en | -|---|---|---| -| полоса | Стрелки и круги: правая кнопка мыши на доске — протяните или щёлкните. Сохраняются в партии. | Arrows and circles: drag or click with the right mouse button on the board. They are saved in the game. | -| подсказка полосы | Без клавиши — зелёный, Shift — красный, Alt — синий, Shift+Alt — жёлтый. Та же фигура ещё раз — убрать. Ctrl+Z — отменить. | No key — green, Shift — red, Alt — blue, Shift+Alt — yellow. Draw the same one again to remove it. Ctrl+Z undoes. | -| `×` | Больше не показывать | Don't show again | -| признак | Стрелки: {a} · круги: {c} — видны на доске на этом ходу | Arrows: {a} · circles: {c} — shown on the board at this move | -| настройки | Стрелки и круги — правая кнопка мыши на доске; Shift — красный, Alt — синий, Shift+Alt — жёлтый. Сохраняются в комментарии хода ([%cal], [%csl]). | Arrows and circles: right mouse button on the board; Shift — red, Alt — blue, Shift+Alt — yellow. Saved in the move's comment ([%cal], [%csl]). | - -Если число равно нулю, его часть в подсказке признака опускается («Стрелки: 2 — видны…»). - ---- - -# Требования к реализации (разработчику) - -**42** -1. `LargeView`: `selection` (битовое множество/набор номеров записей), `cursor: Option` - (бывший `selected`), `anchor`. Кэш `selected_count`, `hidden_count`, пересчёт по изменению. - Отрисовка строки: `set_selected(selection.contains(i))`, рамка курсора painter'ом (§42.4). -2. Модификаторы щелчка через `ui.input(|i| i.modifiers)` (`command` = Ctrl на Linux); таблица - и клавиатура по §42.5–42.6; Esc — в цепочку `library.rs:672-683` перед `view.escape()`. -3. Строка условий (`chips()`): справа налево — порядок ходов, затем блок выделения или - прогресса. Условия сворачиваются раньше, высота 22 px не меняется. -4. Меню и пакетный режим `Chooser`/`NewBaseDialog` (§42.7–42.8). Новый `LibraryAction` - с `Vec` в порядке §42.10 (порядок вычисляется при запуске). -5. Фоновое задание по §42.11; итог — тост с кнопкой «Открыть» (по образцу `Toast.undo`); - карточка на полке — только после публикации файла. -6. Delete при N ≥ 2 — тост, не удаление. - -**43** -1. Полоса подсказки — тот же компонент, что полоса перевода; правила §43.3; поля настроек - `hints.board_shapes` (`done`, `shown`). -2. Признак — `paint_move_cell` (после `text_right`, после таблетки ошибок) и `move_chip`; - кэш разбора на версию партии; подсказка при наведении. -3. Строка в «Настройки › Доска и фигуры». -4. Тесты `apply_shape` и протяжки мышью — из аудита (не дизайн, но условие приёмки 43). - -Отладочные хуки для снимков (предложение, чтобы ревьюер и тестировщик смогли снять состояния -без мыши): `CP_SELECT=3,7,15` (выделить записи), `CP_BATCH=new:<имя>` (запустить пакет), -`CP_BATCH_SLOW=1` (искусственная задержка на запись, чтобы снять прогресс), -`CP_HINT_RESET=1` (сбросить подсказку 43). `CP_KEYS` уже умеет Shift/Ctrl+клавиши. - -# Критерии приёмки для дизайн-ревьюера - -Ревьюер — не автор кода. Окна только через `scripts/dev/headless-run.sh`, изолированный профиль. -Каждый пункт подтверждается снимком с размером и состоянием. - -**42** -1. Серия 1920×1080, `ruy`: нет выделения → щелчок № 3 → Ctrl+щелчок № 7 → Ctrl+щелчок № 15 → - Shift+щелчок № 20. Измерить y-координату верха таблицы и строки № 15 на каждом снимке: - **сдвиг 0 px**. Счётчик появляется только начиная с N = 2. -2. Вид при N = 1 совпадает с исходным `lib-sel-ru.png` попиксельно в строке (кроме ✓). -3. Курсор отличим от выбранной строки в тёмной и светлой теме и в оттенках серого (рамка видна). - Курсор на невыбранной строке (Ctrl+↓) — рамка без заливки. -4. Строка условий с фильтром (2–3 чипа) и выделением: чипы сворачиваются, счётчик целиком, - высота строки 22 px; 960×600 — сокращённый счётчик, без переноса шапки. -5. Пакетное меню и пакетный диалог: заголовок, подзаголовок с порядком, строка «скрыто - фильтром»; ширина диалога и кнопки как у `chooser-ru.png`/`newbase-ru.png`. -6. Серия записи (с `CP_BATCH_SLOW`): запуск → 30 % → «Отмена…» → отменено; и запуск → готово - → тост → карточка на полке. На всех снимках высота строки условий и верх таблицы - неизменны; полка меняется только появлением карточки в конце. -7. Ошибка (цель в каталоге без прав): красный текст на месте прогресса, `×`, таблица не - сдвинута. -8. Большая база (Mega2026 или синтетика ≥ 1 млн): Ctrl+A, прокрутка, Shift+End — кадры идут - (`CP_LOG_FRAMES`), счётчик с группировкой разрядов не обрезан. -9. Английский интерфейс: все строки §42.12 помещаются, без обрезки на 1920 и 960. - -**43** -10. Открытие `shapes.pgn` на ходе e5 (1920 и 960): полоса вверху нотации тем же компонентом, - что и полоса перевода (сравнить снимок с полосой перевода: отступы, высота строки, `×`). -11. Признак у `e5`, `d4`, `Qb3`, у `8.Qxb7` в варианте; на текущем ходе (заливка) значок - читается. Позиция SAN в ячейке с признаком и без него одинакова (x отличается на 0 px); - высота строки 26 px. -12. Серия: нарисовать стрелку (протяжка) → отпустить → полоса исчезла, признак появился; сдвиг - нотации ровно на высоту полосы, один раз, после отпускания. -13. Повторное открытие после `×` — полосы нет; четвёртое открытие без реакции — полосы нет. -14. В просмотре линии движка, в игре с Maia и в тренировке полосы нет. -15. HiDPI (если окружение позволяет, иначе пометить «не проверено»): значок и рамка курсора - чёткие. - -# Что передать тестировщику - -- 42: сохранность — источник sha256/mtime до и после (PGN UTF-8, legacy windows-1252, - `.cbv`, Mega2026); порядок в новой базе = порядок таблицы при сортировке по «Белые ▼» и при - скрытых фильтром выбранных; дубли внутри выбора и с существующей базой; отмена на середине — - файла нет, временного файла нет; kill процесса во время записи — частичного файла нет; имя - занято к моменту публикации — существующий файл не тронут; Delete при N ≥ 2 ничего не - удаляет; выделение после внешнего изменения файла снимается; Ctrl+A в поле поиска выделяет - текст, а не партии. -- 43: протяжка правой кнопкой в анализе с работающим движком; Alt-цвет в доступных оконных - менеджерах; полоса не появляется в Maia, тренировке и подготовке; счётчик «3 показа» не растёт - при повторном открытии той же партии в сессии; признак после Ctrl+Z/Ctrl+Y и после - сохранения и повторного открытия. - -# Нерешённое (оркестратору) - -1. Пакет в **существующую** базу — в минимуме или нет (§42.8). Вёрстка готова для обоих - вариантов. -2. Порог «Много партий» (50 000) и порог отзывчивости Ctrl+A — после замера разработчика. -3. Значок для корня без текста — вне минимума. -4. «Убрать все стрелки и круги хода» в меню хода — полезно, но владелец просил только - обнаруживаемость; не включено. diff --git a/docs/design/web-version.md b/docs/design/web-version.md deleted file mode 100644 index de8838e..0000000 --- a/docs/design/web-version.md +++ /dev/null @@ -1,876 +0,0 @@ -# Веб-версия (лёгкая): интерфейс - -Статус: проект дизайнера, 2026-10-30, **не утверждён**. Задача — `docs/dev/tasks.md` §22, подпроект `web/`. - -Обязательные решения владельца — `docs/decisions.md` «Веб-версия (2026-10-30)» и уточнение того же дня (через оркестратора): **под телефон веб-приложение не делаем**; на телефоне вместо приложения — страница-заглушка (§3.6). iPad и компьютер — веб-приложение. - -Опирается на: `docs/research/web-version.md` (аналитик: возможности браузеров, квоты, PWA), `docs/research/web-version-tech.md` (разработчик: прототип в Firefox, Stockfish в wasm, файлы, воркеры), `narrow-windows.md` (компоновка по размеру окна), `android-ui.md` и `android-play.md` (касание, нижняя панель, отчёт, ввод ходов пальцем), `user-comments.md` (Ctrl+1…6), `move-notation.md`, `reference.md`. Снимки: программа в браузере — `target/webresearch/shot2.png`, `shot3.png`, `shot5.png`; компьютер — `website/static/screenshots/04-review-1280.jpg` и др.; телефон — `website/static/screenshots/phone/`. - -Обозначения: **Факт** — проверено по источнику или коду (ссылка в исследованиях). **Проверить** — утверждение по памяти или по вторичному источнику; разработчик проверяет на прототипе до реализации. Размеры — логические точки egui; в браузере 1 точка = 1 CSS-пиксель (eframe ставит `pixels_per_point = devicePixelRatio`), это то же, что dp на Android и pt на iPad. - -## 0. Главное - -1. **Это та же программа.** Веб-версия — настольный интерфейс (egui в ``), а не новый сайт. Кто попробовал в браузере, узнает программу после установки, и наоборот. Отличия — только там, где браузер не даёт иначе: файлы, клавиши, хранение, касание. -2. **Лёгкая версия = попробовать и поработать с партией:** открыть PGN/архив, смотреть, вводить ходы и варианты, комментарии, живой анализ Stockfish 19, разбор с ?!/?/?? и !!/!, отчёт и график, скачать PGN. Нет: полки больших баз, справочника, поиска по позиции, подготовки к сопернику, игры, тренировки, онлайн-партий, других движков, офлайна. -3. **Файлы пользователя только читаются.** Правки партии из файла сохраняются в «Мои партии» (в браузере) или скачиваются. Ничего не пишется в файл на диске — ни в Chrome, ни где-либо ещё. -4. **Всё, что лежит в браузере, честно подписано:** где хранится, сколько занимает, что пропадёт при очистке данных сайта, и всегда рядом «Скачать всё в PGN». -5. **Три среды:** компьютер (мышь), iPad (палец; альбом и портрет), телефон — страница-заглушка с приложением для Android и ответом для iPhone. -6. **Без всплывающих уговоров.** Установку как приложения предлагаем там, где она решает настоящую проблему (iPad: Safari стирает данные), и только в момент, когда это важно. - -## 1. Состав лёгкой версии и как она выглядит - -### 1.1. Карта экранов - -``` - ссылка с сайта /app/ - │ - ▼ - ┌──────────────┐ телефон (§3.6) ─────────────▶ страница «ChessPenguin на телефоне» - │ определение │ └ «Всё равно открыть веб-версию» ─┐ - │ устройства │ компьютер, iPad ──┐ │ - └──────────────┘ ▼ │ - ┌──────────────┐ ◀──────────────────────────────────────┘ - ⚙ Настройки ◀────── │ Библиотека │ ──── «Открыть файл», перетаскивание, «Вставить PGN» - └──────┬───────┘ - │ партия (двойной щелчок / касание) - ▼ - ┌──────────────┐ движок, разбор, отчёт, «Скачать PGN», - │ Партия │ «Сохранить в Мои партии» (Ctrl+S) - └──────────────┘ -``` - -- Экранов два, как на компьютере: **Библиотека** и **Партия**. Переход в партию добавляет запись в историю браузера (`history.pushState`), поэтому кнопка «Назад» браузера, Alt+←, боковая кнопка мыши и жест от левого края в Safari на iPad означают «← Библиотека» — с теми же вопросами о несохранённом, что и кнопка в шапке (§2.6). Из Библиотеки «Назад» уводит со страницы — это обычное поведение браузера, мы его не трогаем. -- Адрес не меняется по партиям (`/app/` всегда): ссылка на партию из чужого файла бессмысленна. Исключение — ссылки на встроенные примеры (§1.3). - -### 1.2. Первый экран: Библиотека при первом входе - -Человек пришёл с сайта по кнопке «Открыть в браузере». Он ещё ничего не открывал. Библиотека — та же, что на компьютере (полка карточек сверху, справа кнопки), только в центре вместо таблицы — приветствие с местом для файла. - -``` -1400 × 860, первый вход -┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ -│ Базы ♟ Новая партия 📋 Вставить PGN ⇩ Установить ⚙ │ -│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ -│ │ ★ Классика │ │ ★ Алехин │ │ ✎ Мои партии │ │ + Открыть файл… │ │ -│ │ 100 партий │ │ 267 партий │ │ пока пусто │ │ PGN, CBV, ZIP, 7Z│ │ -│ └──────────────────┘ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ -├──────────────────────────────────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ -│ Перетащите сюда файл с партиями │ -│ │ │ │ -│ [ Открыть файл… ] PGN · ChessBase CBV · ZIP · 7Z │ -│ │ │ │ -│ Файл только читается и не уходит на сервер: всё работает │ -│ │ в вашем браузере. │ │ -│ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ │ -│ │ -│ Или начните с примера: 100 классических партий › Партии Алехина › Новая партия › │ -│ │ -│ Нужны большие базы, игра с компьютером, подготовка к сопернику? │ -│ Скачайте программу для компьютера ↗ │ -└──────────────────────────────────────────────────────────────────────────────────────────────────┘ -``` - -- **Полка.** Карточки примеров (★ — встроенный, только чтение), «Мои партии» (✎ — хранится в браузере, §2.3), открытые раньше файлы (§2.2), справа отдельно «+ Открыть файл…» — как зона действий в `library-layout.md` §1. Карточки «+ Новая база», «🌐 Онлайн-партии» в лёгкой версии не рисуются (принцип «чего нет — не рисуем»). -- **Приветствие** показывается, пока не выбрана ни одна база (первый вход или все карточки убраны). Дальше Библиотека открывается на последней выбранной базе, как на компьютере. -- **Перетаскивание** работает над всем окном, не только над рамкой: при наведении файла поверх экрана — полупрозрачная заливка `accent` 12 % и надпись «Отпустите, чтобы открыть». Несколько файлов — каждый своей карточкой; первый выбирается. -- **«📋 Вставить PGN»** — как на компьютере: в Chrome/Edge читает буфер по кнопке (браузер спросит разрешение), в Firefox/Safari открывает поле, куда вставляют Ctrl+V / «Вставить» из меню (событие `paste` работает везде без разрешений). Вставленные партии — во временной карточке «Из буфера» до сохранения в «Мои партии». -- **«⇩ Установить»** — только когда браузер может установить приложение (§5); иначе кнопки нет. -- **«Новая партия»** — пустая партия, при сохранении попадает в «Мои партии». -- **Язык** — по `?lang=` из ссылки сайта, иначе выбранный раньше в настройках, иначе первый подходящий из `navigator.languages` среди 9 языков, иначе английский. -- В шапке нет шестерёнки «Обновить программу», «Онлайн-партии», «Подготовка» — их в веб-версии нет. - -**Примеры по ссылке.** Сайт может вести сразу на пример: `/app/?open=classics` (база), `/app/?open=classics&game=3` (партия). Только для встроенных примеров. Это даёт кнопкам сайта «посмотреть разбор Бессмертной» прямой путь. - -**Открытый файл.** После выбора файла — та же таблица партий, что на компьютере (поиск, сортировка, фильтры для небольших баз), `narrow-windows.md` §2. Ограничение лёгкой версии — §2.5. - -### 1.3. Экран партии - -Тот же экран, что на компьютере (`shot3.png`, `04-review-1280.jpg`): шапка, доска с полосой оценки, справа строка движка, вкладки **Нотация | Отчёт**, панель инструментов. Вкладки «Справочник» в лёгкой версии нет (ему нужна полка баз; открытый вопрос 3). - -``` -1400 × 860, мышь -┌──────────────────────────────────────────────────────────────────────────────────────────────┐ -│ ← Библиотека │ Андерсен, Адольф — Дюфрен, Жан 1-0 ⇩ Скачать PGN ▾ ⚙ │ -│ │ Классика · № 3 · Берлин 1852 · C52 │ -├───────────────────────────────────────────────────────┬──────────────────────────────────────┤ -│ ▌┌────────────────────────────────────────────────┐ │ Анализ: вкл +1.9 гл.24 · Stockfish ⚙│ -│ ▌│ │ │ 19.Rad1 Qxf3 20.Rxe7+ … │ -│ ▌│ ДОСКА │ ├──────────────────────────────────────┤ -│ ▌│ │ │ Нотация [Отчёт] │ -│ ▌│ │ │ ○ Андерсен !! 1 ! 4 ?? 1 85 %│ -│ ▌└────────────────────────────────────────────────┘ │ ● Дюфрен !! 0 ! 2 ?? 3 73 %│ -│ ▁▂▃▅▆▇ график оценки (когда есть разбор) ▇▆▅▃▂▁ │ … │ -│ │ ⏮ ◀ ▶ ⏭ │ 🔃 ↩ ↪ │ ☰ 💾 │ 📈 │ -└───────────────────────────────────────────────────────┴──────────────────────────────────────┘ -``` - -Отличия от настольной версии: - -| Где | На компьютере | В вебе | -|---|---|---| -| Шапка справа | «🔍 Найти в базе ▾», «⚙» | **«⇩ Скачать PGN ▾»** (меню: «Эту партию (.pgn)», «Всю базу с моими правками (.pgn)» — §2.4), «⚙». «Найти в базе» нет | -| 💾 / Ctrl+S | сохранить в базу партии или в выбранную | **«Сохранить в Мои партии»** (§2.4); для партии из «Моих партий» — сохранить в неё | -| Разбор 📈 | запуск сразу, оценка времени в подсказке | мышь — так же; касание — короткий лист с оценкой времени и «Анализировать» (подсказок у пальца нет), как Android §21.2 | -| Движок ⚙ | выбор движка, потоки, память | только «Линий» (1–5) и «Время на позицию»; потоки и память — автоматически (§1.5) | -| «Записать анализ в партию» | меняет партию в базе | меняет партию в памяти → это правка, её сохраняют в «Мои партии» или скачивают | - -- **Разбор с !!/!** — те же правила и тот же поиск (1 млн узлов, 1 поток, Hash 32): **Факт** — оценки Stockfish 19 wasm побитово совпадают с нативными (`web-version-tech.md` §2.2), поэтому отметки и точность те же, что в программе и на Android. Отчёт (вкладка «Отчёт»), график под доской, значки !!/! на доске, переход к ходам — как на компьютере. -- **Параллельность разбора** — воркеры с отдельным движком в каждом: компьютер — по `navigator.hardwareConcurrency`, не больше 8; iPad — не больше 3 (память ≈ 130 МБ на воркер, **проверить** на iPad); оценка времени — по скорости прошлого разбора на этом устройстве. -- **Вкладка в фоне.** Живой анализ останавливается, когда вкладка скрыта (`visibilitychange`), и сам продолжается при возврате (кнопка остаётся включённой) — экономия батареи и честность: браузер всё равно тормозит фоновые вкладки. Разбор на компьютере продолжается в фоне; на iPad Safari его приостанавливает — при возврате он продолжается с недостающих позиций (посчитанное в кэше). Пока идёт разбор, заголовок вкладки браузера: «Анализ 23/80 · ChessPenguin». -- **Уход со страницы** (закрыть вкладку, F5, ввести адрес) при несохранённых правках или идущем разборе — стандартный вопрос браузера «Покинуть сайт?» (`beforeunload`; свой текст браузеры не показывают — **факт** общеизвестный). Внутри программы (← Библиотека, «Назад» браузера) — наш вопрос, §2.6. - -### 1.4. Движок: скачивание один раз - -Движок — 78 МБ (brotli; **факт**, `web-version-tech.md` §2.1) — не грузится вместе с программой. Первое нажатие «Анализ» (L) или 📈 открывает окно: - -``` -┌ Движок Stockfish 19 ──────────────────────────────┐ -│ Оценивает позицию, показывает лучшие ходы и │ -│ разбирает партию. Скачивается один раз и хранится │ -│ в этом браузере. │ -│ │ -│ Размер: 78 МБ · свободно для сайта: 9,6 ГБ │ -│ │ -│ [Не сейчас] [Скачать] │ -└───────────────────────────────────────────────────┘ -``` - -- Ход загрузки — полоса в том же окне «Скачано 23 из 78 МБ» и «Отменить»; окно можно закрыть — загрузка идёт, на кнопке «Анализ» кольцо прогресса. Готово → движок сразу включается (или стартует разбор, если звали его). -- Ошибки — тексты Android §8.4 (нет сети, оборвалось, не хватает места, файл повреждён), с проверкой SHA-256. -- Сохраняется в Cache API/OPFS, виден в «Данных в браузере» (§2.3) с кнопкой «Удалить». -- Пока движок не скачан, строка движка: «Анализ: выкл · Stockfish не скачан». -- Облегчённая сеть (1,1 МБ, другие оценки) в лёгкой версии **не используется**: разбор на ней дал бы другие отметки, а два движка с разными оценками в одной программе путают (открытый вопрос 5). - -### 1.5. Настройки (минимум) - -Окно настроек как на компьютере (`shot5.png`), вкладки: - -| Вкладка | Что есть | Чего нет (по сравнению с компьютером) | -|---|---|---| -| **Доска и фигуры** | доска, набор фигур (часть наборов: по 4–6 лучших, остальные — открытый вопрос 6), координаты, запись ходов (`move-notation.md`) | — | -| **Движок** | Линий 1–5, Время на позицию (10 с, 20 с, 1 мин, без ограничения), «Stockfish 19 · скачан · 78 МБ [Удалить]» | список движков, «Выбрать файл движка…», потоки, память | -| **Интерфейс** | язык (9), тема (как в системе / светлая / тёмная), звук вкл/выкл, **«Крупные кнопки для пальца: Авто / Вкл / Выкл»** (§3.1) | перевод комментариев (ChatGPT) | -| **Данные в браузере** | §2.3 | — | -| **О программе** | версия, «Установить как приложение» (§5), лицензии (ChessPenguin GPL-3.0-or-later, Stockfish GPL-3.0, шрифты, фигуры), «Исходный код этой версии ↗», «Программа для компьютера ↗», «Сайт ↗» | проверка обновлений (веб-версия обновляется сама при следующем открытии) | - -Потоки живого анализа — автоматически: компьютер — половина `hardwareConcurrency`, не больше 8; iPad — 2. Многопоточный движок требует COOP/COEP (решение владельца: ставим на `/app/`); если страница всё же не изолирована, работает однопоточный, без сообщений пользователю. - -## 2. Файлы и хранение - -### 2.1. Две полки — два правила - -| Что | Где лежит | Можно ли потерять | -|---|---|---| -| **Ваши файлы** (PGN, CBV, ZIP, 7Z) | на диске; программа только читает | нет: программа их не меняет | -| **Копия файла в браузере** (по желанию, §2.2) | хранилище сайта (OPFS) | да, при очистке данных сайта; оригинал на диске цел | -| **Мои партии** — новые партии, правленые копии, партии с записанным разбором | хранилище сайта | да — поэтому «Скачать всё в PGN» | -| Разборы партий (кэш), отметки «просмотрено», настройки, движок | хранилище сайта | да; разборы пересчитываются, движок скачивается снова | - -### 2.2. Открытые файлы: только чтение, с диска - -**Chrome / Edge** (File System Access API, **факт**: `web-version.md` §3.1). «Открыть файл…» вызывает `showOpenFilePicker`; программа хранит ссылку на файл (в IndexedDB). В следующий раз карточка на полке: - -``` -┌──────────────────────┐ ┌──────────────────────┐ -│ 🗄 Alekhin.pgn │ │ 🗄 Alekhin.pgn │ -│ 267 партий │ → │ 267 партий │ -│ 🔒 Разрешить чтение │ щелчок│ │ -└──────────────────────┘ └──────────────────────┘ -``` - -- Пока разрешения нет, на карточке строка «🔒 Разрешить чтение» (цвет `accent`). Щелчок по карточке → `requestPermission()` → браузер сам спрашивает «Разрешить ChessPenguin просматривать Alekhin.pgn?». В Chrome 122+ там есть «Разрешать всегда» (**проверить**) — тогда строки больше не будет. -- Отказ → карточка остаётся с той же строкой; снизу на 4 с: «Без разрешения браузер не даёт прочитать файл». -- Файл изменился на диске → читается заново (как на компьютере, по размеру и времени). -- Файл удалён или перемещён → «Файл не найден на диске. [Выбрать снова] [Убрать с полки]». - -**Firefox / Safari** (API нет — **факт**). Файл выбирается через ``; ссылку сохранить нельзя. Программа помнит **имя, размер и отпечаток** (SHA-256 первых 1 МБ + размер), чтобы вернуть отметки «просмотрено» и кэш разборов. После перезагрузки: - -``` -┌──────────────────────┐ -│ 🗄 Alekhin.pgn │ -│ 267 партий │ -│ ↻ Выбрать файл снова │ -└──────────────────────┘ -``` - -- Щелчок → системный выбор файла (подсказка в нём, где он был, браузеры не дают). Выбран тот же файл (отпечаток совпал) — открывается как был. Другой файл с тем же именем — открывается как новый, старая карточка заменяется, без вопросов. -- Под полкой один раз за сеанс, слабым текстом: «Этот браузер не запоминает файлы: после перезагрузки выберите файл снова или оставьте копию в браузере.» - -**«Оставить копию в браузере»** — пункт меню карточки файла (во всех браузерах; в Chrome/Edge полезен мало, но не прячем — одинаково везде). Окно: - -``` -┌ Оставить копию в браузере ────────────────────────┐ -│ Alekhin.pgn · 2,7 МБ │ -│ │ -│ Копия откроется сразу, без выбора файла. Она │ -│ хранится в этом браузере на этом устройстве и │ -│ пропадёт, если очистить данные сайта. Файл на │ -│ диске не меняется. │ -│ │ -│ Занято сайтом: 96 МБ · свободно: 9,6 ГБ │ -│ │ -│ [Отмена] [Оставить копию] │ -└───────────────────────────────────────────────────┘ -``` - -- Место — из `navigator.storage.estimate()`: «свободно» = `quota − usage` (это квота сайта, а не свободное место диска; так и называем — «свободно для сайта» в настройках). -- **Не помещается** (`размер × 1,1 > свободно`): кнопка «Оставить копию» неактивна, вместо описания места: «Не помещается: копии нужно 1,2 ГБ, а браузер даёт сайту ещё 900 МБ. Освободите место в «Данных в браузере» или открывайте файл с диска.» Если квота неизвестна — пробуем записать; при ошибке записи — тот же текст без чисел и копия удаляется целиком (половины копии не бывает). -- Карточка с копией: значок ⧉ и строка «копия в браузере». Меню: «Удалить копию» (файл на диске не трогается). -- Копия **не обновляется** сама, если файл на диске изменился (браузер не видит диск). Меню: «Обновить копию из файла…» (выбор файла). - -### 2.3. «Мои партии» и «Данные в браузере» - -**«Мои партии»** — одна своя база в браузере (PGN в OPFS), карточка на полке всегда (пустая — «пока пусто»). Что туда попадает: - -- новая партия при сохранении (Ctrl+S / 💾); -- партия из файла или примера, которую поправили и сохранили (копия; тег `Source` с именем файла — **предложение**, чтобы видно было, откуда); -- партия с записанным разбором («Записать анализ в партию» + сохранить); -- в полной версии — сыгранные с движком (место готово, в лёгкой их нет). - -Меню карточки и шапка таблицы «Моих партий»: **«Скачать всё в PGN»** (`ChessPenguin-my-games-2026-10-30.pgn`), удаление партии (Delete, с отменой Ctrl+Z, как на компьютере), «Очистить всё…» (подтверждение с числом партий; перед этим — кнопка «Сначала скачать»). На карточке вторая строка: «12 партий · скачано 3 дня назад» или «12 партий · ещё не скачаны» (цвет `warn`, если есть партии, не скачанные больше 14 дней, — без окон и уговоров). - -**Постоянное хранение.** При **первом** сохранении в «Мои партии» или первой копии файла программа вызывает `navigator.storage.persist()` (это действие пользователя — Firefox покажет свой вопрос; Chromium и Safari решают сами, **факт**: `web-version.md` §3.2). Перед вопросом Firefox — строка в окне сохранения: «Браузер спросит, можно ли хранить данные постоянно, — разрешите, чтобы партии не пропали при нехватке места.» - -**Настройки → «Данные в браузере»:** - -``` -Данные в этом браузере -Всё ниже хранится только здесь, на этом устройстве. Файлы на диске не меняются. - -Занято 96 МБ · свободно для сайта 9,6 ГБ -Постоянное хранение: ✓ включено (или ⚠ не разрешено браузером) - - Мои партии · 12 партий 340 КБ [Скачать всё в PGN] - Копии файлов · 2 16 МБ [Удалить…] - Движок Stockfish 19 78 МБ [Удалить] - Разборы партий · 31 1,2 МБ [Очистить] - Запомненные файлы, отметки, настройки 40 КБ - -Если очистить данные сайта в браузере, всё это пропадёт. -Скачайте свои партии в PGN, чтобы не потерять их. -``` - -- В Safari (не установленном, §5) — ещё строка `warn`: «Safari удаляет данные сайта, если не открывать его 7 дней. Установите ChessPenguin на экран «Домой» или скачивайте партии.» (**факт** про 7 дней — WebKit 2020, на 2026 **проверить**). -- Числа — из `estimate()` и размеров файлов в OPFS; «Удалить…» у копий открывает список с размерами. - -### 2.4. Сохранение и скачивание - -| Действие | Что делает | -|---|---| -| **Ctrl+S / 💾 «Сохранить в Мои партии»** | Партия из «Моих партий» — сохраняется в неё же. Любая другая (пример, файл, буфер, новая) — копия в «Мои партии»; после этого открытая партия — уже эта копия (шапка: «Мои партии · № 13»), дальнейшие Ctrl+S пишут в неё. Подтверждение внизу на 4 с: «Сохранено в «Мои партии» · Скачать PGN». | -| **⇩ «Скачать PGN» → «Эту партию»** | Скачивание `Anderssen-Dufresne-1852.pgn` (имена латиницей из тегов, иначе `game.pgn`; как Android §7.8). С правками, сохранёнными или нет. | -| **⇩ → «Всю базу с моими правками»** | Только если в этой базе есть правленые, но не сохранённые в «Мои партии» партии, или это «Мои партии». Скачивается новый файл `Alekhin (ChessPenguin).pgn` — оригинал на диске не трогается. | -| Скачать «Мои партии» | §2.3 | - -Скачанный файл уходит туда, куда браузер кладёт загрузки (Chrome может спросить место — это его настройка). Запись **в исходный файл** даже в Chrome не делаем — решение владельца «базы только для чтения». - -### 2.5. Что открывается, что нет - -| Файл | Лёгкая версия | -|---|---| -| `.pgn` (любая кодировка, FEN, `--`), `.cbv`, `.zip`/`.7z` с PGN или CBV | да; замечания совместимости — как на компьютере | -| Папка ChessBase `.cbh` + `.cbg/.cba/…` | выбрать **все файлы базы сразу** (множественный выбор) или перетащить папку; если выбран один `.cbh`: «Это часть базы ChessBase из нескольких файлов. Выберите все её файлы сразу (Ctrl+A в папке) или откройте архив .cbv.» (**предложение**; разработчик подтверждает, что `open_chessbase_files` укладывается в лёгкую) | -| Большие базы | предел по размеру файла и числу партий (ставит разработчик по замеру памяти; ориентир — 200 МБ / 200 000 партий на компьютере, вдвое меньше на iPad). Сверх предела: «Эта база слишком большая для веб-версии (1,9 ГБ). Откройте её в программе для компьютера — там нет такого предела. [Скачать программу ↗]» | - -### 2.6. Несохранённые правки - -- «← Библиотека», «Назад» браузера, переход к другой партии: тот же вопрос, что на компьютере, но с веб-ответами: «Сохранить изменения в партии? [Сохранить в Мои партии] [Не сохранять] [Отмена]». -- Esc дважды — уйти без сохранения (как на компьютере). -- Закрытие вкладки / перезагрузка — только вопрос браузера (§1.3). **Черновик** несохранённой партии пишется в хранилище раз в 5 с (одна запись, последняя партия); при следующем открытии вверху Библиотеки: «Есть несохранённая партия: Андерсен — Дюфрен, 14 ходов. [Открыть] [Удалить]». Это защита от случайно закрытой вкладки, а не автосохранение в «Мои партии». - -### 2.7. При очистке данных сайта - -Пропадает всё из таблицы §2.1, кроме файлов на диске: «Мои партии», копии, разборы, движок, настройки, список открытых файлов и разрешения. Программа после этого выглядит как при первом входе (§1.2) — отличить очистку от первого входа нельзя, и не нужно. Предупреждение заранее — в «Данных в браузере» (§2.3) и на карточке «Моих партий» (дата последнего скачивания). - -## 3. Раскладки: компьютер, iPad, телефон - -### 3.1. Два независимых признака - -1. **Ввод: мышь или палец.** «Крупные кнопки для пальца» = Авто → включены, если основной указатель грубый: `matchMedia('(pointer: coarse)')`. iPad с клавиатурой и трекпадом остаётся «пальцем» (основной указатель у него — палец, **проверить** в Safari); ноутбук с сенсорным экраном — «мышь». Настройка Вкл/Выкл перекрывает Авто. -2. **Компоновка: по размеру окна**, как `narrow-windows.md` §0: рядом / стопкой — чистая функция `W`, `H`, без гистерезиса. Для «пальца» меняются только константы. - -| Константа | Мышь (как на компьютере) | Палец | -|---|---|---| -| Высота кнопки, строки списка | как сейчас (≈ 24–28) | **44** (Apple HIG), основные ◀ ▶ — 48 × 72 | -| `SIDE_MIN` правой колонки | 240 | **320** | -| `STACK_BOTTOM_MIN` | 300 | **380** (строка движка 48 + вкладки 44 + 4 строки нотации по 44 + панель 64 + поля) | -| Строка нотации | как сейчас | 40 (ход — вся ячейка; в тексте вариантов — ближайший ход в радиусе 22) | -| Доска в стопке | `narrow-windows.md` §3.1 | не выше **60 % высоты** окна (как Android §13.2) | -| Панель инструментов | одна строка мелких значков | нижняя панель кнопок 64 (§3.3) | - -### 3.2. Компьютер - -Ровно настольная программа с правилами `narrow-windows.md`: Библиотека (полка, таблица, фильтры рядом или выдвижные), партия рядом или стопкой. Отличия — только §1–2 и клавиши (§4). Масштаб — масштабом браузера (Ctrl + / Ctrl −): egui сам следует `devicePixelRatio`; собственный масштаб egui по Ctrl+=/− в вебе выключен, чтобы не было двух масштабов. - -**Узкое окно в вебе.** Окно браузера бывает уже 640 (минимум настольной программы). Ниже 640 — стопка с доской во всю ширину, панели переносятся по группам (§4a там же). Ниже **360** по ширине или 420 по высоте — вместо экрана спокойная надпись по центру: «Окно слишком маленькое. Растяните его, чтобы работать с партией.» (Партия и анализ при этом живут, просто не рисуются.) - -### 3.3. iPad: альбом - -Размеры iPad (CSS px): mini 744 × 1133, iPad/Air 820 × 1180, Pro 11" 834 × 1194, Pro 13" 1024 × 1366 (**проверить** по актуальным моделям). В Safari во вкладке высоту съедают адресная строка и вкладки (≈ 70–110), в установленном приложении — только строка состояния (24). - -``` -iPad 1180 × 800 (установленное приложение), палец -┌───────────────────────────────────────────────────────────────────────────────────────────┐ -│ ‹ Библиотека Андерсен — Дюфрен 1-0 · Берлин 1852 ⇩ ☰ ⚙ │ 52 -├─┬────────────────────────────────────────────────────┬────────────────────────────────────┤ -│▌│ │ ● Дюфрен, Жан 0 │ 40 -│▌│ ├────────────────────────────────────┤ -│▌│ │ [Анализ ●] +1.9 гл.24 19.Rad1 … ▾ │ 48 -│▌│ ├────────────────────────────────────┤ -│▌│ ДОСКА │ ?? Зевок · лучше было 19…Qxf3 Отчёт│ 44 -│▌│ ≈ 700 × 700 │ ▁▂▃▅▆▇▇▆▅▃▂▁ график │ 40 -│▌│ ├────────────────────────────────────┤ -│▌│ │ 17 Bxh7+ Kxh7 │ 40 -│▌│ │ 18 ▓Qh5+▓ Kg8 │ -│▌│ │ … │ -│▌│ ├────────────────────────────────────┤ -│▌│ │ ○ Андерсен, Адольф 1 │ 40 -│ │ ├────────────────────────────────────┤ -│ │ │ ↩ 🔃 ⏮ ◀ ▶ ⏭ │ 64 -└─┴────────────────────────────────────────────────────┴────────────────────────────────────┘ -``` - -- **Это компоновка «рядом»** с константами «пальца»: доска = меньшее из высоты и `W − 320 − 26 − 24`; правая колонка ≥ 320. -- **Плашки игроков** (как Android §7.11, §13.1) — первой и последней строкой правой колонки, а не над и под доской: доска не теряет 80 точек высоты. В режиме «мышь» плашек нет — имена в шапке, как на компьютере. -- **Вкладки Нотация | Отчёт** — сегментом 44 над нотацией, когда есть разбор; без разбора — просто нотация. -- **Нижняя панель** (64): ↩ отменить (неактивна, если нечего), 🔃 перевернуть, ⏮ ◀ ▶ ⏭; ◀ ▶ — по 72, удержание повторяет (400 мс, затем каждые 120 мс — Android §7.4). Панель — у правого нижнего края, под большим пальцем правой руки. ↪ повтор — в меню ☰ (на касании редок). -- **☰ (меню партии)**: Анализ партии / Отчёт, Сохранить в Мои партии, Данные партии (F2), Копировать PGN, Копировать FEN, Вставить вариант, Скачать PGN, Повторить (↪), Замечания совместимости. -- **Строка «Дальше»** на развилке (Android §7.5) — над нижней панелью, чипы 44: на касании Shift+↑/↓ нет, а ходы в тексте вариантов мелкие. - -### 3.4. iPad: портрет и разделённый экран - -``` -iPad 820 × 1180, палец -┌────────────────────────────────────────────────────┐ -│ ‹ Библиотека Андерсен — Дюфрен 1-0 ⇩ ☰ ⚙ │ 52 -├────────────────────────────────────────────────────┤ -│ ● Дюфрен, Жан 0 │ 40 -│ ▌┌──────────────────────────────────────┐ │ -│ ▌│ │ │ -│ ▌│ ДОСКА ≈ 700 │ │ ≤ 60 % высоты -│ ▌│ │ │ -│ ▌└──────────────────────────────────────┘ │ -│ ○ Андерсен, Адольф 1 │ 40 -├════════════════════ разделитель ═══════════════════┤ -│ [Анализ ●] +1.9 гл.24 19.Rad1 Qxf3 … ▾ │ 48 -│ ?? Зевок · лучше было 19…Qxf3 Отчёт │ 44 (+ график 40) -│ 17 Bxh7+ Kxh7 │ -│ 18 ▓Qh5+▓ Kg8 │ нотация -├────────────────────────────────────────────────────┤ -│ Дальше: [19.Rad1] (19.Qxf7+) │ 44 на развилке -│ ↩ 🔃 ⏮ ◀ ▶ ⏭ │ 64 -└────────────────────────────────────────────────────┘ -``` - -- **Стопка** с константами «пальца»: плашки над и под доской шириной с доску (Android §13.2), доска ≤ 60 % высоты, разделитель тянется. Бюджет 1180: 24 + 52 + 40 + 700 + 40 + 48 + 64 = 968, нотации ≈ 210 (5 строк); с панелью разбора ≈ 125. -- **Поворот** iPad переключает альбом ↔ портрет без потери состояния (`narrow-windows.md` §3.3: состояние в `GameView`). -- **Split View / Slide Over** (окно 320–700 шириной): та же стопка; плашки, ⇩ и ⚙ уходят в ☰ при ширине < 500; ниже 360 — надпись «Окно слишком маленькое» (§3.2). Это не телефонная раскладка — мы только не ломаемся. -- **Библиотека на iPad**: полка компактной строкой (`narrow-windows.md` §2.5), строки таблицы 44, фильтры — выдвижная панель; двойного щелчка у пальца нет — партия открывается **одним касанием** строки (выделение и открытие сразу). Сортировка — касанием заголовка. - -### 3.5. Жесты (палец) - -| Где | Жест | Действие | -|---|---|---| -| доска | касание фигуры, затем поля; перетаскивание | ход (Android `android-play.md` §29.2–29.3: точки ходов, фигура под пальцем поднята на полклетки; превращение — как на компьютере, **проверить** окно выбора под палец) | -| доска | — | **листания ходов свайпом нет**: свайп по доске спорит с перетаскиванием фигуры, а у левого края в Safari — с жестом «назад» (Android §7.2, то же правило) | -| ◀ ▶ | касание; удержание | шаг; повтор | -| график оценки | касание, протяжка | перейти к ходу — это и есть «листание пальцем»: протяжка по графику пробегает партию | -| нотация | касание хода; прокрутка | перейти; читать | -| нотация | **долгое нажатие** на ход | контекстное меню хода (то, что на компьютере правой кнопкой): комментарий, знаки ! ? !! ?? !? ?!, сделать основным, удалить ход и продолжение | -| линия движка | касание | предпросмотр (◀ ▶ листают линию, ✕ выходит; «+ Вариантом» — вставка с отменой) | -| левый край экрана (Safari) | свайп вправо | «Назад» браузера = ← Библиотека (§1.1) | -| везде | щипок | ничего: масштаб страницы на холсте выключен (`touch-action: none`); на компьютере масштаб — браузером | - -- **Стрелки и цветные поля пальцем не рисуются** (как на Android — решение владельца по `android-play.md` §29.1); с трекпадом или мышью на iPad правая кнопка работает как на компьютере. -- **Комментарий** — поле ввода с экранной клавиатурой iPad. egui в браузере принимает текст через скрытое поле ввода; **проверить** на iPad набор по-русски, автозамену и диктовку до реализации — это главный риск касания (открытый вопрос 7). - -### 3.6. Телефон: страница-заглушка вместо приложения - -**Решение владельца:** веб-приложение под телефон не делаем. Телефон, открывший `/app/` (по ссылке с сайта, из сообщения, по закладке), видит не программу, а страницу «ChessPenguin на телефоне». Программа (5–7 МБ) при этом **не скачивается**. - -#### 3.6.1. Как отличить телефон от планшета и компьютера - -Решение — в маленьком скрипте в самой странице `/app/` **до** загрузки wasm. На сервере по `User-Agent` этого не решить: iPad и iPhone в режиме «Полная версия сайта» выдают себя за Mac, размер экрана сервер не видит. - -```js -// Общая функция для сайта и /app/ — один файл static/js/device.js (сейчас detect() живёт в site.js). -function deviceClass() { - var ua = navigator.userAgent || ""; - var plat = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || ""; - var touch = navigator.maxTouchPoints > 0; - var short = Math.min(screen.width, screen.height); // CSS px, весь экран, не окно - var coarse = matchMedia("(pointer: coarse)").matches; - var finePresent = matchMedia("(any-pointer: fine)").matches; - - var ios = /iPhone|iPod|iPad/.test(ua) || (/Mac/.test(plat) && navigator.maxTouchPoints > 1); - if (ios) return short < 600 ? "iphone" : "ipad"; - if (/Android/i.test(ua)) return short < 600 ? "android-phone" : "android-tablet"; - if (navigator.userAgentData && navigator.userAgentData.mobile) return short < 600 ? "phone" : "tablet"; - if (/CrOS/.test(ua)) return "computer"; - if (touch && coarse && !finePresent && short < 600) return "phone"; // «версия для ПК» на телефоне и прочее - return "computer"; -} -``` - -Почему так: - -- **iPadOS выдаёт себя за Mac** (UA `Macintosh`), а настоящий Mac не имеет `maxTouchPoints > 1` — признак `Mac + касание` (**факт**: так уже работает `site.js`, `touchMac`). Но iPhone с включённой «Запросить настольный веб-сайт» тоже выглядит `Mac + касание` — поэтому iPhone и iPad дальше различаются **размером экрана**. -- **Порог 600 по короткой стороне экрана.** Самый широкий iPhone — 440 (16 Pro Max), самый маленький iPad — 744 (mini); телефоны Android — 360–480; Galaxy Fold в сложенном виде — телефон, в разложенном (≈ 670+) — планшет, и это верно: на развёрнутом экране программа помещается. 600 — граница «компактного» класса окна у Google (Material 3), её же использует Android-дизайн (`android-ui.md` §13). (Размеры моделей — **проверить** по актуальным спецификациям.) -- **`screen`, а не размер окна:** iPad в Split View/Slide Over (окно 320) — всё равно iPad, а узкое окно браузера на компьютере — всё равно компьютер. `min()` убирает зависимость от поворота (Android отдаёт `screen` в текущей ориентации, iOS — в портретной). -- **Android-планшет** (UA без `Mobile` или Chrome в режиме «версия для ПК», который на больших планшетах включён по умолчанию — **проверить**) получает веб-программу: она для такого экрана сделана; в «О программе» и на первом экране — строка «Есть приложение для Android ↗». -- **Ошибки неизбежны** (необычные устройства, увеличенный масштаб экрана Android, будущие складные) — поэтому есть «Всё равно открыть» (§3.6.4), а не тупик. -- Без JavaScript — `