Compare commits
No commits in common. "main" and "v1.9.2" have entirely different histories.
518 changed files with 4187 additions and 94622 deletions
|
|
@ -2,8 +2,3 @@
|
||||||
# without the Visual C++ Redistributable (VCRUNTIME140.dll).
|
# without the Visual C++ Redistributable (VCRUNTIME140.dll).
|
||||||
[target.x86_64-pc-windows-msvc]
|
[target.x86_64-pc-windows-msvc]
|
||||||
rustflags = ["-C", "target-feature=+crt-static"]
|
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\""]
|
|
||||||
|
|
|
||||||
2
.github/workflows/ci.yml
vendored
2
.github/workflows/ci.yml
vendored
|
|
@ -66,7 +66,7 @@ jobs:
|
||||||
|
|
||||||
# Apple Silicon: the build and the app bundle (decision 15).
|
# Apple Silicon: the build and the app bundle (decision 15).
|
||||||
macos-build:
|
macos-build:
|
||||||
runs-on: macos-15
|
runs-on: macos-14
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v7
|
- uses: actions/checkout@v7
|
||||||
- uses: dtolnay/rust-toolchain@stable
|
- uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
|
||||||
52
.github/workflows/release-notes.yml
vendored
52
.github/workflows/release-notes.yml
vendored
|
|
@ -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
|
|
||||||
10
.github/workflows/release.yml
vendored
10
.github/workflows/release.yml
vendored
|
|
@ -114,7 +114,7 @@ jobs:
|
||||||
needs: version
|
needs: version
|
||||||
# Apple Silicon (arm64). Not signed by Apple yet: the first start goes through
|
# Apple Silicon (arm64). Not signed by Apple yet: the first start goes through
|
||||||
# "Open" in the context menu (decision 15).
|
# "Open" in the context menu (decision 15).
|
||||||
runs-on: macos-15
|
runs-on: macos-14
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.version.outputs.version }}
|
VERSION: ${{ needs.version.outputs.version }}
|
||||||
steps:
|
steps:
|
||||||
|
|
@ -169,11 +169,6 @@ jobs:
|
||||||
with:
|
with:
|
||||||
name: android
|
name: android
|
||||||
path: androidApp/dist/*.apk
|
path: androidApp/dist/*.apk
|
||||||
# The RuStore build: uploaded to the store by hand, not a file of the release.
|
|
||||||
- uses: actions/upload-artifact@v7
|
|
||||||
with:
|
|
||||||
name: rustore
|
|
||||||
path: androidApp/dist-rustore/*.apk
|
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
needs: [version, linux, flatpak, windows, macos, android]
|
needs: [version, linux, flatpak, windows, macos, android]
|
||||||
|
|
@ -185,9 +180,6 @@ jobs:
|
||||||
with:
|
with:
|
||||||
path: dist
|
path: dist
|
||||||
merge-multiple: true
|
merge-multiple: true
|
||||||
# The RuStore build stays an artifact of the run (merge-multiple brought it here).
|
|
||||||
- name: Not the store's build
|
|
||||||
run: rm -f dist/*-rustore.apk
|
|
||||||
- name: Stockfish source (GPL-3.0 source offer for the engine bundled in the Flatpak and Android)
|
- name: Stockfish source (GPL-3.0 source offer for the engine bundled in the Flatpak and Android)
|
||||||
run: packaging/stockfish.sh source dist
|
run: packaging/stockfish.sh source dist
|
||||||
- name: Checksums
|
- name: Checksums
|
||||||
|
|
|
||||||
2
.github/workflows/rodent-iv.yml
vendored
2
.github/workflows/rodent-iv.yml
vendored
|
|
@ -30,7 +30,7 @@ jobs:
|
||||||
name: rodent-iv-linux-x86_64
|
name: rodent-iv-linux-x86_64
|
||||||
- os: windows-latest
|
- os: windows-latest
|
||||||
name: rodent-iv-windows-x86_64.exe
|
name: rodent-iv-windows-x86_64.exe
|
||||||
- os: macos-15
|
- os: macos-14
|
||||||
name: rodent-iv-macos-arm64
|
name: rodent-iv-macos-arm64
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
|
|
|
||||||
6
.gitignore
vendored
6
.gitignore
vendored
|
|
@ -10,9 +10,3 @@
|
||||||
|
|
||||||
# A local run of the website from the repository root (website/README.md runs it from server/).
|
# A local run of the website from the repository root (website/README.md runs it from server/).
|
||||||
/data-dev/
|
/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/
|
|
||||||
|
|
|
||||||
|
|
@ -4,19 +4,10 @@ mode: subagent
|
||||||
color: "#33A68C"
|
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, усечённые записи, повтор позиции, старт чёрных.
|
|
||||||
|
|
||||||
Сценарии мысли сквозными: импорт → просмотр → редактирование → экспорт → повторное открытие; внешнее изменение файла; отмена долгой операции; авария посреди записи. Вопросы задавай только там, где ответ меняет решение, и приводи варианты с последствиями.
|
|
||||||
|
|
||||||
Отчёт (обязательный формат): выводы с пометками факт/гипотеза/предложение · изменённые файлы · открытые вопросы · что нужно от других ролей.
|
|
||||||
|
|
|
||||||
|
|
@ -4,26 +4,16 @@ mode: subagent
|
||||||
color: "#BD7AD8"
|
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. Задача экрана и приоритет информации — одной фразой, до макета.
|
Доска и чтение аннотированной партии — центр продукта. Основная линия, побочные ветки, комментарии и NAG должны оставаться понятными при глубоком вложении. Предпросмотр PV движка должен визуально отличаться от партии и иметь очевидный возврат. Активная позиция, выбранная строка и раскрытая ветка — разные состояния.
|
||||||
2. Пользовательский путь и сохранение контекста (библиотека ⇄ партия, возврат из предпросмотра).
|
|
||||||
3. Компоновка: доска, нотация, варианты, комментарии, анализ; обоснуй размещение каждого элемента.
|
|
||||||
4. Конкретика: компоненты, плотность, типографика, цвета, отступы, состояния. Без декора ради декора: никаких бесполезных карточек, градиентов и dashboard-стилистики.
|
|
||||||
5. Матрица состояний: пустое, загрузка, ошибка, переполнение, несохранённые изменения, узкое окно, HiDPI, большие базы.
|
|
||||||
6. Клавиатура: полная карта клавиш и фокуса, tooltip, видимая активная позиция, читаемость без опоры только на цвет.
|
|
||||||
|
|
||||||
Независимая визуальная приёмка после реализации:
|
Учитывай нативные ограничения выбранного Rust UI: перенос rich text, hit testing ходов, виртуализация таблиц, clipboard, диалоги, звук, SVG, IME. Предлагай проверяемый UI-прототип для сомнительных возможностей. Код приложения меняй только по прямому назначению оркестратора. Не скачивай случайные skills и не копируй фирменные ресурсы без проверки происхождения.
|
||||||
|
|
||||||
- Ревьюер — отдельный агент, не автор макета или кода изменения. Он обязан запустить приложение в изолированных настройках и посмотреть реальные снимки, а не оценивать вёрстку только по коду.
|
|
||||||
- Обязательны сравнение с главным экраном и экраном партии, широкое и узкое окно, пустые и заполненные состояния, HiDPI в доступном окружении. Проверять типографику, отступы, выравнивание, одинаковые размеры кнопок и строк, читаемость выделения.
|
|
||||||
- Отдельно проверять последовательность состояний: выбор строки, запуск, завершение, возврат, появление статистики и фоновых сообщений. Размеры блоков не должны скачком меняться без явного действия пользователя; любое изменение высоты фиксировать на серии снимков.
|
|
||||||
- Вердикт подтверждать ссылками на снимки, размером и состоянием каждого. Общее «всё ровно» без визуальных доказательств не считается приёмкой. Дефекты записывать конкретно: место, ожидаемое/фактическое выравнивание, шаги воспроизведения.
|
|
||||||
|
|
||||||
Центр продукта — доска и чтение аннотированной партии: основная линия, ветки, комментарии и NAG остаются понятными при глубоком вложении; предпросмотр PV движка визуально отличим от партии и имеет очевидный выход. Активная позиция, выбранная строка и раскрытая ветка — три разных состояния, не сливать их.
|
|
||||||
|
|
||||||
Ограничения egui проверяй по документации и исходникам (перенос rich text, hit testing ходов, виртуализация таблиц, clipboard, диалоги, звук, SVG, IME). Сомнительную возможность не утверждай — предложи проверяемый UI-прототип. Код меняешь только по прямому назначению оркестратора; чужие фирменные ресурсы без проверки происхождения не копируешь.
|
|
||||||
|
|
||||||
Отчёт: решения с обоснованием · макеты и состояния · требования к реализации для разработчика · что передать тестировщику.
|
|
||||||
|
|
|
||||||
|
|
@ -4,25 +4,12 @@ mode: subagent
|
||||||
color: "#E5AC57"
|
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 с сохранением исходного текста для неизменённых игр.
|
||||||
|
|
||||||
- Сначала читай существующий код области и следуй его идиомам: стиль файла важнее личных предпочтений. Без абстракций «на вырост» и без комментариев-извинений — код и история говорят сами.
|
UCI реализуй как явную машину состояний, с отдельным процессом, асинхронным чтением stdout/stderr, контролем stop/bestmove, таймаутами, MultiPV, типизированными опциями и привязкой результатов к поиску. Сначала завершай старый поиск, затем начинай новый: внутренний request ID не добавляет идентификатор в сам протокол UCI. Не вызывай движок через shell-строку. Завершай процессы при закрытии документа и приложения.
|
||||||
- `unwrap`/`expect`/`panic` на пользовательских данных и границах ввода запрещены: `Result` на границах, ошибки типизированные (thiserror), с понятным текстом для пользователя.
|
|
||||||
- Зависимость добавляешь только после проверки версии и лицензии и убедившись, что существующие зависимости нужду не покрывают; фиксируешь по стилю workspace.
|
|
||||||
|
|
||||||
Предметные инварианты (нарушать нельзя):
|
Отделяй индекс библиотеки от исходного PGN; учитывай изменение файла, отмену импорта, пагинацию и атомарную запись. Не читай большую базу целиком в UI-потоке. Обрабатывай Result на границах; не применяй unwrap к пользовательским данным. Избегай абстракций ради гипотетических функций.
|
||||||
|
|
||||||
- Шахматная модель и PGN независимы от UI. Дерево документа — стабильные NodeId, один шаг Undo на операцию. Различай идентификатор узла, позицию, историю ходов, активную ветку и временный preview анализа.
|
Проверяй доступные API по документации и исходникам, фиксируй версии и лицензии зависимостей. Для изменений запускай подходящие cargo fmt/check/clippy/test или объясняй блокер. Добавляй значимые тесты на ошибки данных и конкурентность. Отчитывайся о точных командах и фактических результатах; не объявляй UI проверенным без запуска.
|
||||||
- Исходные байты PGN/ChessBase сохраняются; roundtrip — семантический, с диагностикой; побайтовую идентичность после редактирования не обещаем.
|
|
||||||
- UCI — только через крейт `uci`: сначала завершить старый поиск (bestmove, затем readyok), потом начинать новый; таймауты, MultiPV, типизированные опции, движок не через shell-строку, процессы завершать при закрытии документа и приложения.
|
|
||||||
- Тяжёлая работа не в UI-потоке: фоновые потоки, прогресс, отмена, наружу — события.
|
|
||||||
|
|
||||||
Ворота качества — обязательны, с фактическим выводом в отчёте:
|
|
||||||
|
|
||||||
- `cargo fmt`, `cargo clippy` без предупреждений в тронутых крейтах, `cargo test -p <crate>` зелёные. Сломать существующий тест нельзя; падающий до тебя тест фиксируешь и сообщаешь, чужое молча не «чинишь».
|
|
||||||
- Поведенческие изменения — с тестами: ошибки данных, отмена, конкурентность, roundtrip. UI проверенным объявляешь только после реального запуска (dev-хуки `CP_*`, снимок), не «на глаз» по коду.
|
|
||||||
- Замеры производительности с методикой и оборудованием; цели не выдаёшь за результаты.
|
|
||||||
|
|
||||||
Отчёт: изменённые файлы · команды проверки и их итог (скопированный вывод) · принятые решения и почему · непроверенное · вопросы.
|
|
||||||
|
|
|
||||||
|
|
@ -4,14 +4,10 @@ mode: primary
|
||||||
color: "#5B8DEF"
|
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. Определи ближайший проверяемый результат и назови его пользователю до начала работы.
|
Делегируй независимые задачи агентам analyst, designer, developer и tester. Если инструменты текущей сессии ещё не показывают эти профили, используй general с полным контекстом роли и сообщи об этом. Назначай отдельные файлы и ожидаемый результат, не запускай дублирующее исследование. Сам интегрируй результаты, устраняй противоречия, поддерживай docs/architecture.md. Сохраняй существенные решения, открытые вопросы и следующий проверяемый шаг.
|
||||||
2. Делегируй независимые части агентам analyst, designer, developer, tester: каждой — отдельные файлы без пересечений, в задании — цель, известные пути и факты, ожидаемый артефакт. Не дублируй их исследования своими и не делай их работу за них. После UI-реализации отдельно назначай дизайн-ревьюера, который не писал эту реализацию: обязательны реальные скриншоты, сравнение с основными экранами и проверка отсутствия скачков между состояниями.
|
|
||||||
3. Интегрируй только проверенное: утверждение агента принимай как гипотезу, пока не увидел доказательства (команда, её вывод, файл:строка). Ключевое и спорное перепроверяй сам.
|
|
||||||
4. Закрывая задачу, обновляй `docs/dev/tasks.md`, при существенных решениях — `docs/decisions.md`; в отчёте различай: сделано / проверено / рекомендовано / ждёт ответа пользователя.
|
|
||||||
5. Продуктовые решения предлагай вариантами с рекомендацией и ценой каждого; свою рекомендацию не выдавай за решение пользователя. Объём без согласования не расширяй.
|
|
||||||
|
|
||||||
Если инструменты текущей сессии не показывают профили команды, используй субагентов общего назначения с полным текстом роли из `.opencode/agents/<роль>.md` и скажи об этом пользователю. Активный сервис (OpenCode, Kimi Code) самостоятельно не перезапускай.
|
Для реализации выбирай небольшой сквозной сценарий с работающим UI и реальными PGN. Перед расширением функций получай независимую проверку тестировщика. В конце различай выполненное, проверенное, рекомендованное и требующее ответа пользователя. Не перезапускай активный OpenCode самостоятельно.
|
||||||
|
|
|
||||||
|
|
@ -4,16 +4,12 @@ mode: subagent
|
||||||
color: "#E87575"
|
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, отсутствие readyok, некорректные строки, MultiPV, мат и завершение процесса. Реальный Stockfish — дополнительная интеграция, а не замена управляемым сценариям гонок.
|
||||||
- UCI: детерминированный fake engine, воспроизводящий задержки, устаревший `info` после `bestmove`, отсутствие `readyok`, мусорные строки, MultiPV, мат и завершение процесса. Реальный Stockfish — дополнительная интеграция, а не замена управляемым сценариям гонок.
|
|
||||||
- UI и сценарии: переход библиотека—партия—библиотека, клавиатура и фокус, предпросмотр PV без изменения документа, отмена операций, экспорт, восстановление после аварии; Wayland/X11 и HiDPI в доступном окружении.
|
|
||||||
|
|
||||||
Оформление дефекта — строго: серьёзность · окружение и версия · шаги · ожидаемое и фактическое поведение · файл/строка · минимальный пример воспроизведения. Не воспроизвёл — не репортишь: пишешь «не подтвердилось» с перечнем проверок. Производительность: фиксируешь оборудование, размер входа, методику и измерения; цели не называешь результатами.
|
Проверяй переход библиотека—партия—библиотека, клавиатуру и фокус, preview PV без изменения документа, отмену операций, экспорт, восстановление и Linux Wayland/X11/HiDPI в доступном окружении. Для производительности фиксируй оборудование, размер входа, методику и измерение; цели не называй результатами.
|
||||||
|
|
||||||
Границы: production-код без задания не исправляешь; неподтверждённые бинарники не запускаешь; пользовательские PGN и базы не изменяешь — работаешь на копиях; внешние тестовые библиотеки не публикуешь без выяснения условий распространения.
|
Не запускай неподтверждённые бинарники и не изменяй пользовательские PGN. Не исправляй production-код в ревью без задания. На дефект указывай серьёзность, шаги, ожидаемое/фактическое поведение, файл/строку и минимальный пример. Явно перечисляй непроверенное. Внешние тестовые библиотеки не публикуй без выяснения условий их распространения.
|
||||||
|
|
||||||
Отчёт: проверено (чем и каким сценарием) · дефекты (по формату) · не подтвердилось · непроверенное — явным списком · оценка рисков остатка.
|
|
||||||
|
|
|
||||||
20
AGENTS.md
20
AGENTS.md
|
|
@ -5,27 +5,21 @@
|
||||||
- Исходное ТЗ: `техническое задание.txt`.
|
- Исходное ТЗ: `техническое задание.txt`.
|
||||||
- Пользовательские материалы: `designExample/`, `pgnFilesforExample/`, `engines/`.
|
- Пользовательские материалы: `designExample/`, `pgnFilesforExample/`, `engines/`.
|
||||||
- Рабочий язык обсуждений и проектных заметок — русский; идентификаторы кода — английский.
|
- Рабочий язык обсуждений и проектных заметок — русский; идентификаторы кода — английский.
|
||||||
- Текущий этап: развитие выпускаемого продукта (релиз 2.5.2). Задачи и бэклог — `docs/dev/tasks.md`.
|
- Текущий этап: исследование и согласование архитектуры. Рекомендация не равна утверждённому решению.
|
||||||
- Архитектура реализованной системы: `docs/architecture.md`; архитектурное предложение этапа исследования — `docs/research/architecture-proposal-2026-10-17.md`; исследования: `docs/research/`.
|
- Сводка решений: `docs/architecture.md`; исследования: `docs/research/`.
|
||||||
- Журнал решений: `docs/decisions.md`; подтверждённые пользователем решения имеют приоритет над предложениями исследований.
|
- Подтверждённые пользователем границы первой версии: `docs/decisions.md`; они имеют приоритет над ранними предложениями исследований.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
Оркестратор распределяет независимые задачи между `analyst`, `designer`, `developer`, `tester`, согласует результаты и обсуждает продуктовые решения с пользователем. Делегирование разрешено. Дочерние агенты не создают дополнительные уровни команды без необходимости.
|
Оркестратор распределяет независимые задачи между `analyst`, `designer`, `developer`, `tester`, согласует результаты и обсуждает продуктовые решения с пользователем. Делегирование разрешено. Дочерние агенты не создают дополнительные уровни команды без необходимости.
|
||||||
|
|
||||||
- Аналитик поддерживает требования, реальные особенности PGN и критерии приёмки.
|
- Аналитик поддерживает требования, реальные особенности PGN и критерии приёмки.
|
||||||
- Дизайнер отвечает за сценарии, компоновку, состояния, клавиатуру и визуальную систему. После UI-реализации отдельный дизайн-ревьюер, не автор реализации, проверяет её на реальных снимках приложения: сравнение с главным экраном и экраном партии, выравнивание, размеры и состояния, отсутствие скачков при переходах и появлении данных. Одного чтения кода и тестов для визуальной приёмки недостаточно.
|
- Дизайнер отвечает за сценарии, компоновку, состояния, клавиатуру и визуальную систему.
|
||||||
- Разработчик отвечает за Rust, архитектуру, хранение, PGN и UCI.
|
- Разработчик отвечает за 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 как форматом обмена.
|
- Локальное приложение для просмотра, ввода и анализа шахматных партий, с PGN как форматом обмена.
|
||||||
|
|
@ -40,8 +34,4 @@
|
||||||
|
|
||||||
## Работа
|
## Работа
|
||||||
|
|
||||||
Окна приложения для тестов и снимков запускать только через `scripts/dev/headless-run.sh -- ENV=… команда` (невидимый монитор Hyprland 1920×1080, без фокуса и курсора владельца); прямой запуск окна на мониторах владельца запрещён. Не запускать и не подменять службы сессии владельца (AT-SPI, D-Bus, порталы, ydotool и т. п.) для эмуляции ввода; нужное действие — через отладочный хук приложения.
|
Не изменять исходное ТЗ и референсы. Не запускать незавершённые загрузки движков. Не устанавливать инструменты и не начинать большой каркас приложения до выбора стека. Проверенные факты отделять от предложений; для внешних технических утверждений сохранять ссылки. Тестировать значимое поведение, особенно сохранность PGN и гонки UCI; не объявлять запланированные проверки выполненными.
|
||||||
|
|
||||||
Экономия (владелец, 2026-11-27): визуальная проверка — одно разрешение 1920×1080 и основная (тёмная) тема; светлая — только если меняются цвета. Минимум снимков: только те, что доказывают критерий; не снимать серии и другие разрешения без нужды, не держать несколько агентов на проверке одного и того же.
|
|
||||||
|
|
||||||
Не изменять исходное ТЗ и референсы. Не запускать неподтверждённые бинарники и незавершённые загрузки движков. Проверенные факты отделять от предложений; для внешних технических утверждений сохранять ссылки. Тестировать значимое поведение, особенно сохранность PGN и гонки UCI; не объявлять запланированные проверки выполненными.
|
|
||||||
|
|
|
||||||
233
CHANGELOG.md
233
CHANGELOG.md
|
|
@ -4,239 +4,6 @@ All notable changes are listed here. Versions follow [Semantic Versioning](https
|
||||||
|
|
||||||
## [Unreleased]
|
## [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
|
|
||||||
own: at the start of the program and when one comes back to it after ten minutes or
|
|
||||||
more, one database after another, on the desktop and on Android. Only new games are
|
|
||||||
told («+N»); no message when there are none or the network is off.
|
|
||||||
- Desktop: the notation no longer jumps on every move with the engine on. Between two
|
|
||||||
positions the old lines go at once and the new ones come a frame later; the engine
|
|
||||||
panel now keeps their room, so what is below it stays still.
|
|
||||||
- The moves of the notation and the signs after them are bold (Ubuntu Bold on the desktop,
|
|
||||||
the bold system font on Android), and so are the marks in the circles on the board. In
|
|
||||||
Russian the report's rows read «Блестящий» and «Замечательный».
|
|
||||||
- Android: the dark theme by default (it was the system's); a theme chosen before stays.
|
|
||||||
Android is told the app's own theme, so the window and the splash screen before the
|
|
||||||
app draws match it (no white flash before a dark app on a light phone).
|
|
||||||
- Game review marks brilliant moves (!!, a sound piece sacrifice) and great moves (!, the
|
|
||||||
only good move that turns the game), next to inaccuracies, mistakes and blunders: in the
|
|
||||||
report, the notation, the graph and on the board; written to the game as $3 and $1. The
|
|
||||||
engine searches a second time for the moves that could be such (about a third longer
|
|
||||||
analysis); for an analysis from before, «Update» looks for them without evaluating the
|
|
||||||
game again. With evaluations from the PGN alone there are none (the report says so).
|
|
||||||
Calibrated on chess.com's marks of the Evergreen game: a sacrifice is a piece the move
|
|
||||||
itself gives up, every move of a combination is marked, and a piece saving itself on
|
|
||||||
the only good square or the only good move in an equal position is great too.
|
|
||||||
The first rules stay in the code beside these (to compare them and go back). In
|
|
||||||
Russian ! is now «Замечательный ход».
|
|
||||||
- The review's mark in the notation stands right after the move, the move in its color
|
|
||||||
(Qg7?? in red), as on Lichess, instead of a colored pill at the edge of the cell; the
|
|
||||||
author's own sign, when there is one, stands instead.
|
|
||||||
- Desktop, a game against the computer: the draw offer is «½–½» on its button («Offer a
|
|
||||||
draw» in its tooltip), so that the game's buttons fit in a narrow panel.
|
|
||||||
- Move marks in the owner's palette (as on chess.com): !! #26C2A3, ! #81B64C, ?! Lichess
|
|
||||||
blue #56B4E9, ? #FFA459, ?? #FA412D, on the board, in the notation, the report and the graph,
|
|
||||||
on the desktop and Android; as text in the light theme darkened to stay readable. The
|
|
||||||
accuracy numbers follow the same colors (green, blue, orange, red).
|
|
||||||
- Android: the board shows the move's mark in the corner of its square, as on the desktop:
|
|
||||||
the review's ?!, ?, ??, !, !! or the author's own sign.
|
|
||||||
|
|
||||||
## [1.9.4] — 2026-10-27
|
|
||||||
|
|
||||||
- Desktop: the database cards show how many games each holds instead of «not loaded»:
|
|
||||||
the databases are counted in the background, one after another, and the counts are
|
|
||||||
remembered for the next start (a changed file is counted again).
|
|
||||||
- Desktop, the play dialog: the strength rides above the slider's handle, where the eye
|
|
||||||
is while it moves.
|
|
||||||
- Translation of annotations is faster: ChatGPT is asked to think little (translating
|
|
||||||
needs no long thought), and a long game goes in three requests at once instead of one
|
|
||||||
after another.
|
|
||||||
- Desktop, a game against the computer: the buttons under the clocks are of one height;
|
|
||||||
the moves and the board flip on one row, the game's own actions on the next.
|
|
||||||
|
|
||||||
## [1.9.3] — 2026-10-27
|
|
||||||
|
|
||||||
- Android: «About» no longer calls the app an alpha, says what it does now (chess
|
|
||||||
databases, game analysis, play against the computer) and shows the penguin in a crown,
|
|
||||||
as the app's icon does; the empty list of databases shows it too.
|
|
||||||
|
|
||||||
## [1.9.2] — 2026-10-27
|
## [1.9.2] — 2026-10-27
|
||||||
|
|
||||||
- Desktop, a game against the computer: the header shows its time control («5+3», «∞»)
|
- Desktop, a game against the computer: the header shows its time control («5+3», «∞»)
|
||||||
|
|
|
||||||
151
Cargo.lock
generated
151
Cargo.lock
generated
|
|
@ -716,12 +716,6 @@ dependencies = [
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cast"
|
|
||||||
version = "0.3.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cc"
|
name = "cc"
|
||||||
version = "1.8.0"
|
version = "1.8.0"
|
||||||
|
|
@ -774,18 +768,17 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chess-core"
|
name = "chess-core"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
"pgn-reader",
|
"pgn-reader",
|
||||||
"serde",
|
|
||||||
"shakmaty",
|
"shakmaty",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chess-import"
|
name = "chess-import"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
|
|
@ -796,24 +789,14 @@ dependencies = [
|
||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "chess-openings"
|
|
||||||
version = "2.5.2"
|
|
||||||
dependencies = [
|
|
||||||
"chess-import",
|
|
||||||
"serde",
|
|
||||||
"shakmaty",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chesspenguin"
|
name = "chesspenguin"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"arboard",
|
"arboard",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"chess-import",
|
"chess-import",
|
||||||
"chess-openings",
|
|
||||||
"chrono",
|
"chrono",
|
||||||
"directories",
|
"directories",
|
||||||
"eframe",
|
"eframe",
|
||||||
|
|
@ -824,12 +807,10 @@ dependencies = [
|
||||||
"game-review",
|
"game-review",
|
||||||
"getrandom 0.3.4",
|
"getrandom 0.3.4",
|
||||||
"image",
|
"image",
|
||||||
"js-sys",
|
|
||||||
"log",
|
"log",
|
||||||
"maia",
|
"maia",
|
||||||
"online-games",
|
"online-games",
|
||||||
"play",
|
"play",
|
||||||
"prep",
|
|
||||||
"releases",
|
"releases",
|
||||||
"rfd",
|
"rfd",
|
||||||
"rodio",
|
"rodio",
|
||||||
|
|
@ -840,31 +821,14 @@ dependencies = [
|
||||||
"skrifa",
|
"skrifa",
|
||||||
"sys-locale",
|
"sys-locale",
|
||||||
"tar",
|
"tar",
|
||||||
"thiserror 2.0.21",
|
|
||||||
"trainer",
|
"trainer",
|
||||||
"uci",
|
"uci",
|
||||||
"ureq",
|
"ureq",
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-futures",
|
|
||||||
"web-sys",
|
|
||||||
"web-time",
|
|
||||||
"whatlang",
|
"whatlang",
|
||||||
"winresource",
|
"winresource",
|
||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "chesspenguin-web"
|
|
||||||
version = "2.5.2"
|
|
||||||
dependencies = [
|
|
||||||
"chesspenguin",
|
|
||||||
"eframe",
|
|
||||||
"log",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-futures",
|
|
||||||
"web-sys",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "chrono"
|
name = "chrono"
|
||||||
version = "0.4.45"
|
version = "0.4.45"
|
||||||
|
|
@ -872,9 +836,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"iana-time-zone",
|
"iana-time-zone",
|
||||||
"js-sys",
|
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"wasm-bindgen",
|
|
||||||
"windows-link",
|
"windows-link",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
@ -1706,15 +1668,13 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "game-review"
|
name = "game-review"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"chess-openings",
|
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"shakmaty",
|
"shakmaty",
|
||||||
"uci",
|
"uci",
|
||||||
"web-time",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -1745,11 +1705,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cfg-if",
|
"cfg-if",
|
||||||
"js-sys",
|
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi 5.3.0",
|
"r-efi 5.3.0",
|
||||||
"wasip2",
|
"wasip2",
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -2427,7 +2385,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "maia"
|
name = "maia"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"shakmaty",
|
"shakmaty",
|
||||||
|
|
@ -2476,16 +2434,6 @@ dependencies = [
|
||||||
"unicase",
|
"unicase",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "minicov"
|
|
||||||
version = "0.3.8"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d"
|
|
||||||
dependencies = [
|
|
||||||
"cc",
|
|
||||||
"walkdir",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "minimal-lexical"
|
name = "minimal-lexical"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
|
|
@ -2514,7 +2462,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "mobile-api"
|
name = "mobile-api"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"chess-import",
|
"chess-import",
|
||||||
|
|
@ -2660,15 +2608,6 @@ dependencies = [
|
||||||
"winapi",
|
"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]]
|
[[package]]
|
||||||
name = "num-bigint"
|
name = "num-bigint"
|
||||||
version = "0.4.8"
|
version = "0.4.8"
|
||||||
|
|
@ -3122,7 +3061,7 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "online-games"
|
name = "online-games"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"serde",
|
"serde",
|
||||||
|
|
@ -3130,12 +3069,6 @@ dependencies = [
|
||||||
"ureq",
|
"ureq",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "oorandom"
|
|
||||||
version = "11.1.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "option-ext"
|
name = "option-ext"
|
||||||
version = "0.2.0"
|
version = "0.2.0"
|
||||||
|
|
@ -3395,7 +3328,7 @@ checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "play"
|
name = "play"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"getrandom 0.3.4",
|
"getrandom 0.3.4",
|
||||||
|
|
@ -3494,19 +3427,6 @@ version = "1.5.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1"
|
checksum = "196a7c80b9a7652aba7cc070827516c2abe4ccdf53d128e1944003cf5726cff1"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "prep"
|
|
||||||
version = "2.5.2"
|
|
||||||
dependencies = [
|
|
||||||
"chess-core",
|
|
||||||
"chess-import",
|
|
||||||
"chess-openings",
|
|
||||||
"game-review",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"uci",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "presser"
|
name = "presser"
|
||||||
version = "0.3.1"
|
version = "0.3.1"
|
||||||
|
|
@ -3695,7 +3615,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "releases"
|
name = "releases"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"ureq",
|
"ureq",
|
||||||
|
|
@ -4446,10 +4366,7 @@ version = "0.3.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"js-sys",
|
|
||||||
"libc",
|
"libc",
|
||||||
"wasm-bindgen",
|
|
||||||
"web-sys",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -4693,13 +4610,12 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "trainer"
|
name = "trainer"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chess-core",
|
"chess-core",
|
||||||
"chrono",
|
"chrono",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"web-time",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -4736,16 +4652,10 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uci"
|
name = "uci"
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"js-sys",
|
|
||||||
"libc",
|
"libc",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"wasm-bindgen",
|
|
||||||
"wasm-bindgen-futures",
|
|
||||||
"wasm-bindgen-test",
|
|
||||||
"web-sys",
|
|
||||||
"web-time",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
@ -5116,45 +5026,6 @@ dependencies = [
|
||||||
"unicode-ident",
|
"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]]
|
[[package]]
|
||||||
name = "wayland-backend"
|
name = "wayland-backend"
|
||||||
version = "0.3.17"
|
version = "0.3.17"
|
||||||
|
|
|
||||||
17
Cargo.toml
17
Cargo.toml
|
|
@ -4,7 +4,6 @@ members = [
|
||||||
"crates/chess-core",
|
"crates/chess-core",
|
||||||
"crates/chess-import",
|
"crates/chess-import",
|
||||||
"crates/uci",
|
"crates/uci",
|
||||||
"crates/openings",
|
|
||||||
"crates/game-review",
|
"crates/game-review",
|
||||||
"crates/online-games",
|
"crates/online-games",
|
||||||
"crates/releases",
|
"crates/releases",
|
||||||
|
|
@ -12,13 +11,11 @@ members = [
|
||||||
"crates/maia",
|
"crates/maia",
|
||||||
"crates/trainer",
|
"crates/trainer",
|
||||||
"crates/play",
|
"crates/play",
|
||||||
"crates/prep",
|
|
||||||
"apps/desktop",
|
"apps/desktop",
|
||||||
"apps/web",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "2.5.2"
|
version = "1.9.2"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.97"
|
rust-version = "1.97"
|
||||||
license = "GPL-3.0-or-later"
|
license = "GPL-3.0-or-later"
|
||||||
|
|
@ -31,8 +28,6 @@ shakmaty = "0.30.2"
|
||||||
pgn-reader = "0.29.1"
|
pgn-reader = "0.29.1"
|
||||||
encoding_rs = "0.8"
|
encoding_rs = "0.8"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
# `Instant`/`SystemTime` that also work in a browser (std's panic there).
|
|
||||||
web-time = "1.1"
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
egui = "=0.36.2"
|
egui = "=0.36.2"
|
||||||
|
|
@ -48,20 +43,10 @@ chess-import = { path = "crates/chess-import" }
|
||||||
uci = { path = "crates/uci" }
|
uci = { path = "crates/uci" }
|
||||||
maia = { path = "crates/maia" }
|
maia = { path = "crates/maia" }
|
||||||
game-review = { path = "crates/game-review" }
|
game-review = { path = "crates/game-review" }
|
||||||
chess-openings = { path = "crates/openings" }
|
|
||||||
online-games = { path = "crates/online-games" }
|
online-games = { path = "crates/online-games" }
|
||||||
releases = { path = "crates/releases" }
|
releases = { path = "crates/releases" }
|
||||||
trainer = { path = "crates/trainer" }
|
trainer = { path = "crates/trainer" }
|
||||||
play = { path = "crates/play" }
|
play = { path = "crates/play" }
|
||||||
prep = { path = "crates/prep" }
|
|
||||||
|
|
||||||
[profile.dev.package."*"]
|
[profile.dev.package."*"]
|
||||||
opt-level = 2
|
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"
|
|
||||||
|
|
|
||||||
56
README.md
56
README.md
|
|
@ -5,9 +5,8 @@
|
||||||
<h1 align="center">ChessPenguin</h1>
|
<h1 align="center">ChessPenguin</h1>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
A chess database for Linux, Windows, macOS and Android: open PGN and ChessBase collections,
|
A native chess database for Linux: open PGN collections, read annotated games,
|
||||||
read annotated games, enter your own, analyse them with Stockfish, prepare against an
|
enter your own and analyse them with Stockfish or any UCI engine.
|
||||||
opponent and play against the computer.
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
|
|
@ -15,7 +14,7 @@
|
||||||
<a href="README.ru.md">Русский</a>
|
<a href="README.ru.md">Русский</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
|
|
@ -29,24 +28,11 @@
|
||||||
- **Notation** — main line as a two-column table, comments and variations as blocks,
|
- **Notation** — main line as a two-column table, comments and variations as blocks,
|
||||||
mouse and keyboard navigation.
|
mouse and keyboard navigation.
|
||||||
- **Stockfish included** — analysis works right after installation; other UCI engines can be added.
|
- **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;
|
- **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.
|
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),
|
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
|
better moves in the notation; write it into the game as NAGs, comments and `[%eval]` (undoable).
|
||||||
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.
|
|
||||||
- **Engine lines on the board** — step through a line without touching the game, add it as a
|
- **Engine lines on the board** — step through a line without touching the game, add it as a
|
||||||
variation with one click (undoable).
|
variation with one click (undoable).
|
||||||
- **Editing** — enter moves and variations, promote or delete lines, undo/redo,
|
- **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.
|
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,
|
- **Looks** — 17 piece sets, 37 boards (flat colours and textures), 7 sound sets,
|
||||||
dark and light themes.
|
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.
|
- **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.
|
||||||
- **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.
|
|
||||||
- **Languages** — English, Русский, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша.
|
- **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 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|  |  |
|
|  |  |
|
||||||
| **Engine analysis** | **Reference: what was played here** |
|
| **Engine settings in the analysis panel** | **Library** |
|
||||||
|  |  |
|
|  |  |
|
||||||
| **Library with filters** | **Search by position** |
|
| **Boards and pieces** | |
|
||||||
|  |  |
|
|  | |
|
||||||
| **Play against the computer** | **Android** |
|
|
||||||
|  |  |
|
|
||||||
| **Boards, pieces and a light theme** | |
|
|
||||||
|  | |
|
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
|
|
@ -107,7 +85,7 @@ Packages for every release are on the [Releases](https://github.com/vrubelroman/
|
||||||
| Flatpak | `flatpak install --user ChessPenguin-<version>-x86_64.flatpak` |
|
| Flatpak | `flatpak install --user ChessPenguin-<version>-x86_64.flatpak` |
|
||||||
| Windows | unzip `ChessPenguin-<version>-windows-x86_64.zip`, run `ChessPenguin.exe` |
|
| Windows | unzip `ChessPenguin-<version>-windows-x86_64.zip`, run `ChessPenguin.exe` |
|
||||||
| macOS (Apple Silicon) | open `ChessPenguin-<version>-macos-arm64.dmg`, drag ChessPenguin to Applications |
|
| macOS (Apple Silicon) | open `ChessPenguin-<version>-macos-arm64.dmg`, drag ChessPenguin to Applications |
|
||||||
| Android 12+ | open `ChessPenguin-<version>-android.apk` (Stockfish built in) or `…-android-noengine.apk` (Stockfish downloaded in the app) on the phone |
|
| Android 12+ (alpha) | open `ChessPenguin-<version>-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
|
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).
|
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
|
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.
|
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
|
The **Android app** (alpha) opens databases and games (the same formats), with the notation under
|
||||||
board and Stockfish. Moves are made on the board (variations, undo); your own databases live on
|
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
|
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
|
||||||
move. The two APKs install over each other; databases and settings are kept.
|
APKs install over each other; databases and settings are kept.
|
||||||
|
|
||||||
### Build from source
|
### Build from source
|
||||||
|
|
||||||
|
|
|
||||||
53
README.ru.md
53
README.ru.md
|
|
@ -1,14 +1,11 @@
|
||||||
# ChessPenguin
|
# ChessPenguin
|
||||||
|
|
||||||
Шахматная база для Linux, Windows, macOS и Android: открывайте сборники PGN и ChessBase, читайте
|
Нативная шахматная база для Linux: открывайте PGN-сборники, читайте аннотированные партии,
|
||||||
аннотированные партии, вводите свои, анализируйте их со Stockfish, готовьтесь к сопернику и
|
вводите свои и анализируйте их со Stockfish или любым UCI-движком.
|
||||||
играйте с компьютером.
|
|
||||||
|
|
||||||
[English](README.md) · [Скачать](https://github.com/vrubelroman/chessPenguin/releases/latest)
|
[English](README.md) · [Скачать](https://github.com/vrubelroman/chessPenguin/releases/latest)
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
Скриншоты — английского интерфейса; в программе девять языков, русский среди них.
|
|
||||||
|
|
||||||
## Возможности
|
## Возможности
|
||||||
|
|
||||||
|
|
@ -20,22 +17,11 @@
|
||||||
(windows-1251, windows-1252, KOI8-R, CP866) и учебные нулевые ходы `--`. Исходные файлы не изменяются.
|
(windows-1251, windows-1252, KOI8-R, CP866) и учебные нулевые ходы `--`. Исходные файлы не изменяются.
|
||||||
- **Нотация** — основная линия таблицей в две колонки, комментарии и варианты блоками,
|
- **Нотация** — основная линия таблицей в две колонки, комментарии и варианты блоками,
|
||||||
навигация мышью и клавиатурой.
|
навигация мышью и клавиатурой.
|
||||||
- **Справочник** — какие ходы делали из текущей позиции в базе с полки (для теории — в большой),
|
|
||||||
их статистика, сколько партия держится в базе, сильнейшие партии с этой позицией.
|
|
||||||
- **Поиск по позиции** — расставьте ходы на доске и отфильтруйте базу на миллионы партий по
|
|
||||||
позиции, рядом — фильтры по игроку, годам, рейтингу, дебюту и результату.
|
|
||||||
- **Анализ движком** — любой UCI-движок, до 5 линий, стрелки лучших ходов, шкала оценки;
|
- **Анализ движком** — любой UCI-движок, до 5 линий, стрелки лучших ходов, шкала оценки;
|
||||||
время, потоки и память настраиваются прямо в панели анализа.
|
время, потоки и память настраиваются прямо в панели анализа.
|
||||||
- **Разбор партии** — оценка всей партии в фоне: график под доской, точность, неточности, ошибки
|
- **Анализ партии** — оценка всей партии в фоне: график под доской, точность, неточности, ошибки
|
||||||
и зевки каждого игрока и по стадиям партии (методика Lichess), **блестящие (!!) и
|
и зевки каждого игрока и по стадиям партии (методика Lichess), лучшие ходы в нотации;
|
||||||
замечательные (!) ходы**, сверенные с отметками chess.com на известных партиях, лучшие ходы в
|
запись анализа в партию знаками, комментариями и `[%eval]` (с отменой).
|
||||||
нотации и значки на доске; запись разбора в партию знаками, комментариями и `[%eval]` (с
|
|
||||||
отменой). Разбор всегда идёт на одних и тех же параметрах движка, поэтому у партии одинаковые
|
|
||||||
отметки на любом компьютере и телефоне.
|
|
||||||
- **Подготовка к сопернику** — выберите игрока базы и посмотрите его дебютный репертуар за белых и
|
|
||||||
за чёрных: дерево его ходов с названиями дебютов, партиями, счётом и датой последней партии,
|
|
||||||
таблица дебютов и вариантов с первыми ходами, где он уходит из теории; по кнопке движок находит
|
|
||||||
его ошибки в дебютах — по дебютам и те, что он повторяет. Все таблицы сортируются по колонкам.
|
|
||||||
- **Линии движка на доске** — просмотр линии без изменения партии и вставка её вариантом (с отменой).
|
- **Линии движка на доске** — просмотр линии без изменения партии и вставка её вариантом (с отменой).
|
||||||
- **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор,
|
- **Редактирование** — ввод ходов и вариантов, повышение и удаление линий, отмена/повтор,
|
||||||
копирование PGN/FEN, сохранение партии в новый файл.
|
копирование PGN/FEN, сохранение партии в новый файл.
|
||||||
|
|
@ -51,24 +37,16 @@
|
||||||
в проигранной позиции соперник предлагает сдаться. Сыгранные партии сами записываются в базу
|
в проигранной позиции соперник предлагает сдаться. Сыгранные партии сами записываются в базу
|
||||||
игрока. Maia (316 МБ) и Rodent (48 и 70 МБ) скачиваются по кнопке.
|
игрока. Maia (316 МБ) и Rodent (48 и 70 МБ) скачиваются по кнопке.
|
||||||
- **Оформление** — 17 наборов фигур, 37 досок (цвета и текстуры), 7 наборов звуков, тёмная и светлая тема.
|
- **Оформление** — 17 наборов фигур, 37 досок (цвета и текстуры), 7 наборов звуков, тёмная и светлая тема.
|
||||||
- **Онлайн-партии** — партии любого игрока с Lichess и Chess.com по нику (без входа) в базу; новые партии приходят сами.
|
- **Ваши онлайн-партии** — загрузка своих партий с Lichess и Chess.com по нику (без входа) в базу и обновление одной кнопкой.
|
||||||
- **100 классических партий** встроены — от Андерсена и Морфи до Карлсена, знаменитые — с
|
|
||||||
короткими введениями; встроенные базы обновляются вместе с программой.
|
|
||||||
- **Приложение для Android** — базы и партии тех же форматов, ходы на доске, свои базы, разбор
|
|
||||||
партии с !! и !, игра с Maia, изучение дебюта.
|
|
||||||
- **Языки** — English, Русский, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша.
|
- **Языки** — English, Русский, Français, Deutsch, Español, Italiano, Português, Oʻzbekcha, Қазақша.
|
||||||
|
|
||||||
| Подготовка к сопернику | Разбор партии: отчёт, !! и ! |
|
| Анализ партии: график и отчёт | Отметки движка и лучшие варианты |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
|  |  |
|
|  |  |
|
||||||
| **Анализ движком** | **Справочник: что здесь играли** |
|
| **Настройки движка в панели анализа** | **Библиотека** |
|
||||||
|  |  |
|
|  |  |
|
||||||
| **Библиотека с фильтрами** | **Поиск по позиции** |
|
| **Доски и фигуры** | |
|
||||||
|  |  |
|
|  | |
|
||||||
| **Игра с компьютером** | **Android** |
|
|
||||||
|  |  |
|
|
||||||
| **Доски, фигуры и светлая тема** | |
|
|
||||||
|  | |
|
|
||||||
|
|
||||||
## Установка
|
## Установка
|
||||||
|
|
||||||
|
|
@ -81,9 +59,8 @@ Stockfish 19 (около 80 МБ, проверяется перед запуск
|
||||||
в **Настройки → Движки**. Установленный в системе `stockfish` находится сам, другие UCI-движки
|
в **Настройки → Движки**. Установленный в системе `stockfish` находится сам, другие UCI-движки
|
||||||
добавляются из файла. Во Flatpak Stockfish уже есть.
|
добавляются из файла. Во Flatpak Stockfish уже есть.
|
||||||
|
|
||||||
**Android 12+:** базы и партии (те же форматы), нотация под доской, Stockfish; ходы на доске
|
**Android 12+ (альфа-версия):** базы и партии (те же форматы), нотация под доской, Stockfish; ходы на доске
|
||||||
(варианты, отмена), свои базы на телефоне, разбор партии с !! и !, игра с Maia и Rodent IV,
|
(варианты, отмена), свои базы на телефоне, игра с Maia (малая модель, без часов; партии сами пишутся в базу игрока) и изучение дебюта.
|
||||||
изучение дебюта.
|
|
||||||
Две сборки: `ChessPenguin-<версия>-android.apk` — Stockfish уже внутри, `…-android-noengine.apk` —
|
Две сборки: `ChessPenguin-<версия>-android.apk` — Stockfish уже внутри, `…-android-noengine.apk` —
|
||||||
Stockfish скачивается в приложении. Ставятся одна поверх другой, базы и настройки сохраняются.
|
Stockfish скачивается в приложении. Ставятся одна поверх другой, базы и настройки сохраняются.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -149,39 +149,6 @@ platform into the user's data directory and checks its SHA-256 (pinned in
|
||||||
Open Database License (ODbL).
|
Open Database License (ODbL).
|
||||||
- ChessPenguin runs Stockfish as a separate process over the UCI protocol.
|
- 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
|
## ChessBase formats
|
||||||
|
|
||||||
- `crates/chess-import/src/cbv.rs` reads ChessBase archives following uncbv
|
- `crates/chess-import/src/cbv.rs` reads ChessBase archives following uncbv
|
||||||
|
|
@ -203,16 +170,3 @@ Three evaluation signs (⩲ ⩱ ⌓) come from Noto Sans Math (Copyright 2022 Go
|
||||||
cut down to those glyphs: `apps/desktop/assets/fonts/NotoSansMath-nag.ttf`, licence beside it.
|
cut down to those glyphs: `apps/desktop/assets/fonts/NotoSansMath-nag.ttf`, licence beside it.
|
||||||
The figurines of the move notation (♔♕♖♗♘) are the five chess glyphs of egui's
|
The figurines of the move notation (♔♕♖♗♘) are the five chess glyphs of egui's
|
||||||
emoji-icon-font (MIT), cut out to `apps/desktop/assets/fonts/figurines.ttf`.
|
emoji-icon-font (MIT), cut out to `apps/desktop/assets/fonts/figurines.ttf`.
|
||||||
The moves of the notation and the move marks on the board are in Ubuntu Bold (Ubuntu Font
|
|
||||||
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`.
|
|
||||||
|
|
|
||||||
1
androidApp/.gitignore
vendored
1
androidApp/.gitignore
vendored
|
|
@ -14,5 +14,4 @@
|
||||||
.cxx
|
.cxx
|
||||||
local.properties
|
local.properties
|
||||||
/dist
|
/dist
|
||||||
/dist-rustore
|
|
||||||
.env
|
.env
|
||||||
|
|
|
||||||
|
|
@ -147,9 +147,6 @@ android {
|
||||||
buildConfigField("String", "NET_NAME", "\"nn-1a298aa575a0.nnue\"")
|
buildConfigField("String", "NET_NAME", "\"nn-1a298aa575a0.nnue\"")
|
||||||
buildConfigField("String", "NET_SHA256", "\"1a298aa575a085434d29027978dc36867fe9c5bcea9376654b7a8eba1e52dfc2\"")
|
buildConfigField("String", "NET_SHA256", "\"1a298aa575a085434d29027978dc36867fe9c5bcea9376654b7a8eba1e52dfc2\"")
|
||||||
buildConfigField("long", "NET_SIZE", "98511183L")
|
buildConfigField("long", "NET_SIZE", "98511183L")
|
||||||
// The app checks for its releases and installs them itself (android-ui.md §25);
|
|
||||||
// the check is what the site counts installations by. Off for stores.
|
|
||||||
buildConfigField("boolean", "SELF_UPDATE", "true")
|
|
||||||
buildConfigField(
|
buildConfigField(
|
||||||
"String",
|
"String",
|
||||||
"NET_URL",
|
"NET_URL",
|
||||||
|
|
@ -185,14 +182,6 @@ android {
|
||||||
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||||
signingConfig = signingConfigs.findByName("release")
|
signingConfig = signingConfigs.findByName("release")
|
||||||
}
|
}
|
||||||
// RuStore (docs/decisions.md «RuStore»): the release, signed with the same key,
|
|
||||||
// without the app's own updates and the check the site counts installations by;
|
|
||||||
// the store updates it. Its manifest (src/rustore) drops the install permissions.
|
|
||||||
create("rustore") {
|
|
||||||
initWith(getByName("release"))
|
|
||||||
buildConfigField("boolean", "SELF_UPDATE", "false")
|
|
||||||
matchingFallbacks += listOf("release")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// The languages of the interface; the libraries' other translations stay out.
|
// The languages of the interface; the libraries' other translations stay out.
|
||||||
androidResources {
|
androidResources {
|
||||||
|
|
@ -240,11 +229,6 @@ tasks.named("preBuild") {
|
||||||
dependsOn(uniffiBindings, bundleAssets, stockfish, rodent4)
|
dependsOn(uniffiBindings, bundleAssets, stockfish, rodent4)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RuStore gets the full build only (Stockfish inside: nothing to fetch from GitHub).
|
|
||||||
androidComponents {
|
|
||||||
beforeVariants(selector().withBuildType("rustore").withFlavor("engine" to "light")) { it.enable = false }
|
|
||||||
}
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
val composeBom = platform(libs.androidx.compose.bom)
|
val composeBom = platform(libs.androidx.compose.bom)
|
||||||
implementation(composeBom)
|
implementation(composeBom)
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,6 @@
|
||||||
<!-- One task: a file opened from another app comes to the app already open. -->
|
<!-- One task: a file opened from another app comes to the app already open. -->
|
||||||
<activity
|
<activity
|
||||||
android:name=".MainActivity"
|
android:name=".MainActivity"
|
||||||
android:configChanges="uiMode"
|
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTask">
|
android:launchMode="singleTask">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
|
|
|
||||||
|
|
@ -7,9 +7,6 @@ import androidx.compose.runtime.setValue
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.provider.OpenableColumns
|
import android.provider.OpenableColumns
|
||||||
import io.github.vrubelroman.chesspenguin.data.AppUpdates
|
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.DbEntry
|
||||||
import io.github.vrubelroman.chesspenguin.data.EngineFiles
|
import io.github.vrubelroman.chesspenguin.data.EngineFiles
|
||||||
import io.github.vrubelroman.chesspenguin.data.MaiaFiles
|
import io.github.vrubelroman.chesspenguin.data.MaiaFiles
|
||||||
|
|
@ -27,6 +24,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger
|
||||||
import java.io.FileNotFoundException
|
import java.io.FileNotFoundException
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
|
|
@ -51,18 +49,6 @@ class ChessPenguinApp : Application() {
|
||||||
val downloads by lazy { OnlineDownloads(library, scope) }
|
val downloads by lazy { OnlineDownloads(library, scope) }
|
||||||
/// The app's own updates (android-ui.md §25).
|
/// The app's own updates (android-ui.md §25).
|
||||||
val updates by lazy { AppUpdates(this, scope, engineFiles) }
|
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() {
|
override fun onCreate() {
|
||||||
super.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.
|
/// One copy at a time, in the order the files came; only the last one opened is shown.
|
||||||
private val copying = Mutex()
|
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
|
/// 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.
|
/// the list; `incoming` tells the screens how it went.
|
||||||
fun receive(uri: Uri) {
|
fun receive(uri: Uri) {
|
||||||
val request = latestIncoming.withLock {
|
waiting.incrementAndGet()
|
||||||
latestIncoming.next(IncomingOrigin.Uri).also { incoming.value = Incoming.Opening }
|
incoming.value = Incoming.Opening
|
||||||
}
|
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val result = copying.withLock {
|
val result = copying.withLock {
|
||||||
try {
|
try {
|
||||||
|
|
@ -116,47 +101,9 @@ class ChessPenguinApp : Application() {
|
||||||
Incoming.Failed(e)
|
Incoming.Failed(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
latestIncoming.publish(request) { incoming.value = result }
|
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
|
||||||
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -172,47 +119,8 @@ class ChessBasePart : Exception()
|
||||||
|
|
||||||
private val CHESSBASE_PARTS = setOf("cbh", "cbg", "cba", "cbp", "cbs", "cbj", "cbt", "cbc", "cbe", "cbm")
|
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 <T> withLock(action: () -> T): T = synchronized(lock, action)
|
|
||||||
}
|
|
||||||
|
|
||||||
sealed interface Incoming {
|
sealed interface Incoming {
|
||||||
data object Opening : Incoming
|
data object Opening : Incoming
|
||||||
data class Opened(val entry: DbEntry) : Incoming
|
data class Opened(val entry: DbEntry) : Incoming
|
||||||
data class Pasted(val entry: DbEntry) : Incoming
|
|
||||||
data class Failed(val error: Throwable) : Incoming
|
data class Failed(val error: Throwable) : Incoming
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,6 @@
|
||||||
package io.github.vrubelroman.chesspenguin
|
package io.github.vrubelroman.chesspenguin
|
||||||
|
|
||||||
import android.content.ClipboardManager
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.app.UiModeManager
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import androidx.lifecycle.Lifecycle
|
import androidx.lifecycle.Lifecycle
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
|
|
@ -21,7 +19,6 @@ import androidx.compose.material3.Surface
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.foundation.isSystemInDarkTheme
|
import androidx.compose.foundation.isSystemInDarkTheme
|
||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
|
||||||
import androidx.compose.runtime.collectAsState
|
import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import io.github.vrubelroman.chesspenguin.data.Language
|
import io.github.vrubelroman.chesspenguin.data.Language
|
||||||
|
|
@ -63,18 +60,6 @@ class MainActivity : ComponentActivity() {
|
||||||
Theme.Light -> false
|
Theme.Light -> false
|
||||||
Theme.Dark -> true
|
Theme.Dark -> true
|
||||||
}
|
}
|
||||||
// Android keeps the app's own day or night (Android 12+): the window and the
|
|
||||||
// splash screen before Compose draws then match the theme chosen, not the
|
|
||||||
// system's (no white flash before a dark app).
|
|
||||||
LaunchedEffect(prefs.theme) {
|
|
||||||
getSystemService(UiModeManager::class.java)?.setApplicationNightMode(
|
|
||||||
when (prefs.theme) {
|
|
||||||
Theme.System -> UiModeManager.MODE_NIGHT_AUTO
|
|
||||||
Theme.Light -> UiModeManager.MODE_NIGHT_NO
|
|
||||||
Theme.Dark -> UiModeManager.MODE_NIGHT_YES
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
// The system bars follow the theme chosen in the app, not the system's: light
|
// The system bars follow the theme chosen in the app, not the system's: light
|
||||||
// icons over a dark app even when the phone itself is light, and back.
|
// icons over a dark app even when the phone itself is light, and back.
|
||||||
DisposableEffect(dark) {
|
DisposableEffect(dark) {
|
||||||
|
|
@ -112,15 +97,11 @@ class MainActivity : ComponentActivity() {
|
||||||
val updates = (application as ChessPenguinApp).updates
|
val updates = (application as ChessPenguinApp).updates
|
||||||
updates.foreground = true
|
updates.foreground = true
|
||||||
updates.checkIfDue()
|
updates.checkIfDue()
|
||||||
// The downloaded databases get their new games (at most every ten minutes).
|
|
||||||
(application as ChessPenguinApp).downloads.updateAllQuietly()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
super.onResume()
|
super.onResume()
|
||||||
val app = application as ChessPenguinApp
|
(application as ChessPenguinApp).updates.onResume()
|
||||||
app.updates.onResume()
|
|
||||||
app.clipboardPgn.check(clipboardText(this))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onStop() {
|
override fun onStop() {
|
||||||
|
|
@ -130,10 +111,3 @@ class MainActivity : ComponentActivity() {
|
||||||
if (!isChangingConfigurations) (application as ChessPenguinApp).leftApp()
|
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()
|
|
||||||
|
|
|
||||||
|
|
@ -16,8 +16,6 @@ import androidx.compose.runtime.collectAsState
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
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.res.stringResource
|
||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.window.Dialog
|
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.PLAY_GAME
|
||||||
import io.github.vrubelroman.chesspenguin.ui.GamesScreen
|
import io.github.vrubelroman.chesspenguin.ui.GamesScreen
|
||||||
import io.github.vrubelroman.chesspenguin.ui.OnlineScreen
|
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
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
@Serializable data object Databases : NavKey
|
@Serializable data object Databases : NavKey
|
||||||
|
|
||||||
@Serializable data class Games(val db: String) : 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 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).
|
/// the same game comes back after Android restarts the app).
|
||||||
@Serializable data class GameAt(val db: String, val place: Int, val query: String = "") : NavKey
|
@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))
|
backStack.add(Games(entry.id))
|
||||||
if (entry.games == 1) backStack.add(GameAt(entry.id, 0))
|
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 app = app()
|
||||||
val incoming by app.incoming.collectAsState()
|
val incoming by app.incoming.collectAsState()
|
||||||
LaunchedEffect(incoming) {
|
LaunchedEffect(incoming) {
|
||||||
when (val i = incoming) {
|
(incoming as? Incoming.Opened)?.let {
|
||||||
is Incoming.Opened -> {
|
app.incoming.value = null
|
||||||
if (app.incoming.compareAndSet(i, null)) show(i.entry)
|
show(it.entry)
|
||||||
}
|
|
||||||
is Incoming.Pasted -> {
|
|
||||||
if (app.incoming.compareAndSet(i, null)) {
|
|
||||||
resetPastedView(app.shown, app.lastOpened, i.entry.id)
|
|
||||||
showPasted(i.entry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else -> {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// The app's update, over any screen (android-ui.md §25.3).
|
// The app's update, over any screen (android-ui.md §25.3).
|
||||||
val updateSheet by app.updates.sheet.collectAsState()
|
val updateSheet by app.updates.sheet.collectAsState()
|
||||||
if (updateSheet) UpdateSheet()
|
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) {
|
when (val i = incoming) {
|
||||||
Incoming.Opening -> Dialog(onDismissRequest = {}, properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) {
|
Incoming.Opening -> Dialog(onDismissRequest = {}, properties = DialogProperties(dismissOnBackPress = false, dismissOnClickOutside = false)) {
|
||||||
Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainerHigh) {
|
Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.surfaceContainerHigh) {
|
||||||
|
|
@ -158,10 +99,10 @@ fun MainNavigation() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
is Incoming.Failed -> AlertDialog(
|
is Incoming.Failed -> AlertDialog(
|
||||||
onDismissRequest = { app.incoming.compareAndSet(i, null) },
|
onDismissRequest = { app.incoming.value = null },
|
||||||
title = { Text(stringResource(R.string.file_failed)) },
|
title = { Text(stringResource(R.string.file_failed)) },
|
||||||
text = { Text(incomingProblem(i.error)) },
|
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 -> {}
|
else -> {}
|
||||||
}
|
}
|
||||||
|
|
@ -195,35 +136,10 @@ fun MainNavigation() {
|
||||||
}, onOpenDatabase = { id -> backStack.add(Games(id)) })
|
}, onOpenDatabase = { id -> backStack.add(Games(id)) })
|
||||||
}
|
}
|
||||||
entry<Games> { key ->
|
entry<Games> { key ->
|
||||||
GamesScreen(
|
GamesScreen(key.db, onBack = { backStack.removeLastOrNull() }, onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) })
|
||||||
key.db,
|
|
||||||
onBack = { backStack.removeLastOrNull() },
|
|
||||||
onGame = { place, query -> backStack.add(GameAt(key.db, place, query)) },
|
|
||||||
onPlayers = { backStack.add(Players(key.db)) },
|
|
||||||
)
|
|
||||||
}
|
|
||||||
entry<Players> { key ->
|
|
||||||
PlayersScreen(
|
|
||||||
key.db,
|
|
||||||
onBack = { backStack.removeLastOrNull() },
|
|
||||||
onPrepare = { player, white ->
|
|
||||||
backStack.add(Preparation(PrepStart(db = key.db, player = player.name, white = white)))
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
|
||||||
entry<Preparation> { key ->
|
|
||||||
PrepScreen(key.request, onBack = { backStack.removeLastOrNull() })
|
|
||||||
}
|
}
|
||||||
entry<GameAt> { key ->
|
entry<GameAt> { key ->
|
||||||
GameScreen(
|
GameScreen(key.db, key.place, key.query, onBack = { backStack.removeLastOrNull() }, onSettings = { backStack.add(SettingsKey) }, onPlayGame = { backStack.add(PlayKey) })
|
||||||
key.db,
|
|
||||||
key.place,
|
|
||||||
key.query,
|
|
||||||
onBack = { backStack.removeLastOrNull() },
|
|
||||||
onSettings = { backStack.add(SettingsKey) },
|
|
||||||
onPlayGame = { backStack.add(PlayKey) },
|
|
||||||
onPrepare = { backStack.add(Preparation(it)) },
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
entry<SettingsKey> {
|
entry<SettingsKey> {
|
||||||
SettingsScreen(
|
SettingsScreen(
|
||||||
|
|
@ -252,15 +168,6 @@ fun MainNavigation() {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun resetPastedView(
|
|
||||||
shown: HashMap<String, List<UInt>>,
|
|
||||||
lastOpened: HashMap<String, Pair<String, Int>>,
|
|
||||||
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
|
/// 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).
|
/// not that of a database on it (openProblem).
|
||||||
@Composable
|
@Composable
|
||||||
|
|
|
||||||
|
|
@ -186,9 +186,8 @@ class AppUpdates(private val context: Context, private val scope: CoroutineScope
|
||||||
}
|
}
|
||||||
val update = known()
|
val update = known()
|
||||||
when {
|
when {
|
||||||
// Installed by hand from the site, or never newer than this app; or a store's
|
// Installed by hand from the site, or never newer than this app.
|
||||||
// build put over the site's (the store updates it, a release kept is dropped).
|
update == null || !newer(update.version) -> forgetAll()
|
||||||
!BuildConfig.SELF_UPDATE || update == null || !newer(update.version) -> forgetAll()
|
|
||||||
prefs.getLong(DOWNLOAD, -1L) != -1L -> watch(update, prefs.getLong(DOWNLOAD, -1L))
|
prefs.getLong(DOWNLOAD, -1L) != -1L -> watch(update, prefs.getLong(DOWNLOAD, -1L))
|
||||||
update.sha256.isEmpty() -> _state.value = UpdateState.Failed(update, UpdateProblem.BadRelease, null)
|
update.sha256.isEmpty() -> _state.value = UpdateState.Failed(update, UpdateProblem.BadRelease, null)
|
||||||
prefs.getString(READY, null) == update.version && apk(update).exists() -> _state.value = UpdateState.Ready(update, aborted = false)
|
prefs.getString(READY, null) == update.version && apk(update).exists() -> _state.value = UpdateState.Ready(update, aborted = false)
|
||||||
|
|
@ -206,7 +205,7 @@ class AppUpdates(private val context: Context, private val scope: CoroutineScope
|
||||||
/// of the app, as the desktop does (a release out since the last check is offered at
|
/// of the app, as the desktop does (a release out since the last check is offered at
|
||||||
/// once), and on return 6 h after the last answer (1 h after a failed try).
|
/// once), and on return 6 h after the last answer (1 h after a failed try).
|
||||||
fun checkIfDue() {
|
fun checkIfDue() {
|
||||||
if (!BuildConfig.SELF_UPDATE || !_auto.value || busy()) return
|
if (!_auto.value || busy()) return
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
if (askedThisRun && (now - _lastCheck.value < RECHECK || now - prefs.getLong(LAST_ATTEMPT, 0L) < HOUR)) return
|
if (askedThisRun && (now - _lastCheck.value < RECHECK || now - prefs.getLong(LAST_ATTEMPT, 0L) < HOUR)) return
|
||||||
askedThisRun = true
|
askedThisRun = true
|
||||||
|
|
@ -215,13 +214,11 @@ class AppUpdates(private val context: Context, private val scope: CoroutineScope
|
||||||
|
|
||||||
/// «Check now» (works with the automatic check off).
|
/// «Check now» (works with the automatic check off).
|
||||||
fun checkNow() {
|
fun checkNow() {
|
||||||
if (!BuildConfig.SELF_UPDATE || _check.value == CheckState.Checking) return
|
if (_check.value == CheckState.Checking) return
|
||||||
scope.launch { runCheck(manual = true) }
|
scope.launch { runCheck(manual = true) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun runCheck(manual: Boolean) {
|
private suspend fun runCheck(manual: Boolean) {
|
||||||
// A store's build never asks the site (nor counts itself there).
|
|
||||||
if (!BuildConfig.SELF_UPDATE) return
|
|
||||||
if (busy()) {
|
if (busy()) {
|
||||||
if (manual) _check.value = CheckState.Idle
|
if (manual) _check.value = CheckState.Idle
|
||||||
return
|
return
|
||||||
|
|
|
||||||
|
|
@ -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<ClipboardOffer?>(null)
|
|
||||||
val offer: StateFlow<ClipboardOffer?> = _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<String> = emptySet(),
|
|
||||||
private val onDecide: (Set<String>) -> 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
|
|
||||||
|
|
@ -73,8 +73,7 @@ data class DbEntry(
|
||||||
val format: String? = null,
|
val format: String? = null,
|
||||||
/// A sample shows the name of the current language until it is renamed (displayName).
|
/// A sample shows the name of the current language until it is renamed (displayName).
|
||||||
val renamed: Boolean = false,
|
val renamed: Boolean = false,
|
||||||
/// A copy's SHA-256: the same file opened again is not copied twice. A sample's: of
|
/// A copy's SHA-256: the same file opened again is not copied twice.
|
||||||
/// the text its number of games was taken from (a new app may bring a new text).
|
|
||||||
val sha256: String? = null,
|
val sha256: String? = null,
|
||||||
/// A downloaded database: when its last download finished (Unix seconds).
|
/// A downloaded database: when its last download finished (Unix seconds).
|
||||||
val updated: Long? = null,
|
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) }
|
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.
|
/// 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 } } }
|
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
|
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
|
/// 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]
|
/// 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
|
/// 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) }
|
val sum = digest.digest().joinToString("") { "%02x".format(it) }
|
||||||
lock.withLock {
|
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 id = UUID.randomUUID().toString()
|
||||||
val kept = File(copies, "$id.$ext")
|
val kept = File(copies, "$id.$ext")
|
||||||
|
|
@ -326,11 +292,6 @@ class Library(private val context: Context) {
|
||||||
sha256 = sum,
|
sha256 = sum,
|
||||||
)
|
)
|
||||||
lock.withLock {
|
lock.withLock {
|
||||||
copyWithDigest(_entries.value, sum)?.let { existing ->
|
|
||||||
db.close()
|
|
||||||
kept.delete()
|
|
||||||
return@withContext existing
|
|
||||||
}
|
|
||||||
open[id] = db
|
open[id] = db
|
||||||
update { it + entry }
|
update { it + entry }
|
||||||
}
|
}
|
||||||
|
|
@ -618,14 +579,10 @@ class Library(private val context: Context) {
|
||||||
suspend fun database(id: String): Result<Database> = lock.withLock {
|
suspend fun database(id: String): Result<Database> = lock.withLock {
|
||||||
open[id]?.let { return@withLock Result.success(it) }
|
open[id]?.let { return@withLock Result.success(it) }
|
||||||
val e = entry(id) ?: return@withLock Result.failure(IllegalArgumentException("no database $id"))
|
val e = entry(id) ?: return@withLock Result.failure(IllegalArgumentException("no database $id"))
|
||||||
var text: String? = e.sha256
|
|
||||||
val result = withContext(Dispatchers.IO) {
|
val result = withContext(Dispatchers.IO) {
|
||||||
runCatching {
|
runCatching {
|
||||||
when (e.source) {
|
when (e.source) {
|
||||||
Source.Sample -> sampleBytes(e).let { bytes ->
|
Source.Sample -> openBytes(e.fileName, context.assets.open(e.location).use { it.readBytes() })
|
||||||
text = sha256(bytes)
|
|
||||||
openBytes(e.fileName, bytes)
|
|
||||||
}
|
|
||||||
Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd())
|
Source.File -> openFile(e.fileName, openDocument(Uri.parse(e.location)).detachFd())
|
||||||
Source.ChessBase -> openChessBase(e)
|
Source.ChessBase -> openChessBase(e)
|
||||||
Source.Copy -> openFile(
|
Source.Copy -> openFile(
|
||||||
|
|
@ -644,20 +601,10 @@ class Library(private val context: Context) {
|
||||||
open[id] = db
|
open[id] = db
|
||||||
val games = db.len().toInt()
|
val games = db.len().toInt()
|
||||||
val format = db.format()
|
val format = db.format()
|
||||||
val sum = text
|
if (e.games != games || e.format != format) {
|
||||||
if (e.games != games || e.format != format || e.sha256 != sum) {
|
update { list -> list.map { if (it.id == id) it.copy(games = games, format = format) else it } }
|
||||||
update { list -> list.map { if (it.id == id) it.copy(games = games, format = format, sha256 = sum) else it } }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun firstPgnGameIsMeaningful(count: Int, tags: Int, nodes: Int): Boolean =
|
|
||||||
count > 0 && (tags > 0 || nodes > 1)
|
|
||||||
|
|
||||||
internal fun copyWithDigest(entries: List<DbEntry>, 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) }
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package io.github.vrubelroman.chesspenguin.data
|
||||||
|
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
|
@ -23,9 +22,8 @@ import java.util.concurrent.ConcurrentHashMap
|
||||||
/// database did not exist before it (its first download).
|
/// database did not exist before it (its first download).
|
||||||
data class DownloadView(val accounts: List<OnlineAccount>, val state: DownloadState, val fresh: Boolean = false)
|
data class DownloadView(val accounts: List<OnlineAccount>, val state: DownloadState, val fresh: Boolean = false)
|
||||||
|
|
||||||
/// A download that has ended, for the snackbar of the screen that is shown then;
|
/// A download that has ended, for the snackbar of the screen that is shown then.
|
||||||
/// `quiet` when the app started it on its own (said only when it added games).
|
data class Finished(val id: String, val name: String, val view: DownloadView, val games: Int)
|
||||||
data class Finished(val id: String, val name: String, val view: DownloadView, val games: Int, val quiet: Boolean = false)
|
|
||||||
|
|
||||||
/// The downloads of games from Lichess and Chess.com (android-ui.md §23). They belong to
|
/// The downloads of games from Lichess and Chess.com (android-ui.md §23). They belong to
|
||||||
/// the app, not to a screen: leaving the screen does not stop them, and the list of
|
/// the app, not to a screen: leaving the screen does not stop them, and the list of
|
||||||
|
|
@ -46,15 +44,13 @@ class OnlineDownloads(private val library: Library, private val scope: Coroutine
|
||||||
|
|
||||||
/// Starts fetching the new games of `accounts` into the database file `path` (put on
|
/// Starts fetching the new games of `accounts` into the database file `path` (put on
|
||||||
/// the list at once); one download per database. Returns the database's entry.
|
/// the list at once); one download per database. Returns the database's entry.
|
||||||
fun start(accounts: List<OnlineAccount>, path: String): DbEntry = run(accounts, path, false).first
|
fun start(accounts: List<OnlineAccount>, path: String): DbEntry {
|
||||||
|
|
||||||
private fun run(accounts: List<OnlineAccount>, path: String, quiet: Boolean): Pair<DbEntry, Job?> {
|
|
||||||
val fresh = !File(path).exists()
|
val fresh = !File(path).exists()
|
||||||
val entry = library.addOnline(File(path))
|
val entry = library.addOnline(File(path))
|
||||||
if (running.containsKey(entry.id)) return entry to null
|
if (running.containsKey(entry.id)) return entry
|
||||||
val d = OnlineDownload.start(accounts, path)
|
val d = OnlineDownload.start(accounts, path)
|
||||||
running[entry.id] = d
|
running[entry.id] = d
|
||||||
val job = scope.launch(Dispatchers.IO) {
|
scope.launch(Dispatchers.IO) {
|
||||||
while (true) {
|
while (true) {
|
||||||
val s = d.state()
|
val s = d.state()
|
||||||
_views.update { it + (entry.id to DownloadView(accounts, s, fresh)) }
|
_views.update { it + (entry.id to DownloadView(accounts, s, fresh)) }
|
||||||
|
|
@ -68,9 +64,9 @@ class OnlineDownloads(private val library: Library, private val scope: Coroutine
|
||||||
// No game at all (no standard chess there, or it failed at once): not a database.
|
// No game at all (no standard chess there, or it failed at once): not a database.
|
||||||
val name = library.entry(entry.id)?.name ?: entry.name
|
val name = library.entry(entry.id)?.name ?: entry.name
|
||||||
if (games == 0) library.dropEmpty(entry.id) else library.downloaded(entry.id, games, info?.updated)
|
if (games == 0) library.dropEmpty(entry.id) else library.downloaded(entry.id, games, info?.updated)
|
||||||
_views.value[entry.id]?.let { _finished.tryEmit(Finished(entry.id, name, it, games, quiet)) }
|
_views.value[entry.id]?.let { _finished.tryEmit(Finished(entry.id, name, it, games)) }
|
||||||
}
|
}
|
||||||
return entry to job
|
return entry
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetches the games played since the last download of a database.
|
/// Fetches the games played since the last download of a database.
|
||||||
|
|
@ -80,26 +76,6 @@ class OnlineDownloads(private val library: Library, private val scope: Coroutine
|
||||||
start(info.accounts, path)
|
start(info.accounts, path)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every downloaded database gets the games played since, one after another (the
|
|
||||||
/// sites ask for one export at a time): at the app's start and when it comes back to
|
|
||||||
/// the screen, at most every [AUTO_EVERY_MS].
|
|
||||||
fun updateAllQuietly() {
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
if (auto?.isActive == true || now - lastAuto < AUTO_EVERY_MS) return
|
|
||||||
lastAuto = now
|
|
||||||
auto = scope.launch(Dispatchers.IO) {
|
|
||||||
for (e in library.entries.value.filter { it.source == Source.Online }) {
|
|
||||||
if (isRunning(e.id)) continue
|
|
||||||
val path = library.onlineFile(e).path
|
|
||||||
val info = onlineDatabase(path) ?: continue
|
|
||||||
run(info.accounts, path, true).second?.join()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private var lastAuto = 0L
|
|
||||||
private var auto: Job? = null
|
|
||||||
|
|
||||||
/// Stops a download; what it fetched stays.
|
/// Stops a download; what it fetched stays.
|
||||||
fun cancel(id: String) {
|
fun cancel(id: String) {
|
||||||
running[id]?.cancel()
|
running[id]?.cancel()
|
||||||
|
|
@ -109,6 +85,5 @@ class OnlineDownloads(private val library: Library, private val scope: Coroutine
|
||||||
|
|
||||||
private companion object {
|
private companion object {
|
||||||
const val POLL_MS = 400L
|
const val POLL_MS = 400L
|
||||||
const val AUTO_EVERY_MS = 10 * 60 * 1000L
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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<String, UInt>()
|
|
||||||
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(),
|
|
||||||
)
|
|
||||||
|
|
@ -15,9 +15,11 @@ import uniffi.mobile_api.Database
|
||||||
import uniffi.mobile_api.GameReview
|
import uniffi.mobile_api.GameReview
|
||||||
import uniffi.mobile_api.ReviewState
|
import uniffi.mobile_api.ReviewState
|
||||||
|
|
||||||
/// A first guess at the speed of one engine process (one thread) before it was measured
|
/// Nodes per position of the three qualities, as on the desktop (android-ui.md §21.2).
|
||||||
/// on this phone.
|
val REVIEW_NODES = listOf(250_000UL, 1_000_000UL, 3_000_000UL)
|
||||||
const val GUESS_NPS = 250_000L
|
|
||||||
|
/// 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
|
/// 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
|
/// 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`
|
/// 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
|
/// `done` gets the final state when the job ends by itself.
|
||||||
/// (decisions.md, 2026-10-28). `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) {
|
||||||
fun start(path: String, evalFile: String, full: Boolean, done: (ReviewState) -> Unit) {
|
|
||||||
val gen = generation
|
val gen = generation
|
||||||
scope.launch {
|
scope.launch {
|
||||||
lock.withLock {
|
lock.withLock {
|
||||||
val r = review ?: return@withLock
|
val r = review ?: return@withLock
|
||||||
if (gen != generation) return@withLock
|
if (gen != generation) return@withLock
|
||||||
val started = withContext(Dispatchers.IO) {
|
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() }
|
_state.value = withContext(Dispatchers.IO) { r.state() }
|
||||||
if (started) poll(r, gen, done)
|
if (started) poll(r, gen, done)
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ enum class Notation { Latin, Figurines, Local }
|
||||||
|
|
||||||
/// The user's choices (android-ui.md §9), applied at once and kept across starts.
|
/// The user's choices (android-ui.md §9), applied at once and kept across starts.
|
||||||
data class Prefs(
|
data class Prefs(
|
||||||
val theme: Theme = Theme.Dark,
|
val theme: Theme = Theme.System,
|
||||||
val notation: Notation = Notation.Latin,
|
val notation: Notation = Notation.Latin,
|
||||||
val board: BoardTheme = BoardTheme.Green,
|
val board: BoardTheme = BoardTheme.Green,
|
||||||
val pieces: PieceSet = PieceSet.Merida,
|
val pieces: PieceSet = PieceSet.Merida,
|
||||||
|
|
@ -27,8 +27,10 @@ data class Prefs(
|
||||||
val engineSeconds: Int = 20,
|
val engineSeconds: Int = 20,
|
||||||
val engineThreads: Int = defaultThreads(),
|
val engineThreads: Int = defaultThreads(),
|
||||||
val engineHashMb: Int = 64,
|
val engineHashMb: Int = 64,
|
||||||
/// The speed of one engine process (one thread) measured by the last game analysis
|
/// The game report's quality, an index into REVIEW_NODES (§21.2).
|
||||||
/// (0 = not yet), for the time estimate.
|
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,
|
val reviewNps: Long = 0,
|
||||||
/// The last choices of a game against the computer (android-play.md §31.1,
|
/// 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,
|
/// 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),
|
engineSeconds = store.getInt("engineSeconds", d.engineSeconds),
|
||||||
engineThreads = store.getInt("engineThreads", d.engineThreads),
|
engineThreads = store.getInt("engineThreads", d.engineThreads),
|
||||||
engineHashMb = store.getInt("engineHashMb", d.engineHashMb),
|
engineHashMb = store.getInt("engineHashMb", d.engineHashMb),
|
||||||
|
reviewQuality = store.getInt("reviewQuality", d.reviewQuality).coerceIn(0, REVIEW_NODES.size - 1),
|
||||||
reviewNps = store.getLong("reviewNps", d.reviewNps),
|
reviewNps = store.getLong("reviewNps", d.reviewNps),
|
||||||
opponent = Opponent.entries.firstOrNull { it.key == store.getString("opponent", null) } ?: d.opponent,
|
opponent = Opponent.entries.firstOrNull { it.key == store.getString("opponent", null) } ?: d.opponent,
|
||||||
maiaStrength = store.getInt("maiaStrength", d.maiaStrength),
|
maiaStrength = store.getInt("maiaStrength", d.maiaStrength),
|
||||||
|
|
@ -106,6 +109,7 @@ class Settings(context: Context) {
|
||||||
.putInt("engineSeconds", p.engineSeconds)
|
.putInt("engineSeconds", p.engineSeconds)
|
||||||
.putInt("engineThreads", p.engineThreads)
|
.putInt("engineThreads", p.engineThreads)
|
||||||
.putInt("engineHashMb", p.engineHashMb)
|
.putInt("engineHashMb", p.engineHashMb)
|
||||||
|
.putInt("reviewQuality", p.reviewQuality)
|
||||||
.putLong("reviewNps", p.reviewNps)
|
.putLong("reviewNps", p.reviewNps)
|
||||||
.putString("opponent", p.opponent.key)
|
.putString("opponent", p.opponent.key)
|
||||||
.putInt("maiaStrength", p.maiaStrength)
|
.putInt("maiaStrength", p.maiaStrength)
|
||||||
|
|
|
||||||
|
|
@ -54,24 +54,24 @@ val DarkChess = LightChess.copy(
|
||||||
comment = Color(0xFF9EC4E0),
|
comment = Color(0xFF9EC4E0),
|
||||||
)
|
)
|
||||||
|
|
||||||
/// Move assessments in the owner's palette (chess.com's), as on the desktop. On a light
|
/// Move assessments in the colors of Lichess (as on the desktop). On a light background
|
||||||
/// background they are darkened to stay readable (contrast at least 4.5:1).
|
/// they are darkened to stay readable (contrast at least 4.5:1).
|
||||||
fun nagColor(nag: Int, dark: Boolean): Color? = if (dark) {
|
fun nagColor(nag: Int, dark: Boolean): Color? = if (dark) {
|
||||||
when (nag) {
|
when (nag) {
|
||||||
1 -> Color(0xFF81B64C) // !
|
1 -> Color(0xFF629C2E) // !
|
||||||
2 -> Color(0xFFFFA459) // ?
|
2 -> Color(0xFFE68F00) // ?
|
||||||
3 -> Color(0xFF26C2A3) // !!
|
3 -> Color(0xFF22AC9A) // !!
|
||||||
4 -> Color(0xFFFA412D) // ??
|
4 -> Color(0xFFDF5353) // ??
|
||||||
5 -> Color(0xFFEA45D8) // !?
|
5 -> Color(0xFFEA45D8) // !?
|
||||||
6 -> Color(0xFF56B4E9) // ?! (Lichess blue)
|
6 -> Color(0xFF56B4E9) // ?!
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
when (nag) {
|
when (nag) {
|
||||||
1 -> Color(0xFF5B8135)
|
1 -> Color(0xFF4E7F22)
|
||||||
2 -> Color(0xFFC25700)
|
2 -> Color(0xFFA35F00)
|
||||||
3 -> Color(0xFF1A846F)
|
3 -> Color(0xFF12806F)
|
||||||
4 -> Color(0xFFD2301C)
|
4 -> Color(0xFFC23B3B)
|
||||||
5 -> Color(0xFFB0259F)
|
5 -> Color(0xFFB0259F)
|
||||||
6 -> Color(0xFF1F72A8)
|
6 -> Color(0xFF1F72A8)
|
||||||
else -> null
|
else -> null
|
||||||
|
|
|
||||||
|
|
@ -84,14 +84,11 @@ fun AboutScreen(onBack: () -> Unit) {
|
||||||
Spacer(Modifier.height(16.dp))
|
Spacer(Modifier.height(16.dp))
|
||||||
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleLarge)
|
Text(stringResource(R.string.app_name), style = MaterialTheme.typography.titleLarge)
|
||||||
val build = stringResource(if (BuildConfig.NET_BUILT_IN) R.string.build_full else R.string.build_light)
|
val build = stringResource(if (BuildConfig.NET_BUILT_IN) R.string.build_full else R.string.build_light)
|
||||||
Text("${BuildConfig.VERSION_NAME} · $build", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
Text("${BuildConfig.VERSION_NAME} ${stringResource(R.string.alpha)} · $build", color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(24.dp))
|
||||||
// Right under the version (android-ui.md §25.5); a store's build is updated by
|
// Right under the version (android-ui.md §25.5).
|
||||||
// the store.
|
|
||||||
if (BuildConfig.SELF_UPDATE) {
|
|
||||||
AboutUpdates()
|
AboutUpdates()
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(24.dp))
|
||||||
}
|
|
||||||
Text(stringResource(R.string.about_text), style = MaterialTheme.typography.bodyLarge)
|
Text(stringResource(R.string.about_text), style = MaterialTheme.typography.bodyLarge)
|
||||||
TextButton(onClick = { uri.openUri(SITE) }, contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)) {
|
TextButton(onClick = { uri.openUri(SITE) }, contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp)) {
|
||||||
Text(stringResource(R.string.website))
|
Text(stringResource(R.string.website))
|
||||||
|
|
|
||||||
|
|
@ -36,9 +36,7 @@ import androidx.compose.ui.platform.LocalViewConfiguration
|
||||||
import androidx.compose.ui.layout.onSizeChanged
|
import androidx.compose.ui.layout.onSizeChanged
|
||||||
import androidx.compose.ui.platform.LocalContext
|
import androidx.compose.ui.platform.LocalContext
|
||||||
import androidx.compose.ui.platform.LocalDensity
|
import androidx.compose.ui.platform.LocalDensity
|
||||||
import androidx.compose.ui.semantics.CustomAccessibilityAction
|
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
import androidx.compose.ui.semantics.customActions
|
|
||||||
import androidx.compose.ui.semantics.semantics
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.ui.text.TextStyle
|
import androidx.compose.ui.text.TextStyle
|
||||||
import androidx.compose.ui.text.drawText
|
import androidx.compose.ui.text.drawText
|
||||||
|
|
@ -155,22 +153,9 @@ class BoardInput(
|
||||||
/// An arrow on the board: a comment's `[%cal]` or the engine's best move.
|
/// 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)
|
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.
|
/// A marked square of a comment (`[%csl]`), drawn as a ring.
|
||||||
data class BoardMark(val square: String, val color: Color)
|
data class BoardMark(val square: String, val color: Color)
|
||||||
|
|
||||||
/// A round label over the corner of the square a move went to: the move's assessment
|
|
||||||
/// (`!!`, `?`, …) or the review's judgement, as on the desktop (board.rs `Badge`).
|
|
||||||
data class BoardBadge(val square: String, val text: String, val color: Color)
|
|
||||||
|
|
||||||
/// The comment colors of the desktop app (game_view.rs `shape_color`).
|
/// The comment colors of the desktop app (game_view.rs `shape_color`).
|
||||||
fun markColor(letter: String): Color = when (letter) {
|
fun markColor(letter: String): Color = when (letter) {
|
||||||
"R" -> Color(136, 32, 32, 170)
|
"R" -> Color(136, 32, 32, 170)
|
||||||
|
|
@ -183,56 +168,6 @@ fun markColor(letter: String): Color = when (letter) {
|
||||||
/// The engine's arrows are blue, as on the desktop.
|
/// The engine's arrows are blue, as on the desktop.
|
||||||
val EngineArrow = Color(0, 48, 136, 160)
|
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<BoardArrowMove>,
|
|
||||||
headRadius: Float,
|
|
||||||
): List<BoardArrowMove> {
|
|
||||||
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
|
/// 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
|
/// 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);
|
/// tapping a piece and then a square, or by dragging it (android-play.md §29.2–29.3);
|
||||||
|
|
@ -249,8 +184,6 @@ fun Board(
|
||||||
description: String,
|
description: String,
|
||||||
modifier: Modifier = Modifier,
|
modifier: Modifier = Modifier,
|
||||||
arrows: List<BoardArrow> = emptyList(),
|
arrows: List<BoardArrow> = emptyList(),
|
||||||
arrowMoves: List<BoardArrowMove> = emptyList(),
|
|
||||||
onArrowMoves: (List<String>) -> Unit = {},
|
|
||||||
marks: List<BoardMark> = emptyList(),
|
marks: List<BoardMark> = emptyList(),
|
||||||
check: Boolean = false,
|
check: Boolean = false,
|
||||||
animated: Boolean = true,
|
animated: Boolean = true,
|
||||||
|
|
@ -259,7 +192,6 @@ fun Board(
|
||||||
alert: Pair<String, String>? = null,
|
alert: Pair<String, String>? = null,
|
||||||
/// The files and ranks along the edges (none on a small board that only shows).
|
/// The files and ranks along the edges (none on a small board that only shows).
|
||||||
coordinates: Boolean = true,
|
coordinates: Boolean = true,
|
||||||
badge: BoardBadge? = null,
|
|
||||||
) {
|
) {
|
||||||
val colors = LocalChessColors.current
|
val colors = LocalChessColors.current
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
@ -295,8 +227,6 @@ fun Board(
|
||||||
var dragAt by remember(fen) { mutableStateOf<Offset?>(null) }
|
var dragAt by remember(fen) { mutableStateOf<Offset?>(null) }
|
||||||
val slop = LocalViewConfiguration.current.touchSlop
|
val slop = LocalViewConfiguration.current.touchSlop
|
||||||
val currentInput = androidx.compose.runtime.rememberUpdatedState(input)
|
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() }
|
val lift = with(density) { 22.dp.toPx() }
|
||||||
fun indexAt(p: Offset, sq: Float): Int? {
|
fun indexAt(p: Offset, sq: Float): Int? {
|
||||||
val col = (p.x / sq).toInt()
|
val col = (p.x / sq).toInt()
|
||||||
|
|
@ -313,8 +243,7 @@ fun Board(
|
||||||
val startName = squareName(start)
|
val startName = squareName(start)
|
||||||
val movable = inp.targets(startName).isNotEmpty()
|
val movable = inp.targets(startName).isNotEmpty()
|
||||||
val was = selected
|
val was = selected
|
||||||
// A tap on a target of the piece chosen makes the move. An already chosen
|
// A tap on a target of the piece chosen makes the move.
|
||||||
// piece always has priority over continuation arrows.
|
|
||||||
if (was != null && start != was) {
|
if (was != null && start != was) {
|
||||||
inp.move(squareName(was), startName)?.let { m ->
|
inp.move(squareName(was), startName)?.let { m ->
|
||||||
selected = null
|
selected = null
|
||||||
|
|
@ -323,7 +252,6 @@ fun Board(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (movable) selected = start
|
if (movable) selected = start
|
||||||
val shortcutCandidate = was == null && !movable
|
|
||||||
var dragging = false
|
var dragging = false
|
||||||
while (true) {
|
while (true) {
|
||||||
val e = awaitPointerEvent()
|
val e = awaitPointerEvent()
|
||||||
|
|
@ -338,29 +266,17 @@ fun Board(
|
||||||
inp.onMove(m)
|
inp.onMove(m)
|
||||||
}
|
}
|
||||||
// A drop elsewhere: the piece goes back, still chosen.
|
// A drop elsewhere: the piece goes back, still chosen.
|
||||||
} else {
|
} else if (!movable || start == was) {
|
||||||
if (!movable || start == was) {
|
|
||||||
// A tap on the same piece, an empty square or the other side's
|
// A tap on the same piece, an empty square or the other side's
|
||||||
// piece: nothing chosen any more.
|
// piece: nothing chosen any more.
|
||||||
selected = null
|
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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.consume()
|
c.consume()
|
||||||
break
|
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 (dragging) {
|
||||||
if (movable) dragAt = c.position
|
dragAt = c.position
|
||||||
c.consume()
|
c.consume()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -371,21 +287,16 @@ fun Board(
|
||||||
.aspectRatio(1f)
|
.aspectRatio(1f)
|
||||||
.onSizeChanged { side = it.width }
|
.onSizeChanged { side = it.width }
|
||||||
.then(touch)
|
.then(touch)
|
||||||
.semantics {
|
.semantics { contentDescription = description },
|
||||||
contentDescription = description
|
|
||||||
if (arrowMoves.isNotEmpty()) {
|
|
||||||
customActions = arrowMoves.map { move ->
|
|
||||||
CustomAccessibilityAction(move.actionLabel) {
|
|
||||||
onArrowMoves(listOf(move.uci))
|
|
||||||
true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
) {
|
) {
|
||||||
val sq = size.width / 8f
|
val sq = size.width / 8f
|
||||||
val px = sq.toInt()
|
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
|
val image = texture
|
||||||
if (image != null) {
|
if (image != null) {
|
||||||
// The squares of the image are the same seen from either side: it is not turned.
|
// The squares of the image are the same seen from either side: it is not turned.
|
||||||
|
|
@ -478,25 +389,6 @@ fun Board(
|
||||||
val t = squareIndex(a.to) ?: continue
|
val t = squareIndex(a.to) ?: continue
|
||||||
drawArrow(cell(f) + Offset(sq / 2, sq / 2), cell(t) + Offset(sq / 2, sq / 2), sq, a)
|
drawArrow(cell(f) + Offset(sq / 2, sq / 2), cell(t) + Offset(sq / 2, sq / 2), sq, a)
|
||||||
}
|
}
|
||||||
badge?.let { b ->
|
|
||||||
val i = squareIndex(b.square) ?: return@let
|
|
||||||
val c = cell(i)
|
|
||||||
// Readable on a small board too (a split screen).
|
|
||||||
val r = maxOf(sq * 0.21f, with(density) { 9.dp.toPx() })
|
|
||||||
// Over the corner of the square, kept inside the board.
|
|
||||||
val center = Offset(
|
|
||||||
(c.x + sq - r * 0.35f).coerceAtMost(size.width - r - 1f),
|
|
||||||
(c.y + r * 0.35f).coerceAtLeast(r + 1f),
|
|
||||||
)
|
|
||||||
drawCircle(Color(0, 0, 0, 90), r, center + Offset(0f, sq * 0.015f))
|
|
||||||
drawCircle(b.color, r, center)
|
|
||||||
drawCircle(Color.White, r, center, style = Stroke(width = sq * 0.025f))
|
|
||||||
val label = measurer.measure(
|
|
||||||
b.text,
|
|
||||||
TextStyle(color = Color.White, fontWeight = FontWeight.Black, fontSize = with(density) { (r * 1.05f).toSp() }),
|
|
||||||
)
|
|
||||||
drawText(label, topLeft = center - Offset(label.size.width / 2f, label.size.height / 2f))
|
|
||||||
}
|
|
||||||
// The dragged piece: bigger and lifted above the finger, a shade on the square
|
// The dragged piece: bigger and lifted above the finger, a shade on the square
|
||||||
// under it so that one sees where it goes.
|
// under it so that one sees where it goes.
|
||||||
val held = dragAt
|
val held = dragAt
|
||||||
|
|
@ -514,17 +406,22 @@ fun Board(
|
||||||
/// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops
|
/// An arrow as on the desktop (board.rs `draw_arrow`): a shaft and a head that stops
|
||||||
/// short of the square's center.
|
/// short of the square's center.
|
||||||
private fun DrawScope.drawArrow(from: Offset, to: Offset, sq: Float, a: BoardArrow) {
|
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 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 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 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)
|
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 {
|
val head = Path().apply {
|
||||||
moveTo(geometry.tip.x, geometry.tip.y)
|
moveTo(tip.x, tip.y)
|
||||||
lineTo(geometry.base.x + normal.x * headW, geometry.base.y + normal.y * headW)
|
lineTo(base.x + normal.x * headW, base.y + normal.y * headW)
|
||||||
lineTo(geometry.base.x - normal.x * headW, geometry.base.y - normal.y * headW)
|
lineTo(base.x - normal.x * headW, base.y - normal.y * headW)
|
||||||
close()
|
close()
|
||||||
}
|
}
|
||||||
drawPath(head, a.color)
|
drawPath(head, a.color)
|
||||||
|
|
|
||||||
|
|
@ -224,7 +224,9 @@ fun DatabasesScreen(onOpen: (String) -> Unit, onAdded: (DbEntry) -> Unit, onSett
|
||||||
}
|
}
|
||||||
val scroll = TopAppBarDefaults.pinnedScrollBehavior()
|
val scroll = TopAppBarDefaults.pinnedScrollBehavior()
|
||||||
// The samples are small: read them at once, so their rows show the number of games.
|
// 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(
|
Scaffold(
|
||||||
modifier = Modifier.nestedScroll(scroll.nestedScrollConnection),
|
modifier = Modifier.nestedScroll(scroll.nestedScrollConnection),
|
||||||
|
|
@ -813,8 +815,6 @@ private fun pastedName(db: Database, dated: String): String {
|
||||||
fun finishedText(res: android.content.res.Resources, f: Finished): String? {
|
fun finishedText(res: android.content.res.Resources, f: Finished): String? {
|
||||||
val s = f.view.state
|
val s = f.view.state
|
||||||
val games = res.getQuantityString(R.plurals.games_count, f.games, groupDigits(f.games))
|
val games = res.getQuantityString(R.plurals.games_count, f.games, groupDigits(f.games))
|
||||||
// An update of its own speaks only of new games.
|
|
||||||
if (f.quiet && (s.failure != null || s.added == 0UL)) return null
|
|
||||||
s.failure?.let { return res.getString(R.string.online_snack_failed, f.name, problemShort(res, it)) }
|
s.failure?.let { return res.getString(R.string.online_snack_failed, f.name, problemShort(res, it)) }
|
||||||
return when {
|
return when {
|
||||||
s.cancelled || f.games == 0 -> null
|
s.cancelled || f.games == 0 -> 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
|
|
||||||
}
|
|
||||||
|
|
@ -5,20 +5,19 @@ import android.content.res.Configuration
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.view.HapticFeedbackConstants
|
import android.view.HapticFeedbackConstants
|
||||||
import androidx.activity.compose.BackHandler
|
import androidx.activity.compose.BackHandler
|
||||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
|
||||||
import androidx.compose.foundation.background
|
import androidx.compose.foundation.background
|
||||||
import androidx.compose.foundation.clickable
|
import androidx.compose.foundation.clickable
|
||||||
import androidx.compose.foundation.combinedClickable
|
|
||||||
import androidx.compose.foundation.layout.heightIn
|
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.verticalScroll
|
||||||
import androidx.compose.foundation.gestures.detectTapGestures
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
import androidx.compose.foundation.horizontalScroll
|
import androidx.compose.foundation.horizontalScroll
|
||||||
import androidx.compose.foundation.layout.Arrangement
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
import androidx.compose.foundation.layout.Box
|
import androidx.compose.foundation.layout.Box
|
||||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
|
||||||
import androidx.compose.foundation.layout.Column
|
import androidx.compose.foundation.layout.Column
|
||||||
import androidx.compose.foundation.layout.Row
|
import androidx.compose.foundation.layout.Row
|
||||||
import androidx.compose.foundation.layout.Spacer
|
|
||||||
import androidx.compose.foundation.layout.WindowInsets
|
import androidx.compose.foundation.layout.WindowInsets
|
||||||
import androidx.compose.foundation.layout.WindowInsetsSides
|
import androidx.compose.foundation.layout.WindowInsetsSides
|
||||||
import androidx.compose.foundation.layout.navigationBars
|
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.layout.width
|
||||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||||
import androidx.compose.foundation.rememberScrollState
|
import androidx.compose.foundation.rememberScrollState
|
||||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
|
||||||
import androidx.compose.material.icons.Icons
|
import androidx.compose.material.icons.Icons
|
||||||
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
|
||||||
import androidx.compose.material.icons.outlined.Memory
|
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.VerticalAlignTop
|
||||||
import androidx.compose.material.icons.rounded.ChevronRight
|
import androidx.compose.material.icons.rounded.ChevronRight
|
||||||
import androidx.compose.material.icons.rounded.Download
|
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.Memory
|
||||||
import androidx.compose.material.icons.rounded.MoreVert
|
import androidx.compose.material.icons.rounded.MoreVert
|
||||||
import androidx.compose.material.icons.rounded.PlayArrow
|
import androidx.compose.material.icons.rounded.PlayArrow
|
||||||
import androidx.compose.material.icons.rounded.QueryStats
|
|
||||||
import androidx.compose.material.icons.rounded.SwapVert
|
import androidx.compose.material.icons.rounded.SwapVert
|
||||||
import androidx.compose.material3.AlertDialog
|
import androidx.compose.material3.AlertDialog
|
||||||
import androidx.compose.material3.CircularProgressIndicator
|
import androidx.compose.material3.CircularProgressIndicator
|
||||||
|
|
@ -71,6 +70,7 @@ import androidx.compose.material3.Surface
|
||||||
import androidx.compose.material3.Text
|
import androidx.compose.material3.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.material3.TopAppBar
|
import androidx.compose.material3.TopAppBar
|
||||||
|
import androidx.compose.material3.ripple
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.DisposableEffect
|
import androidx.compose.runtime.DisposableEffect
|
||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
|
@ -85,7 +85,6 @@ import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
import androidx.compose.ui.Modifier
|
import androidx.compose.ui.Modifier
|
||||||
import androidx.compose.ui.draw.clip
|
|
||||||
import androidx.compose.ui.draw.scale
|
import androidx.compose.ui.draw.scale
|
||||||
import androidx.compose.ui.graphics.Color
|
import androidx.compose.ui.graphics.Color
|
||||||
import androidx.compose.ui.graphics.vector.ImageVector
|
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.platform.LocalView
|
||||||
import androidx.compose.ui.res.pluralStringResource
|
import androidx.compose.ui.res.pluralStringResource
|
||||||
import androidx.compose.ui.res.stringResource
|
import androidx.compose.ui.res.stringResource
|
||||||
import androidx.compose.ui.semantics.CustomAccessibilityAction
|
|
||||||
import androidx.compose.ui.semantics.Role
|
import androidx.compose.ui.semantics.Role
|
||||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
|
||||||
import androidx.compose.ui.semantics.contentDescription
|
import androidx.compose.ui.semantics.contentDescription
|
||||||
import androidx.compose.ui.semantics.customActions
|
|
||||||
import androidx.compose.ui.semantics.disabled
|
import androidx.compose.ui.semantics.disabled
|
||||||
import androidx.compose.ui.semantics.onClick
|
import androidx.compose.ui.semantics.onClick
|
||||||
import androidx.compose.ui.semantics.onLongClick
|
|
||||||
import androidx.compose.ui.semantics.role
|
import androidx.compose.ui.semantics.role
|
||||||
import androidx.compose.ui.semantics.semantics
|
import androidx.compose.ui.semantics.semantics
|
||||||
import androidx.compose.ui.semantics.stateDescription
|
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.EngineSession
|
||||||
import io.github.vrubelroman.chesspenguin.data.NetState
|
import io.github.vrubelroman.chesspenguin.data.NetState
|
||||||
import io.github.vrubelroman.chesspenguin.data.Opponent
|
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.ReviewSession
|
||||||
import io.github.vrubelroman.chesspenguin.data.enginePosition
|
import io.github.vrubelroman.chesspenguin.data.enginePosition
|
||||||
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
|
import io.github.vrubelroman.chesspenguin.theme.LocalChessColors
|
||||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.coroutineScope
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
|
|
@ -131,7 +128,6 @@ import uniffi.mobile_api.EngineLine
|
||||||
import uniffi.mobile_api.Edited
|
import uniffi.mobile_api.Edited
|
||||||
import uniffi.mobile_api.GameData
|
import uniffi.mobile_api.GameData
|
||||||
import uniffi.mobile_api.GameSession
|
import uniffi.mobile_api.GameSession
|
||||||
import io.github.vrubelroman.chesspenguin.theme.nagColor
|
|
||||||
import uniffi.mobile_api.MoveJudgement
|
import uniffi.mobile_api.MoveJudgement
|
||||||
import uniffi.mobile_api.MoveNode
|
import uniffi.mobile_api.MoveNode
|
||||||
|
|
||||||
|
|
@ -151,7 +147,6 @@ fun GameScreen(
|
||||||
onSettings: () -> Unit,
|
onSettings: () -> Unit,
|
||||||
onPlayGame: () -> Unit = {},
|
onPlayGame: () -> Unit = {},
|
||||||
onOpenDatabase: (String) -> Unit = {},
|
onOpenDatabase: (String) -> Unit = {},
|
||||||
onPrepare: (PrepStart) -> Unit = {},
|
|
||||||
) {
|
) {
|
||||||
val app = app()
|
val app = app()
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
|
|
@ -300,7 +295,6 @@ fun GameScreen(
|
||||||
val reviewCycle = remember(place) { HashMap<Pair<Boolean, MoveJudgement>, Int>() }
|
val reviewCycle = remember(place) { HashMap<Pair<Boolean, MoveJudgement>, Int>() }
|
||||||
var menu by remember { mutableStateOf(false) }
|
var menu by remember { mutableStateOf(false) }
|
||||||
var info by remember { mutableStateOf(false) }
|
var info by remember { mutableStateOf(false) }
|
||||||
var prepSheet by remember(place) { mutableStateOf(false) }
|
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current
|
val clipboard = androidx.compose.ui.platform.LocalClipboardManager.current
|
||||||
val pgnCopied = stringResource(R.string.pgn_copied)
|
val pgnCopied = stringResource(R.string.pgn_copied)
|
||||||
|
|
@ -337,9 +331,6 @@ fun GameScreen(
|
||||||
// The player bars above and below the board (§7.11); the top bar names the event.
|
// 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 whiteName = tag("White").trim().takeIf { it.isNotEmpty() && it != "?" }
|
||||||
val blackName = tag("Black").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 whiteLabel = stringResource(R.string.tag_white)
|
||||||
val blackLabel = stringResource(R.string.tag_black)
|
val blackLabel = stringResource(R.string.tag_black)
|
||||||
val resultText = g?.let { resultLine(context, it.result) } ?: ""
|
val resultText = g?.let { resultLine(context, it.result) } ?: ""
|
||||||
|
|
@ -392,8 +383,9 @@ fun GameScreen(
|
||||||
}
|
}
|
||||||
wantReview = null
|
wantReview = null
|
||||||
reviewHidden = false
|
reviewHidden = false
|
||||||
review.start(files.executable, files.net.path, full) { s ->
|
val p = app.settings.prefs.value
|
||||||
if (s.npsPerProcess > 0UL) app.settings.update { it.copy(reviewNps = s.npsPerProcess.toLong()) }
|
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.
|
// The engine became ready for an analysis that was asked for.
|
||||||
|
|
@ -439,24 +431,6 @@ fun GameScreen(
|
||||||
val reviewMarks = remember(rs) { rs?.moves?.associate { it.node.toInt() to it.judgement } ?: emptyMap() }
|
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
|
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) {
|
fun buzz(edge: Boolean) {
|
||||||
if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK)
|
if (prefs.vibration) view.performHapticFeedback(if (edge) HapticFeedbackConstants.CONFIRM else HapticFeedbackConstants.CLOCK_TICK)
|
||||||
}
|
}
|
||||||
|
|
@ -810,13 +784,6 @@ fun GameScreen(
|
||||||
fun forward() {
|
fun forward() {
|
||||||
if (preview != null) stepPreview(1) else node?.children?.firstOrNull()?.let { go(it.toInt()) }
|
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() {
|
fun end() {
|
||||||
preview?.let {
|
preview?.let {
|
||||||
preview = it.copy(step = it.line.steps.size - 1)
|
preview = it.copy(step = it.line.steps.size - 1)
|
||||||
|
|
@ -890,62 +857,24 @@ fun GameScreen(
|
||||||
}
|
}
|
||||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||||
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
Surface(color = MaterialTheme.colorScheme.surfaceContainer) {
|
||||||
BoxWithConstraints(Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp)) {
|
Row(
|
||||||
val compact = maxWidth < 320.dp
|
Modifier.fillMaxWidth().navigationBarsPadding().height(72.dp),
|
||||||
val narrow = maxWidth < 360.dp
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
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(
|
EngineButton(
|
||||||
on = engineOn,
|
on = engineOn,
|
||||||
needsDownload = !engineReady && !files.builtIn,
|
needsDownload = !engineReady && !files.builtIn,
|
||||||
loading = netState as? NetState.Loading,
|
loading = netState as? NetState.Loading,
|
||||||
modifier = Modifier.weight(engineSlot),
|
modifier = Modifier.weight(1.2f),
|
||||||
onClick = ::toggleEngine,
|
onClick = ::toggleEngine,
|
||||||
)
|
)
|
||||||
BarButton(Icons.Rounded.SwapVert, stringResource(R.string.flip), true, Modifier.weight(48f)) { flipped = !flipped }
|
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)) {
|
||||||
BarButton(
|
if (preview != null) preview = null else go(0)
|
||||||
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,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
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() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -958,8 +887,7 @@ fun GameScreen(
|
||||||
val description = when {
|
val description = when {
|
||||||
step != null -> stringResource(R.string.board_description, step.label)
|
step != null -> stringResource(R.string.board_description, step.label)
|
||||||
node == null || current == 0 -> stringResource(R.string.board_start)
|
node == null || current == 0 -> stringResource(R.string.board_start)
|
||||||
else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san + node.nagSymbols) +
|
else -> stringResource(R.string.board_description, (if (node.white) "${node.moveNumber}." else "${node.moveNumber}…") + node.san)
|
||||||
(currentMark?.let { ", " + judgementName(it.judgement) } ?: "")
|
|
||||||
}
|
}
|
||||||
val arrows = buildList {
|
val arrows = buildList {
|
||||||
if (p != null) {
|
if (p != null) {
|
||||||
|
|
@ -979,24 +907,12 @@ fun GameScreen(
|
||||||
if (f != null && t != null) {
|
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))
|
add(BoardArrow(f, t, EngineArrow.copy(alpha = if (i == 0) 0.63f else 0.35f), if (i == 0) 1f else 0.7f))
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val marks = if (p == null) node?.marks?.filter { it.to == null }?.map { BoardMark(it.from, markColor(it.color)) }.orEmpty() else emptyList()
|
val marks = if (p == null) node?.marks?.filter { it.to == null }?.map { BoardMark(it.from, markColor(it.color)) }.orEmpty() else emptyList()
|
||||||
val check = (step?.label ?: node?.san ?: "").let { it.endsWith("+") || it.endsWith("#") }
|
val check = (step?.label ?: node?.san ?: "").let { it.endsWith("+") || it.endsWith("#") }
|
||||||
// The review's judgement of the move, else the move's own assessment in the game.
|
|
||||||
// The bright colors of the dark theme on every board, as on the desktop.
|
|
||||||
val badge = node?.toSquare?.takeIf { p == null }?.let { to ->
|
|
||||||
currentMark?.let { BoardBadge(to, judgementSymbol(it.judgement), judgementColor(it.judgement, true)) }
|
|
||||||
?: node.nags.asList().firstNotNullOfOrNull { b ->
|
|
||||||
val n = b.toInt() and 0xFF
|
|
||||||
val sym = assessmentSymbol(n)
|
|
||||||
val c = nagColor(n, true)
|
|
||||||
if (sym != null && c != null) BoardBadge(to, sym, c) else null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Board(
|
Board(
|
||||||
fen = fen,
|
fen = fen,
|
||||||
flipped = flipped,
|
flipped = flipped,
|
||||||
|
|
@ -1008,7 +924,6 @@ fun GameScreen(
|
||||||
description = description,
|
description = description,
|
||||||
arrows = arrows,
|
arrows = arrows,
|
||||||
marks = marks,
|
marks = marks,
|
||||||
badge = badge,
|
|
||||||
check = check,
|
check = check,
|
||||||
animated = prefs.animation,
|
animated = prefs.animation,
|
||||||
// A touch during a preview of an engine line closes it; no move is made (§29.5).
|
// A touch during a preview of an engine line closes it; no move is made (§29.5).
|
||||||
|
|
@ -1249,32 +1164,32 @@ fun GameScreen(
|
||||||
undo()
|
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 = {
|
DropdownMenuItem(text = { Text(stringResource(R.string.game_info)) }, enabled = g != null, onClick = {
|
||||||
menu = false
|
menu = false
|
||||||
info = true
|
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 = {
|
DropdownMenuItem(text = { Text(stringResource(R.string.copy_pgn)) }, enabled = g != null, onClick = {
|
||||||
menu = false
|
menu = false
|
||||||
scope.launch {
|
scope.launch {
|
||||||
|
|
@ -1363,42 +1278,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) {
|
if (info && g != null) {
|
||||||
AlertDialog(
|
AlertDialog(
|
||||||
onDismissRequest = { info = false },
|
onDismissRequest = { info = false },
|
||||||
|
|
@ -1640,7 +1519,10 @@ fun GameScreen(
|
||||||
if (reviewStart) {
|
if (reviewStart) {
|
||||||
ReviewStartSheet(
|
ReviewStartSheet(
|
||||||
state = rs,
|
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 ->
|
onStart = { full ->
|
||||||
reviewStart = false
|
reviewStart = false
|
||||||
startReview(full)
|
startReview(full)
|
||||||
|
|
@ -1726,92 +1608,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<Int, Int>? = 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.
|
/// The row of continuations at a fork (§7.5): the line's own move first and filled.
|
||||||
@Composable
|
@Composable
|
||||||
private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) {
|
private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMove: (Int) -> Unit) {
|
||||||
|
|
@ -1831,50 +1627,57 @@ private fun Forks(moves: List<MoveNode>, san: (String) -> AnnotatedString, onMov
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A button of the bottom bar. A tap is one action; an optional long press is a separate
|
/// A button of the bottom bar. With `repeat`, holding it steps again after 400 ms and
|
||||||
/// action, never an auto-repeat. Long-press is also an accessibility custom action.
|
/// then every 120 ms (§7.4).
|
||||||
@OptIn(ExperimentalFoundationApi::class)
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun BarButton(
|
private fun BarButton(
|
||||||
icon: ImageVector,
|
icon: ImageVector,
|
||||||
label: String,
|
label: String,
|
||||||
enabled: Boolean,
|
enabled: Boolean,
|
||||||
modifier: Modifier,
|
modifier: Modifier,
|
||||||
iconSize: Int = 24,
|
iconSize: Int = 24,
|
||||||
|
repeat: Boolean = false,
|
||||||
mirrored: Boolean = false,
|
mirrored: Boolean = false,
|
||||||
description: String = label,
|
|
||||||
onLongClickLabel: String? = null,
|
|
||||||
onLongClick: (() -> Unit)? = null,
|
|
||||||
onClick: () -> Unit,
|
onClick: () -> Unit,
|
||||||
) {
|
) {
|
||||||
val color = if (enabled) LocalContentColor.current else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
|
|
||||||
val action by rememberUpdatedState(onClick)
|
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(
|
Box(
|
||||||
modifier
|
modifier
|
||||||
.fillMaxHeight()
|
.fillMaxHeight()
|
||||||
.clearAndSetSemantics {
|
.semantics {
|
||||||
contentDescription = description
|
contentDescription = label
|
||||||
role = Role.Button
|
role = Role.Button
|
||||||
if (enabled) {
|
if (!enabled) disabled()
|
||||||
onClick(label) { action(); true }
|
onClick { action(); true }
|
||||||
if (onLongClickLabel != null && longAction != null) {
|
}
|
||||||
onLongClick(onLongClickLabel) { longAction?.invoke(); true }
|
.indication(interaction, ripple(bounded = false, radius = 32.dp))
|
||||||
customActions = listOf(CustomAccessibilityAction(onLongClickLabel) { longAction?.invoke(); true })
|
.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 {
|
} else {
|
||||||
disabled()
|
null
|
||||||
}
|
}
|
||||||
|
tryAwaitRelease()
|
||||||
|
job?.cancel()
|
||||||
}
|
}
|
||||||
.combinedClickable(
|
interaction.emit(PressInteraction.Release(press))
|
||||||
enabled = enabled,
|
})
|
||||||
onClickLabel = label,
|
},
|
||||||
role = Role.Button,
|
|
||||||
onLongClickLabel = onLongClickLabel,
|
|
||||||
onLongClick = onLongClick,
|
|
||||||
hapticFeedbackEnabled = false,
|
|
||||||
onClick = onClick,
|
|
||||||
),
|
|
||||||
contentAlignment = Alignment.Center,
|
contentAlignment = Alignment.Center,
|
||||||
) {
|
) {
|
||||||
Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier))
|
Icon(icon, null, tint = color, modifier = Modifier.size(iconSize.dp).then(if (mirrored) Modifier.scale(-1f, 1f) else Modifier))
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,6 @@ import androidx.compose.material3.SnackbarHostState
|
||||||
import androidx.compose.material3.SnackbarHost
|
import androidx.compose.material3.SnackbarHost
|
||||||
import androidx.compose.material3.LinearProgressIndicator
|
import androidx.compose.material3.LinearProgressIndicator
|
||||||
import androidx.compose.material.icons.rounded.Download
|
import androidx.compose.material.icons.rounded.Download
|
||||||
import androidx.compose.material.icons.rounded.Groups
|
|
||||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.delay
|
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).
|
/// The games of a database, with a search (android-ui.md §6).
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun GamesScreen(
|
fun GamesScreen(db: String, onBack: () -> Unit, onGame: (place: Int, query: String) -> Unit) {
|
||||||
db: String,
|
|
||||||
onBack: () -> Unit,
|
|
||||||
onGame: (place: Int, query: String) -> Unit,
|
|
||||||
onPlayers: () -> Unit = {},
|
|
||||||
) {
|
|
||||||
val app = app()
|
val app = app()
|
||||||
val entries by app.library.entries.collectAsState()
|
val entries by app.library.entries.collectAsState()
|
||||||
val entry = entries.firstOrNull { it.id == db }
|
val entry = entries.firstOrNull { it.id == db }
|
||||||
|
|
@ -202,7 +196,6 @@ fun GamesScreen(
|
||||||
if (query.isEmpty()) searching = false else query = ""
|
if (query.isEmpty()) searching = false else query = ""
|
||||||
}) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) }
|
}) { Icon(Icons.Rounded.Close, stringResource(R.string.clear)) }
|
||||||
} else if (database != null) {
|
} 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)) }
|
IconButton(onClick = { searching = true }) { Icon(Icons.Rounded.Search, stringResource(R.string.search)) }
|
||||||
// A downloaded database: its new games from here, where they are
|
// A downloaded database: its new games from here, where they are
|
||||||
// looked for (android-ui.md §23.3); ✕ while they come.
|
// looked for (android-ui.md §23.3); ✕ while they come.
|
||||||
|
|
|
||||||
|
|
@ -357,9 +357,9 @@ private fun MoveCell(
|
||||||
onLongMove: ((Int) -> Unit)?,
|
onLongMove: ((Int) -> Unit)?,
|
||||||
) {
|
) {
|
||||||
val selected = id != null && id == current
|
val selected = id != null && id == current
|
||||||
// The engine's mark stands right after the move, the move in its color (as on Lichess);
|
// The engine's mark is left out where the author already put the same sign ("Nf6? ?"
|
||||||
// where the author already gave the move a sign, the author's sign stands instead.
|
// reads as a typo, §21.4).
|
||||||
val mark = mark?.takeIf { id == null || game.nodes[id].nags.none { (it.toInt() and 0xFF) in 1..6 } }
|
val mark = mark?.takeIf { m -> id == null || game.nodes[id].nags.none { it.toInt() == judgementNag(m) } }
|
||||||
// TalkBack reads "4, White, dxe5", the engine's judgement, and whether it is the
|
// TalkBack reads "4, White, dxe5", the engine's judgement, and whether it is the
|
||||||
// current move.
|
// current move.
|
||||||
val markName = mark?.let { judgementName(it) }
|
val markName = mark?.let { judgementName(it) }
|
||||||
|
|
@ -411,16 +411,12 @@ private fun MoveCell(
|
||||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||||
horizontalArrangement = Arrangement.spacedBy(1.dp),
|
horizontalArrangement = Arrangement.spacedBy(1.dp),
|
||||||
) {
|
) {
|
||||||
val markColor = mark?.takeIf { !selected }?.let { judgementColor(it, chess.dark) }
|
Text(san(n.san), fontSize = 17.sp, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.onSurface)
|
||||||
Text(san(n.san), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = markColor ?: MaterialTheme.colorScheme.onSurface)
|
|
||||||
if (mark != null) {
|
|
||||||
Text(judgementSymbol(mark), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = markColor ?: MaterialTheme.colorScheme.onSurface)
|
|
||||||
}
|
|
||||||
if (n.nagSymbols.isNotEmpty()) {
|
if (n.nagSymbols.isNotEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
n.nagSymbols,
|
n.nagSymbols,
|
||||||
fontSize = 17.sp,
|
fontSize = 17.sp,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Medium,
|
||||||
color = if (selected) {
|
color = if (selected) {
|
||||||
MaterialTheme.colorScheme.onSurface
|
MaterialTheme.colorScheme.onSurface
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -429,6 +425,7 @@ private fun MoveCell(
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (mark != null) ReviewBadge(mark, Modifier.padding(start = 2.dp))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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<Database?>(null) }
|
|
||||||
var openFailure by remember { mutableStateOf<Throwable?>(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<PlayerSummary?>(null) }
|
|
||||||
var players by remember { mutableStateOf<List<PlayerSummary>?>(null) }
|
|
||||||
var nextOffset by remember { mutableStateOf<Int?>(null) }
|
|
||||||
var failure by remember { mutableStateOf<Throwable?>(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<PlayerSummary>): List<PlayerSummary> {
|
|
||||||
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()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -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<GameData?>(null)
|
|
||||||
private set
|
|
||||||
var position by mutableStateOf<PrepPosition?>(null)
|
|
||||||
private set
|
|
||||||
var failure by mutableStateOf<Throwable?>(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<String> = 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -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<String> = 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<PrepLineStep> = 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<String> 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<PrepLineStep>, 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<Int>()
|
|
||||||
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<Int>()
|
|
||||||
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<PlayerSummary>,
|
|
||||||
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<PrepContinuation>,
|
|
||||||
val endedHere: Int = 0,
|
|
||||||
val noNormalContinuation: Int = 0,
|
|
||||||
val unknownResults: Int = 0,
|
|
||||||
val playerToMove: Boolean? = null,
|
|
||||||
val matches: List<PrepGameMatch> = emptyList(),
|
|
||||||
val matchesTotal: Int = 0,
|
|
||||||
)
|
|
||||||
|
|
||||||
internal fun sortedContinuations(position: PrepPosition): List<PrepContinuation> =
|
|
||||||
position.continuations.sortedWith(compareByDescending<PrepContinuation> { 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<String, String, String> {
|
|
||||||
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")
|
|
||||||
|
|
@ -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<Database?>(null) }
|
|
||||||
var openFailure by remember { mutableStateOf<Throwable?>(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<List<String>>(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<String>) {
|
|
||||||
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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -35,6 +35,9 @@ import androidx.compose.material3.MaterialTheme
|
||||||
import androidx.compose.material3.ModalBottomSheet
|
import androidx.compose.material3.ModalBottomSheet
|
||||||
import androidx.compose.material3.rememberModalBottomSheetState
|
import androidx.compose.material3.rememberModalBottomSheetState
|
||||||
import androidx.compose.material3.OutlinedButton
|
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.Text
|
||||||
import androidx.compose.material3.TextButton
|
import androidx.compose.material3.TextButton
|
||||||
import androidx.compose.runtime.Composable
|
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.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import io.github.vrubelroman.chesspenguin.R
|
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.LocalChessColors
|
||||||
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
import io.github.vrubelroman.chesspenguin.theme.Tabular
|
||||||
import io.github.vrubelroman.chesspenguin.theme.nagColor
|
import io.github.vrubelroman.chesspenguin.theme.nagColor
|
||||||
|
|
@ -76,37 +80,23 @@ import uniffi.mobile_api.MoveJudgement
|
||||||
import uniffi.mobile_api.ReviewMove
|
import uniffi.mobile_api.ReviewMove
|
||||||
import uniffi.mobile_api.ReviewState
|
import uniffi.mobile_api.ReviewState
|
||||||
import uniffi.mobile_api.SideReview
|
import uniffi.mobile_api.SideReview
|
||||||
|
import kotlin.math.ceil
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
/// The NAG of the same sign: $3 !!, $1 !, $6 ?!, $2 ?, $4 ??.
|
/// The NAG of the same sign: $6 ?!, $2 ?, $4 ??.
|
||||||
fun judgementNag(j: MoveJudgement): Int = when (j) {
|
fun judgementNag(j: MoveJudgement): Int = when (j) {
|
||||||
MoveJudgement.INACCURACY -> 6
|
MoveJudgement.INACCURACY -> 6
|
||||||
MoveJudgement.MISTAKE -> 2
|
MoveJudgement.MISTAKE -> 2
|
||||||
MoveJudgement.BLUNDER -> 4
|
MoveJudgement.BLUNDER -> 4
|
||||||
MoveJudgement.GREAT -> 1
|
|
||||||
MoveJudgement.BRILLIANT -> 3
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The colors of the NAGs !!, !, ?!, ? and ?? (§21.4).
|
/// The colors of the NAGs ?!, ? and ?? (§21.4).
|
||||||
fun judgementColor(j: MoveJudgement, dark: Boolean): Color = nagColor(judgementNag(j), dark) ?: Color.Unspecified
|
fun judgementColor(j: MoveJudgement, dark: Boolean): Color = nagColor(judgementNag(j), dark) ?: Color.Unspecified
|
||||||
|
|
||||||
/// The sign of a move assessment NAG ($1–$6), `null` for others.
|
|
||||||
fun assessmentSymbol(nag: Int): String? = when (nag) {
|
|
||||||
1 -> "!"
|
|
||||||
2 -> "?"
|
|
||||||
3 -> "!!"
|
|
||||||
4 -> "??"
|
|
||||||
5 -> "!?"
|
|
||||||
6 -> "?!"
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
|
|
||||||
fun judgementSymbol(j: MoveJudgement): String = when (j) {
|
fun judgementSymbol(j: MoveJudgement): String = when (j) {
|
||||||
MoveJudgement.INACCURACY -> "?!"
|
MoveJudgement.INACCURACY -> "?!"
|
||||||
MoveJudgement.MISTAKE -> "?"
|
MoveJudgement.MISTAKE -> "?"
|
||||||
MoveJudgement.BLUNDER -> "??"
|
MoveJudgement.BLUNDER -> "??"
|
||||||
MoveJudgement.GREAT -> "!"
|
|
||||||
MoveJudgement.BRILLIANT -> "!!"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
|
|
@ -115,8 +105,6 @@ fun judgementName(j: MoveJudgement): String = stringResource(
|
||||||
MoveJudgement.INACCURACY -> R.string.review_inaccuracy
|
MoveJudgement.INACCURACY -> R.string.review_inaccuracy
|
||||||
MoveJudgement.MISTAKE -> R.string.review_mistake
|
MoveJudgement.MISTAKE -> R.string.review_mistake
|
||||||
MoveJudgement.BLUNDER -> R.string.review_blunder
|
MoveJudgement.BLUNDER -> R.string.review_blunder
|
||||||
MoveJudgement.GREAT -> R.string.review_great
|
|
||||||
MoveJudgement.BRILLIANT -> R.string.review_brilliant
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -126,11 +114,26 @@ private fun judgementPlural(j: MoveJudgement): String = stringResource(
|
||||||
MoveJudgement.INACCURACY -> R.string.review_inaccuracies
|
MoveJudgement.INACCURACY -> R.string.review_inaccuracies
|
||||||
MoveJudgement.MISTAKE -> R.string.review_mistakes
|
MoveJudgement.MISTAKE -> R.string.review_mistakes
|
||||||
MoveJudgement.BLUNDER -> R.string.review_blunders
|
MoveJudgement.BLUNDER -> R.string.review_blunders
|
||||||
MoveJudgement.GREAT -> R.string.review_greats
|
|
||||||
MoveJudgement.BRILLIANT -> R.string.review_brilliants
|
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/// The engine's mark after a main-line move in the notation (§21.4): a layer of its own,
|
||||||
|
/// apart from the author's NAGs.
|
||||||
|
@Composable
|
||||||
|
fun ReviewBadge(j: MoveJudgement, modifier: Modifier = Modifier) {
|
||||||
|
val c = judgementColor(j, LocalChessColors.current.dark)
|
||||||
|
Text(
|
||||||
|
judgementSymbol(j),
|
||||||
|
fontSize = 13.sp,
|
||||||
|
fontWeight = FontWeight.Bold,
|
||||||
|
color = c,
|
||||||
|
modifier = modifier
|
||||||
|
.clip(RoundedCornerShape(4.dp))
|
||||||
|
.background(c.copy(alpha = 0.16f))
|
||||||
|
.padding(horizontal = 4.dp, vertical = 1.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// The place in `state.points` of a node: itself on the main line, or the main-line move
|
/// The place in `state.points` of a node: itself on the main line, or the main-line move
|
||||||
/// its variation leaves from.
|
/// its variation leaves from.
|
||||||
fun pointIndex(points: Map<Int, Int>, game: GameData, node: Int): Int? {
|
fun pointIndex(points: Map<Int, Int>, game: GameData, node: Int): Int? {
|
||||||
|
|
@ -222,23 +225,9 @@ fun ReviewPanel(
|
||||||
TextButton(onClick = onResume) { Text(stringResource(R.string.review_resume)) }
|
TextButton(onClick = onResume) { Text(stringResource(R.string.review_resume)) }
|
||||||
report()
|
report()
|
||||||
}
|
}
|
||||||
// Made with other engine settings (before the fixed search): made again.
|
state.missing > 0u -> {
|
||||||
state.stale -> {
|
|
||||||
Text(
|
Text(
|
||||||
stringResource(R.string.review_stale),
|
stringResource(R.string.review_missing, state.missing.toInt()),
|
||||||
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.
|
|
||||||
if (state.missing > 0u) stringResource(R.string.review_missing, state.missing.toInt()) else stringResource(R.string.review_no_seconds),
|
|
||||||
style = textStyle.merge(Tabular),
|
style = textStyle.merge(Tabular),
|
||||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||||
modifier = Modifier.weight(1f),
|
modifier = Modifier.weight(1f),
|
||||||
|
|
@ -419,13 +408,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
|
/// The sheet that starts the analysis (§21.2).
|
||||||
/// engine search is fixed, the same on every phone and computer: nothing to choose.
|
|
||||||
@OptIn(ExperimentalMaterial3Api::class)
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun ReviewStartSheet(
|
fun ReviewStartSheet(
|
||||||
state: ReviewState?,
|
state: ReviewState?,
|
||||||
npsPerProcess: Long,
|
quality: Int,
|
||||||
|
threads: Int,
|
||||||
|
npsPerThread: Long,
|
||||||
|
onQuality: (Int) -> Unit,
|
||||||
onStart: (full: Boolean) -> Unit,
|
onStart: (full: Boolean) -> Unit,
|
||||||
onDismiss: () -> Unit,
|
onDismiss: () -> Unit,
|
||||||
) {
|
) {
|
||||||
|
|
@ -434,17 +425,29 @@ fun ReviewStartSheet(
|
||||||
Text(stringResource(R.string.review_menu), style = MaterialTheme.typography.titleLarge)
|
Text(stringResource(R.string.review_menu), style = MaterialTheme.typography.titleLarge)
|
||||||
Spacer(Modifier.height(12.dp))
|
Spacer(Modifier.height(12.dp))
|
||||||
Text(stringResource(R.string.review_text), style = MaterialTheme.typography.bodyLarge)
|
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))
|
Spacer(Modifier.height(12.dp))
|
||||||
val total = state?.positions?.toInt() ?: 0
|
val total = state?.positions?.toInt() ?: 0
|
||||||
val missing = state?.missing?.toInt() ?: total
|
val missing = state?.missing?.toInt() ?: total
|
||||||
// Evaluations from the PGN: the engine makes its own, all of them.
|
// Some positions already have an engine evaluation: fill in, or start over.
|
||||||
val pgn = state != null && state.hasData && state.nodes == 0UL
|
val partial = state != null && state.hasData && state.nodes > 0UL && missing in 1 until total
|
||||||
// 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
|
|
||||||
val positions = if (partial) missing else total
|
val positions = if (partial) missing else total
|
||||||
// A full run also searches again for moves that could be !! or ! (about a third more).
|
// "Fill in" keeps the quality of the first run; the choice is for starting over.
|
||||||
val searches = if (partial) positions else (state?.searches?.toInt() ?: positions)
|
val nodes = (if (partial) state.nodes else REVIEW_NODES[quality.coerceIn(0, REVIEW_NODES.size - 1)]).toDouble()
|
||||||
val secs = uniffi.mobile_api.reviewEstimateSecs(searches.toUInt(), (if (npsPerProcess > 0) npsPerProcess else GUESS_NPS).toULong()).toInt().coerceAtLeast(1)
|
val nps = (if (npsPerThread > 0) npsPerThread else GUESS_NPS_PER_THREAD).toDouble() * threads.coerceAtLeast(1)
|
||||||
|
val secs = ceil(positions * 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)
|
val time = if (secs < 60) stringResource(R.string.review_seconds, secs) else stringResource(R.string.review_minutes, (secs + 59) / 60)
|
||||||
Text(
|
Text(
|
||||||
pluralStringResource(R.plurals.review_estimate, positions, positions, time),
|
pluralStringResource(R.plurals.review_estimate, positions, positions, time),
|
||||||
|
|
@ -461,10 +464,14 @@ fun ReviewStartSheet(
|
||||||
}
|
}
|
||||||
Spacer(Modifier.height(24.dp))
|
Spacer(Modifier.height(24.dp))
|
||||||
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
|
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
|
||||||
|
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)) }
|
TextButton(onClick = onDismiss) { Text(stringResource(R.string.cancel)) }
|
||||||
// The same search again would give the same evaluations: only the missing
|
// Everything evaluated already: analysing again starts over.
|
||||||
// ones are made, or all of them over the PGN's (or a stale analysis).
|
Button(onClick = { onStart(state?.hasData == true) }) { Text(stringResource(R.string.review_start)) }
|
||||||
Button(onClick = { onStart(pgn) }) { Text(stringResource(if (partial) R.string.review_fill else R.string.review_start)) }
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -503,20 +510,11 @@ fun ReviewSheet(
|
||||||
black = { ReportNumber(percent(state.black.accuracy), MaterialTheme.typography.headlineSmall) },
|
black = { ReportNumber(percent(state.black.accuracy), MaterialTheme.typography.headlineSmall) },
|
||||||
)
|
)
|
||||||
val next = stringResource(R.string.review_next)
|
val next = stringResource(R.string.review_next)
|
||||||
listOf(
|
listOf(MoveJudgement.INACCURACY, MoveJudgement.MISTAKE, MoveJudgement.BLUNDER).forEach { j ->
|
||||||
MoveJudgement.BRILLIANT,
|
|
||||||
MoveJudgement.GREAT,
|
|
||||||
MoveJudgement.INACCURACY,
|
|
||||||
MoveJudgement.MISTAKE,
|
|
||||||
MoveJudgement.BLUNDER,
|
|
||||||
).forEach { j ->
|
|
||||||
val c = judgementColor(j, dark)
|
val c = judgementColor(j, dark)
|
||||||
val label = judgementPlural(j)
|
val label = judgementPlural(j)
|
||||||
// From the PGN's evaluations alone !! and ! are not known: a dash, not a zero.
|
|
||||||
val unknown = state.nodes == 0UL && (j == MoveJudgement.BRILLIANT || j == MoveJudgement.GREAT)
|
|
||||||
val cell: @Composable (Boolean, UInt, String) -> Unit = { isWhite, count, side ->
|
val cell: @Composable (Boolean, UInt, String) -> Unit = { isWhite, count, side ->
|
||||||
val active = count > 0u && !unknown
|
val active = count > 0u
|
||||||
val shown = if (unknown) "\u2014" else count.toString()
|
|
||||||
Row(
|
Row(
|
||||||
Modifier
|
Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
|
|
@ -530,14 +528,14 @@ fun ReviewSheet(
|
||||||
contentDescription = "$label, $side, $count"
|
contentDescription = "$label, $side, $count"
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
Modifier.clearAndSetSemantics { contentDescription = "$label, $side, $shown" }
|
Modifier.clearAndSetSemantics { contentDescription = "$label, $side, $count" }
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
verticalAlignment = Alignment.CenterVertically,
|
||||||
horizontalArrangement = Arrangement.End,
|
horizontalArrangement = Arrangement.End,
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
shown,
|
count.toString(),
|
||||||
style = MaterialTheme.typography.titleMedium.merge(Tabular),
|
style = MaterialTheme.typography.titleMedium.merge(Tabular),
|
||||||
color = if (active) c else variant,
|
color = if (active) c else variant,
|
||||||
)
|
)
|
||||||
|
|
@ -587,21 +585,11 @@ fun ReviewSheet(
|
||||||
style = MaterialTheme.typography.bodySmall,
|
style = MaterialTheme.typography.bodySmall,
|
||||||
color = variant,
|
color = variant,
|
||||||
)
|
)
|
||||||
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))
|
Spacer(Modifier.height(20.dp))
|
||||||
// With a large font the two buttons go on two lines instead of breaking words.
|
// 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)) {
|
FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) {
|
||||||
TextButton(onClick = onHide) { Text(stringResource(R.string.review_hide)) }
|
TextButton(onClick = onHide) { Text(stringResource(R.string.review_hide)) }
|
||||||
// Over evaluations of the PGN the engine can make its own; an engine
|
OutlinedButton(onClick = onAgain, enabled = !state.running) { Text(stringResource(R.string.review_again)) }
|
||||||
// analysis made again would only repeat itself.
|
|
||||||
if (state.nodes == 0UL) {
|
|
||||||
OutlinedButton(onClick = onAgain, enabled = !state.running) { Text(stringResource(R.string.review_engine)) }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -611,8 +599,6 @@ private fun SideReview.inaccuraciesOf(j: MoveJudgement): UInt = when (j) {
|
||||||
MoveJudgement.INACCURACY -> inaccuracies
|
MoveJudgement.INACCURACY -> inaccuracies
|
||||||
MoveJudgement.MISTAKE -> mistakes
|
MoveJudgement.MISTAKE -> mistakes
|
||||||
MoveJudgement.BLUNDER -> blunders
|
MoveJudgement.BLUNDER -> blunders
|
||||||
MoveJudgement.GREAT -> great
|
|
||||||
MoveJudgement.BRILLIANT -> brilliant
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A row of the report: its label, then White's and Black's cells, 96 dp each.
|
/// A row of the report: its label, then White's and Black's cells, 96 dp each.
|
||||||
|
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 64 KiB After Width: | Height: | Size: 70 KiB |
|
|
@ -36,8 +36,6 @@
|
||||||
<string name="to_start">Zum Anfang</string>
|
<string name="to_start">Zum Anfang</string>
|
||||||
<string name="move_back">Zug zurück</string>
|
<string name="move_back">Zug zurück</string>
|
||||||
<string name="move_forward">Zug vor</string>
|
<string name="move_forward">Zug vor</string>
|
||||||
<string name="move_back_hint">Vorheriger Zug. Gedrückt halten: zum Anfang</string>
|
|
||||||
<string name="move_forward_hint">Nächster Zug. Gedrückt halten: zum Ende der Variante</string>
|
|
||||||
<string name="to_end">Zum Ende der Variante</string>
|
<string name="to_end">Zum Ende der Variante</string>
|
||||||
<string name="next_moves">Weiter:</string>
|
<string name="next_moves">Weiter:</string>
|
||||||
<string name="board_description">Brett, Stellung nach %1$s</string>
|
<string name="board_description">Brett, Stellung nach %1$s</string>
|
||||||
|
|
@ -113,7 +111,8 @@
|
||||||
<string name="about">Über</string>
|
<string name="about">Über</string>
|
||||||
<string name="build_full">Stockfish eingebaut</string>
|
<string name="build_full">Stockfish eingebaut</string>
|
||||||
<string name="build_light">Stockfish wird in der App geladen</string>
|
<string name="build_light">Stockfish wird in der App geladen</string>
|
||||||
<string name="about_text">Schachdatenbanken, Partieanalyse und Spiel gegen den Computer. Ihre Dateien werden nur gelesen, nie geändert.</string>
|
<string name="alpha">Alpha</string>
|
||||||
|
<string name="about_text">Ein Betrachter für Schachdatenbanken: PGN, ChessBase, Archive. Dateien werden nur gelesen, nie geändert.</string>
|
||||||
<string name="licenses">Lizenzen und Autoren</string>
|
<string name="licenses">Lizenzen und Autoren</string>
|
||||||
<string name="website">Website und Quellcode</string>
|
<string name="website">Website und Quellcode</string>
|
||||||
|
|
||||||
|
|
@ -215,14 +214,6 @@
|
||||||
<string name="add_paste_hint">In einer anderen App kopierte Partien</string>
|
<string name="add_paste_hint">In einer anderen App kopierte Partien</string>
|
||||||
<string name="paste_none">Keine PGN-Partien in der Zwischenablage</string>
|
<string name="paste_none">Keine PGN-Partien in der Zwischenablage</string>
|
||||||
<string name="paste_db">Eingefügt am %1$s</string>
|
<string name="paste_db">Eingefügt am %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">Partie in der Zwischenablage</item>
|
|
||||||
<item quantity="other">Partien in der Zwischenablage</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Diese PGN-Partie speichern und auf dem Brett öffnen?</string>
|
|
||||||
<string name="clipboard_open_many">%1$s speichern und die erste Partie auf dem Brett öffnen? Alle Partien bleiben in der lokalen Kopie.</string>
|
|
||||||
<string name="clipboard_open">Öffnen</string>
|
|
||||||
<string name="clipboard_database_name">Zwischenablage</string>
|
|
||||||
<string name="opening_file">Datei wird geöffnet…</string>
|
<string name="opening_file">Datei wird geöffnet…</string>
|
||||||
<string name="file_failed">Die Datei ließ sich nicht öffnen</string>
|
<string name="file_failed">Die Datei ließ sich nicht öffnen</string>
|
||||||
<string name="file_no_games">Diese Datei enthält keine Schachpartien.</string>
|
<string name="file_no_games">Diese Datei enthält keine Schachpartien.</string>
|
||||||
|
|
@ -235,10 +226,15 @@
|
||||||
<string name="review_menu">Partieanalyse</string>
|
<string name="review_menu">Partieanalyse</string>
|
||||||
<string name="review_report_menu">Partiebericht</string>
|
<string name="review_report_menu">Partiebericht</string>
|
||||||
<string name="review_text">Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.</string>
|
<string name="review_text">Die Engine bewertet jede Stellung der Hauptvariante. Die Partie selbst wird nicht verändert.</string>
|
||||||
|
<string name="review_quality">Qualität</string>
|
||||||
|
<string name="review_fast">Schnell</string>
|
||||||
|
<string name="review_normal">Normal</string>
|
||||||
|
<string name="review_deep">Gründlich</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d Min.</string>
|
<string name="review_minutes">%d Min.</string>
|
||||||
<string name="review_start">Analysieren</string>
|
<string name="review_start">Analysieren</string>
|
||||||
<string name="review_fill">Ergänzen</string>
|
<string name="review_fill">Ergänzen</string>
|
||||||
|
<string name="review_again">Erneut analysieren</string>
|
||||||
<string name="review_partial">%1$d von %2$d Stellungen sind schon bewertet.</string>
|
<string name="review_partial">%1$d von %2$d Stellungen sind schon bewertet.</string>
|
||||||
<string name="review_progress">Partieanalyse · %1$d von %2$d</string>
|
<string name="review_progress">Partieanalyse · %1$d von %2$d</string>
|
||||||
<string name="review_stop">Analyse anhalten</string>
|
<string name="review_stop">Analyse anhalten</string>
|
||||||
|
|
@ -252,10 +248,6 @@
|
||||||
<string name="review_inaccuracies">Ungenauigkeiten</string>
|
<string name="review_inaccuracies">Ungenauigkeiten</string>
|
||||||
<string name="review_mistakes">Fehler</string>
|
<string name="review_mistakes">Fehler</string>
|
||||||
<string name="review_blunders">Grobe Fehler</string>
|
<string name="review_blunders">Grobe Fehler</string>
|
||||||
<string name="review_great">Starker Zug</string>
|
|
||||||
<string name="review_brilliant">Brillanter Zug</string>
|
|
||||||
<string name="review_greats">Starke Züge</string>
|
|
||||||
<string name="review_brilliants">Brillante Züge</string>
|
|
||||||
<string name="review_missing">Ohne Bewertung: %d</string>
|
<string name="review_missing">Ohne Bewertung: %d</string>
|
||||||
<string name="review_failed">Die Analyse wurde unterbrochen</string>
|
<string name="review_failed">Die Analyse wurde unterbrochen</string>
|
||||||
<string name="review_resume">Fortsetzen</string>
|
<string name="review_resume">Fortsetzen</string>
|
||||||
|
|
@ -265,17 +257,13 @@
|
||||||
<string name="review_endgame">Endspiel</string>
|
<string name="review_endgame">Endspiel</string>
|
||||||
<string name="review_source">%1$s · %2$s Knoten pro Zug</string>
|
<string name="review_source">%1$s · %2$s Knoten pro Zug</string>
|
||||||
<string name="review_source_pgn" formatted="false">Bewertungen aus der PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Bewertungen aus der PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! und ! braucht die Engine: die PGN enthält nur Bewertungen</string>
|
|
||||||
<string name="review_no_seconds">In dieser Analyse wurde noch nicht nach !! und ! gesucht</string>
|
|
||||||
<string name="review_stale">Analyse mit anderen Engine-Einstellungen gemacht</string>
|
|
||||||
<string name="review_update">Aktualisieren</string>
|
|
||||||
<string name="review_engine">Mit der Engine analysieren</string>
|
|
||||||
<string name="review_hide">Analyse ausblenden</string>
|
<string name="review_hide">Analyse ausblenden</string>
|
||||||
<string name="review_graph">Bewertungsgrafik</string>
|
<string name="review_graph">Bewertungsgrafik</string>
|
||||||
<string name="review_engine_paused">Pausiert: Partie wird analysiert</string>
|
<string name="review_engine_paused">Pausiert: Partie wird analysiert</string>
|
||||||
<string name="review_best_preview">Bessere Variante · Zug %1$d von %2$d</string>
|
<string name="review_best_preview">Bessere Variante · Zug %1$d von %2$d</string>
|
||||||
<string name="review_next">Zum nächsten solchen Zug</string>
|
<string name="review_next">Zum nächsten solchen Zug</string>
|
||||||
<string name="review_show_best">Die bessere Variante auf dem Brett zeigen</string>
|
<string name="review_show_best">Die bessere Variante auf dem Brett zeigen</string>
|
||||||
|
<string name="review_restart">Von vorn</string>
|
||||||
<string name="review_graph_state">%1$s, Bewertung %2$s</string>
|
<string name="review_graph_state">%1$s, Bewertung %2$s</string>
|
||||||
<string name="review_start_position">Ausgangsstellung</string>
|
<string name="review_start_position">Ausgangsstellung</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -669,56 +657,4 @@
|
||||||
<string name="strength_range">%1$s, von %2$s bis %3$s</string>
|
<string name="strength_range">%1$s, von %2$s bis %3$s</string>
|
||||||
<string name="strength">Spielstärke</string>
|
<string name="strength">Spielstärke</string>
|
||||||
<string name="books_delete_cd">Eröffnungsbücher löschen</string>
|
<string name="books_delete_cd">Eröffnungsbücher löschen</string>
|
||||||
|
|
||||||
<!-- Vorbereitung auf den Gegner (Aufgabe 48). -->
|
|
||||||
<string name="players">Spieler</string>
|
|
||||||
<string name="player_name_hint">Spielername</string>
|
|
||||||
<string name="players_read_failed">Spieler konnten nicht gelesen werden</string>
|
|
||||||
<string name="reading_players">Spieler werden gelesen…</string>
|
|
||||||
<string name="no_named_players">Diese Datenbank enthält keine benannten Spieler</string>
|
|
||||||
<string name="player_not_found">Spieler nicht gefunden</string>
|
|
||||||
<string name="to_games">Zu den Partien</string>
|
|
||||||
<string name="reset_search">Suche zurücksetzen</string>
|
|
||||||
<string name="prepare_action">Vorbereiten</string>
|
|
||||||
<string name="prep_choose_color">Farbe wählen</string>
|
|
||||||
<string name="prep_against_player">Vorbereiten gegen %1$s</string>
|
|
||||||
<string name="prep_against_white">Gegen Weiß</string>
|
|
||||||
<string name="prep_against_black">Gegen Schwarz</string>
|
|
||||||
<string name="prep_opponent">Auf Gegner vorbereiten…</string>
|
|
||||||
<string name="prep_title">Vorbereitung auf den Gegner</string>
|
|
||||||
<string name="prep_close_engine_line">Schließen Sie zuerst die Engine-Variante</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">Suche nach einem Lehrzug -- ist nicht verfügbar</string>
|
|
||||||
<string name="prep_as_white">Weiß</string>
|
|
||||||
<string name="prep_as_black">Schwarz</string>
|
|
||||||
<string name="prep_move_failed">Dieser Zug konnte nicht ausgeführt werden</string>
|
|
||||||
<string name="prep_play_continuation">%1$s spielen, %2$s, %3$s Prozent</string>
|
|
||||||
<string name="prep_board_start">Brett, Ausgangsstellung. %1$s unten.</string>
|
|
||||||
<string name="prep_board_after">Brett, Stellung nach %1$s. %2$s unten.</string>
|
|
||||||
<string name="turn_white">Weiß am Zug</string>
|
|
||||||
<string name="turn_black">Schwarz am Zug</string>
|
|
||||||
<string name="prep_opponent_plays">Gegner spielt</string>
|
|
||||||
<string name="prep_opponents_play">Seine Gegner spielen</string>
|
|
||||||
<string name="prep_after">nach %1$s</string>
|
|
||||||
<string name="prep_beginning">Anfang</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Fortsetzungen konnten nicht berechnet werden</string>
|
|
||||||
<string name="prep_no_memory">Nicht genügend Speicher für die Suche in dieser Datenbank</string>
|
|
||||||
<string name="prep_calculating">Fortsetzungen werden berechnet…</string>
|
|
||||||
<string name="prep_position_absent">Diese Stellung kommt in Partien von %1$s nicht vor</string>
|
|
||||||
<string name="prep_position_absent_hint">Sie können auf dem Brett fortsetzen oder zurückgehen</string>
|
|
||||||
<string name="prep_all_ended">Alle Partien endeten hier</string>
|
|
||||||
<string name="prep_ended_here">Hier beendet: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Keine normale Fortsetzung: %1$s</string>
|
|
||||||
<string name="to_game">Zur Partie</string>
|
|
||||||
<string name="to_players">Zu den Spielern</string>
|
|
||||||
<string name="prep_choose_move">Zug auswählen</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s Sieg</item><item quantity="other">%1$s Siege</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s Remis</item><item quantity="other">%1$s Remis</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s Niederlage</item><item quantity="other">%1$s Niederlagen</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Unbekannte Ergebnisse: %1$d; nicht in den Prozentwerten enthalten.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Spielen</string>
|
|
||||||
<string name="prep_unknown_short">weitere %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,6 @@
|
||||||
<string name="to_start">Al inicio</string>
|
<string name="to_start">Al inicio</string>
|
||||||
<string name="move_back">Jugada atrás</string>
|
<string name="move_back">Jugada atrás</string>
|
||||||
<string name="move_forward">Jugada adelante</string>
|
<string name="move_forward">Jugada adelante</string>
|
||||||
<string name="move_back_hint">Jugada anterior. Mantén pulsado para ir al inicio</string>
|
|
||||||
<string name="move_forward_hint">Jugada siguiente. Mantén pulsado para ir al final de la línea</string>
|
|
||||||
<string name="to_end">Al final de la línea</string>
|
<string name="to_end">Al final de la línea</string>
|
||||||
<string name="next_moves">Siguiente:</string>
|
<string name="next_moves">Siguiente:</string>
|
||||||
<string name="board_description">Tablero, posición tras %1$s</string>
|
<string name="board_description">Tablero, posición tras %1$s</string>
|
||||||
|
|
@ -114,7 +112,8 @@
|
||||||
<string name="about">Acerca de</string>
|
<string name="about">Acerca de</string>
|
||||||
<string name="build_full">Stockfish incluido</string>
|
<string name="build_full">Stockfish incluido</string>
|
||||||
<string name="build_light">Stockfish se descarga en la aplicación</string>
|
<string name="build_light">Stockfish se descarga en la aplicación</string>
|
||||||
<string name="about_text">Bases de ajedrez, análisis de partidas y juego contra el ordenador. Tus archivos solo se leen, nunca se modifican.</string>
|
<string name="alpha">alfa</string>
|
||||||
|
<string name="about_text">Un visor de bases de ajedrez: PGN, ChessBase, archivos comprimidos. Los archivos solo se leen, nunca se modifican.</string>
|
||||||
<string name="licenses">Licencias y autores</string>
|
<string name="licenses">Licencias y autores</string>
|
||||||
<string name="website">Sitio web y código fuente</string>
|
<string name="website">Sitio web y código fuente</string>
|
||||||
|
|
||||||
|
|
@ -219,15 +218,6 @@
|
||||||
<string name="add_paste_hint">Partidas copiadas en otra aplicación</string>
|
<string name="add_paste_hint">Partidas copiadas en otra aplicación</string>
|
||||||
<string name="paste_none">No hay partidas PGN en el portapapeles</string>
|
<string name="paste_none">No hay partidas PGN en el portapapeles</string>
|
||||||
<string name="paste_db">Pegado el %1$s</string>
|
<string name="paste_db">Pegado el %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">Partida en el portapapeles</item>
|
|
||||||
<item quantity="many">Partidas en el portapapeles</item>
|
|
||||||
<item quantity="other">Partidas en el portapapeles</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Guardar esta partida PGN y abrirla en el tablero?</string>
|
|
||||||
<string name="clipboard_open_many">Guardar %1$s y abrir la primera partida en el tablero? Todas las partidas se conservarán en la copia local.</string>
|
|
||||||
<string name="clipboard_open">Abrir</string>
|
|
||||||
<string name="clipboard_database_name">Portapapeles</string>
|
|
||||||
<string name="opening_file">Abriendo el archivo…</string>
|
<string name="opening_file">Abriendo el archivo…</string>
|
||||||
<string name="file_failed">No se pudo abrir el archivo</string>
|
<string name="file_failed">No se pudo abrir el archivo</string>
|
||||||
<string name="file_no_games">Este archivo no contiene partidas de ajedrez.</string>
|
<string name="file_no_games">Este archivo no contiene partidas de ajedrez.</string>
|
||||||
|
|
@ -240,10 +230,15 @@
|
||||||
<string name="review_menu">Análisis de la partida</string>
|
<string name="review_menu">Análisis de la partida</string>
|
||||||
<string name="review_report_menu">Informe de la partida</string>
|
<string name="review_report_menu">Informe de la partida</string>
|
||||||
<string name="review_text">El motor evalúa cada posición de la línea principal. La partida en sí no cambia.</string>
|
<string name="review_text">El motor evalúa cada posición de la línea principal. La partida en sí no cambia.</string>
|
||||||
|
<string name="review_quality">Calidad</string>
|
||||||
|
<string name="review_fast">Rápido</string>
|
||||||
|
<string name="review_normal">Normal</string>
|
||||||
|
<string name="review_deep">Profundo</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d min</string>
|
<string name="review_minutes">%d min</string>
|
||||||
<string name="review_start">Analizar</string>
|
<string name="review_start">Analizar</string>
|
||||||
<string name="review_fill">Completar</string>
|
<string name="review_fill">Completar</string>
|
||||||
|
<string name="review_again">Analizar de nuevo</string>
|
||||||
<string name="review_partial">Ya hay %1$d de %2$d posiciones evaluadas.</string>
|
<string name="review_partial">Ya hay %1$d de %2$d posiciones evaluadas.</string>
|
||||||
<string name="review_progress">Análisis · %1$d de %2$d</string>
|
<string name="review_progress">Análisis · %1$d de %2$d</string>
|
||||||
<string name="review_stop">Detener el análisis</string>
|
<string name="review_stop">Detener el análisis</string>
|
||||||
|
|
@ -257,10 +252,6 @@
|
||||||
<string name="review_inaccuracies">Imprecisiones</string>
|
<string name="review_inaccuracies">Imprecisiones</string>
|
||||||
<string name="review_mistakes">Errores</string>
|
<string name="review_mistakes">Errores</string>
|
||||||
<string name="review_blunders">Errores graves</string>
|
<string name="review_blunders">Errores graves</string>
|
||||||
<string name="review_great">Gran jugada</string>
|
|
||||||
<string name="review_brilliant">Jugada brillante</string>
|
|
||||||
<string name="review_greats">Grandes jugadas</string>
|
|
||||||
<string name="review_brilliants">Jugadas brillantes</string>
|
|
||||||
<string name="review_missing">Sin evaluar: %d</string>
|
<string name="review_missing">Sin evaluar: %d</string>
|
||||||
<string name="review_failed">El análisis se interrumpió</string>
|
<string name="review_failed">El análisis se interrumpió</string>
|
||||||
<string name="review_resume">Continuar</string>
|
<string name="review_resume">Continuar</string>
|
||||||
|
|
@ -270,17 +261,13 @@
|
||||||
<string name="review_endgame">Final</string>
|
<string name="review_endgame">Final</string>
|
||||||
<string name="review_source">%1$s · %2$s nodos por jugada</string>
|
<string name="review_source">%1$s · %2$s nodos por jugada</string>
|
||||||
<string name="review_source_pgn" formatted="false">Evaluaciones del PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Evaluaciones del PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! y ! requieren el motor: el PGN solo trae evaluaciones</string>
|
|
||||||
<string name="review_no_seconds">Este análisis aún no buscó !! ni !</string>
|
|
||||||
<string name="review_stale">Análisis hecho con otros ajustes del motor</string>
|
|
||||||
<string name="review_update">Actualizar</string>
|
|
||||||
<string name="review_engine">Analizar con el motor</string>
|
|
||||||
<string name="review_hide">Ocultar el análisis</string>
|
<string name="review_hide">Ocultar el análisis</string>
|
||||||
<string name="review_graph">Gráfico de evaluación</string>
|
<string name="review_graph">Gráfico de evaluación</string>
|
||||||
<string name="review_engine_paused">En pausa: se está analizando la partida</string>
|
<string name="review_engine_paused">En pausa: se está analizando la partida</string>
|
||||||
<string name="review_best_preview">Mejor línea · jugada %1$d de %2$d</string>
|
<string name="review_best_preview">Mejor línea · jugada %1$d de %2$d</string>
|
||||||
<string name="review_next">Ir a la siguiente jugada así</string>
|
<string name="review_next">Ir a la siguiente jugada así</string>
|
||||||
<string name="review_show_best">Mostrar la mejor línea en el tablero</string>
|
<string name="review_show_best">Mostrar la mejor línea en el tablero</string>
|
||||||
|
<string name="review_restart">Empezar de nuevo</string>
|
||||||
<string name="review_graph_state">%1$s, evaluación %2$s</string>
|
<string name="review_graph_state">%1$s, evaluación %2$s</string>
|
||||||
<string name="review_start_position">Posición inicial</string>
|
<string name="review_start_position">Posición inicial</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -678,56 +665,4 @@
|
||||||
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
||||||
<string name="strength">Fuerza</string>
|
<string name="strength">Fuerza</string>
|
||||||
<string name="books_delete_cd">Eliminar los libros de aperturas</string>
|
<string name="books_delete_cd">Eliminar los libros de aperturas</string>
|
||||||
|
|
||||||
<!-- Preparación contra el rival (tarea 48). -->
|
|
||||||
<string name="players">Jugadores</string>
|
|
||||||
<string name="player_name_hint">Nombre del jugador</string>
|
|
||||||
<string name="players_read_failed">No se pudieron leer los jugadores</string>
|
|
||||||
<string name="reading_players">Leyendo jugadores…</string>
|
|
||||||
<string name="no_named_players">No hay jugadores con nombre en esta base</string>
|
|
||||||
<string name="player_not_found">Jugador no encontrado</string>
|
|
||||||
<string name="to_games">Volver a las partidas</string>
|
|
||||||
<string name="reset_search">Borrar búsqueda</string>
|
|
||||||
<string name="prepare_action">Preparar</string>
|
|
||||||
<string name="prep_choose_color">Elige un color</string>
|
|
||||||
<string name="prep_against_player">Prepararse contra %1$s</string>
|
|
||||||
<string name="prep_against_white">Contra las blancas</string>
|
|
||||||
<string name="prep_against_black">Contra las negras</string>
|
|
||||||
<string name="prep_opponent">Prepararse contra el rival…</string>
|
|
||||||
<string name="prep_title">Preparación contra el rival</string>
|
|
||||||
<string name="prep_close_engine_line">Cierra primero la línea del motor</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">La búsqueda después de un -- didáctico no está disponible</string>
|
|
||||||
<string name="prep_as_white">Blancas</string>
|
|
||||||
<string name="prep_as_black">Negras</string>
|
|
||||||
<string name="prep_move_failed">No se pudo jugar este movimiento</string>
|
|
||||||
<string name="prep_play_continuation">Jugar %1$s, %2$s, %3$s por ciento</string>
|
|
||||||
<string name="prep_board_start">Tablero, posición inicial. %1$s abajo.</string>
|
|
||||||
<string name="prep_board_after">Tablero, posición después de %1$s. %2$s abajo.</string>
|
|
||||||
<string name="turn_white">Juegan las blancas</string>
|
|
||||||
<string name="turn_black">Juegan las negras</string>
|
|
||||||
<string name="prep_opponent_plays">Juega el rival</string>
|
|
||||||
<string name="prep_opponents_play">Juegan sus rivales</string>
|
|
||||||
<string name="prep_after">después de %1$s</string>
|
|
||||||
<string name="prep_beginning">inicio</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">No se pudieron calcular las continuaciones</string>
|
|
||||||
<string name="prep_no_memory">No hay memoria suficiente para buscar en esta base</string>
|
|
||||||
<string name="prep_calculating">Calculando continuaciones…</string>
|
|
||||||
<string name="prep_position_absent">Esta posición no aparece en las partidas de %1$s</string>
|
|
||||||
<string name="prep_position_absent_hint">Puedes continuar en el tablero o retroceder</string>
|
|
||||||
<string name="prep_all_ended">Todas las partidas terminaron aquí</string>
|
|
||||||
<string name="prep_ended_here">Terminaron aquí: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Sin continuación normal: %1$s</string>
|
|
||||||
<string name="to_game">Volver a la partida</string>
|
|
||||||
<string name="to_players">Volver a los jugadores</string>
|
|
||||||
<string name="prep_choose_move">Elige un movimiento</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s victoria</item><item quantity="many">%1$s victorias</item><item quantity="other">%1$s victorias</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s tabla</item><item quantity="many">%1$s tablas</item><item quantity="other">%1$s tablas</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s derrota</item><item quantity="many">%1$s derrotas</item><item quantity="other">%1$s derrotas</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Resultados desconocidos: %1$d; excluidos de los porcentajes.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Jugar</string>
|
|
||||||
<string name="prep_unknown_short">%1$s más</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,6 @@
|
||||||
<string name="to_start">Au début</string>
|
<string name="to_start">Au début</string>
|
||||||
<string name="move_back">Coup précédent</string>
|
<string name="move_back">Coup précédent</string>
|
||||||
<string name="move_forward">Coup suivant</string>
|
<string name="move_forward">Coup suivant</string>
|
||||||
<string name="move_back_hint">Coup précédent. Maintenez pour aller au début</string>
|
|
||||||
<string name="move_forward_hint">Coup suivant. Maintenez pour aller à la fin de la ligne</string>
|
|
||||||
<string name="to_end">À la fin de la ligne</string>
|
<string name="to_end">À la fin de la ligne</string>
|
||||||
<string name="next_moves">Suite :</string>
|
<string name="next_moves">Suite :</string>
|
||||||
<string name="board_description">Échiquier, position après %1$s</string>
|
<string name="board_description">Échiquier, position après %1$s</string>
|
||||||
|
|
@ -114,7 +112,8 @@
|
||||||
<string name="about">À propos</string>
|
<string name="about">À propos</string>
|
||||||
<string name="build_full">Stockfish intégré</string>
|
<string name="build_full">Stockfish intégré</string>
|
||||||
<string name="build_light">Stockfish téléchargé dans l’application</string>
|
<string name="build_light">Stockfish téléchargé dans l’application</string>
|
||||||
<string name="about_text">Bases d’échecs, analyse des parties et jeu contre l’ordinateur. Vos fichiers sont seulement lus, jamais modifiés.</string>
|
<string name="alpha">alpha</string>
|
||||||
|
<string name="about_text">Une visionneuse de bases d’échecs : PGN, ChessBase, archives. Les fichiers sont seulement lus, jamais modifiés.</string>
|
||||||
<string name="licenses">Licences et auteurs</string>
|
<string name="licenses">Licences et auteurs</string>
|
||||||
<string name="website">Site web et code source</string>
|
<string name="website">Site web et code source</string>
|
||||||
|
|
||||||
|
|
@ -219,15 +218,6 @@
|
||||||
<string name="add_paste_hint">Parties copiées dans une autre application</string>
|
<string name="add_paste_hint">Parties copiées dans une autre application</string>
|
||||||
<string name="paste_none">Aucune partie PGN dans le presse-papiers</string>
|
<string name="paste_none">Aucune partie PGN dans le presse-papiers</string>
|
||||||
<string name="paste_db">Collé le %1$s</string>
|
<string name="paste_db">Collé le %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">%1$s partie dans le presse-papiers</item>
|
|
||||||
<item quantity="many">%1$s parties dans le presse-papiers</item>
|
|
||||||
<item quantity="other">%1$s parties dans le presse-papiers</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Enregistrer cette partie PGN et l’ouvrir sur l’échiquier ?</string>
|
|
||||||
<string name="clipboard_open_many">Enregistrer %1$s et ouvrir la première partie sur l’échiquier ? Toutes les parties seront conservées dans la copie locale.</string>
|
|
||||||
<string name="clipboard_open">Ouvrir</string>
|
|
||||||
<string name="clipboard_database_name">Presse-papiers</string>
|
|
||||||
<string name="opening_file">Ouverture du fichier…</string>
|
<string name="opening_file">Ouverture du fichier…</string>
|
||||||
<string name="file_failed">Impossible d’ouvrir le fichier</string>
|
<string name="file_failed">Impossible d’ouvrir le fichier</string>
|
||||||
<string name="file_no_games">Ce fichier ne contient aucune partie d’échecs.</string>
|
<string name="file_no_games">Ce fichier ne contient aucune partie d’échecs.</string>
|
||||||
|
|
@ -240,10 +230,15 @@
|
||||||
<string name="review_menu">Analyse de la partie</string>
|
<string name="review_menu">Analyse de la partie</string>
|
||||||
<string name="review_report_menu">Rapport de la partie</string>
|
<string name="review_report_menu">Rapport de la partie</string>
|
||||||
<string name="review_text">Le moteur évalue chaque position de la ligne principale. La partie elle-même n\'est pas modifiée.</string>
|
<string name="review_text">Le moteur évalue chaque position de la ligne principale. La partie elle-même n\'est pas modifiée.</string>
|
||||||
|
<string name="review_quality">Qualité</string>
|
||||||
|
<string name="review_fast">Rapide</string>
|
||||||
|
<string name="review_normal">Normal</string>
|
||||||
|
<string name="review_deep">Approfondi</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d min</string>
|
<string name="review_minutes">%d min</string>
|
||||||
<string name="review_start">Analyser</string>
|
<string name="review_start">Analyser</string>
|
||||||
<string name="review_fill">Compléter</string>
|
<string name="review_fill">Compléter</string>
|
||||||
|
<string name="review_again">Analyser de nouveau</string>
|
||||||
<string name="review_partial">%1$d positions sur %2$d sont déjà évaluées.</string>
|
<string name="review_partial">%1$d positions sur %2$d sont déjà évaluées.</string>
|
||||||
<string name="review_progress">Analyse · %1$d sur %2$d</string>
|
<string name="review_progress">Analyse · %1$d sur %2$d</string>
|
||||||
<string name="review_stop">Arrêter l\'analyse</string>
|
<string name="review_stop">Arrêter l\'analyse</string>
|
||||||
|
|
@ -257,10 +252,6 @@
|
||||||
<string name="review_inaccuracies">Imprécisions</string>
|
<string name="review_inaccuracies">Imprécisions</string>
|
||||||
<string name="review_mistakes">Erreurs</string>
|
<string name="review_mistakes">Erreurs</string>
|
||||||
<string name="review_blunders">Gaffes</string>
|
<string name="review_blunders">Gaffes</string>
|
||||||
<string name="review_great">Excellent coup</string>
|
|
||||||
<string name="review_brilliant">Coup brillant</string>
|
|
||||||
<string name="review_greats">Excellents coups</string>
|
|
||||||
<string name="review_brilliants">Coups brillants</string>
|
|
||||||
<string name="review_missing">Non évaluées : %d</string>
|
<string name="review_missing">Non évaluées : %d</string>
|
||||||
<string name="review_failed">L\'analyse s\'est interrompue</string>
|
<string name="review_failed">L\'analyse s\'est interrompue</string>
|
||||||
<string name="review_resume">Continuer</string>
|
<string name="review_resume">Continuer</string>
|
||||||
|
|
@ -270,17 +261,13 @@
|
||||||
<string name="review_endgame">Finale</string>
|
<string name="review_endgame">Finale</string>
|
||||||
<string name="review_source">%1$s · %2$s nœuds par coup</string>
|
<string name="review_source">%1$s · %2$s nœuds par coup</string>
|
||||||
<string name="review_source_pgn" formatted="false">Évaluations issues du PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Évaluations issues du PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! et ! demandent le moteur : le PGN ne contient que des évaluations</string>
|
|
||||||
<string name="review_no_seconds">Cette analyse n’a pas encore cherché les !! et !</string>
|
|
||||||
<string name="review_stale">Analyse faite avec d’autres réglages du moteur</string>
|
|
||||||
<string name="review_update">Mettre à jour</string>
|
|
||||||
<string name="review_engine">Analyser avec le moteur</string>
|
|
||||||
<string name="review_hide">Masquer l\'analyse</string>
|
<string name="review_hide">Masquer l\'analyse</string>
|
||||||
<string name="review_graph">Graphique d\'évaluation</string>
|
<string name="review_graph">Graphique d\'évaluation</string>
|
||||||
<string name="review_engine_paused">En pause : analyse de la partie en cours</string>
|
<string name="review_engine_paused">En pause : analyse de la partie en cours</string>
|
||||||
<string name="review_best_preview">Meilleure ligne · coup %1$d sur %2$d</string>
|
<string name="review_best_preview">Meilleure ligne · coup %1$d sur %2$d</string>
|
||||||
<string name="review_next">Aller au coup suivant de ce type</string>
|
<string name="review_next">Aller au coup suivant de ce type</string>
|
||||||
<string name="review_show_best">Afficher la meilleure ligne sur l\'échiquier</string>
|
<string name="review_show_best">Afficher la meilleure ligne sur l\'échiquier</string>
|
||||||
|
<string name="review_restart">Recommencer</string>
|
||||||
<string name="review_graph_state">%1$s, évaluation %2$s</string>
|
<string name="review_graph_state">%1$s, évaluation %2$s</string>
|
||||||
<string name="review_start_position">Position de départ</string>
|
<string name="review_start_position">Position de départ</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -678,56 +665,4 @@
|
||||||
<string name="strength_range">%1$s, de %2$s à %3$s</string>
|
<string name="strength_range">%1$s, de %2$s à %3$s</string>
|
||||||
<string name="strength">Force</string>
|
<string name="strength">Force</string>
|
||||||
<string name="books_delete_cd">Supprimer les livres d’ouvertures</string>
|
<string name="books_delete_cd">Supprimer les livres d’ouvertures</string>
|
||||||
|
|
||||||
<!-- Préparation contre l’adversaire (tâche 48). -->
|
|
||||||
<string name="players">Joueurs</string>
|
|
||||||
<string name="player_name_hint">Nom du joueur</string>
|
|
||||||
<string name="players_read_failed">Impossible de lire les joueurs</string>
|
|
||||||
<string name="reading_players">Lecture des joueurs…</string>
|
|
||||||
<string name="no_named_players">Cette base ne contient aucun joueur nommé</string>
|
|
||||||
<string name="player_not_found">Joueur introuvable</string>
|
|
||||||
<string name="to_games">Retour aux parties</string>
|
|
||||||
<string name="reset_search">Effacer la recherche</string>
|
|
||||||
<string name="prepare_action">Préparer</string>
|
|
||||||
<string name="prep_choose_color">Choisissez la couleur</string>
|
|
||||||
<string name="prep_against_player">Préparer contre %1$s</string>
|
|
||||||
<string name="prep_against_white">Contre les Blancs</string>
|
|
||||||
<string name="prep_against_black">Contre les Noirs</string>
|
|
||||||
<string name="prep_opponent">Préparer contre l’adversaire…</string>
|
|
||||||
<string name="prep_title">Préparation contre l’adversaire</string>
|
|
||||||
<string name="prep_close_engine_line">Fermez d’abord la ligne du moteur</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">La recherche après un -- pédagogique est indisponible</string>
|
|
||||||
<string name="prep_as_white">Blancs</string>
|
|
||||||
<string name="prep_as_black">Noirs</string>
|
|
||||||
<string name="prep_move_failed">Impossible de jouer ce coup</string>
|
|
||||||
<string name="prep_play_continuation">Jouer %1$s, %2$s, %3$s pour cent</string>
|
|
||||||
<string name="prep_board_start">Échiquier, position initiale. %1$s en bas.</string>
|
|
||||||
<string name="prep_board_after">Échiquier, position après %1$s. %2$s en bas.</string>
|
|
||||||
<string name="turn_white">Trait aux blancs</string>
|
|
||||||
<string name="turn_black">Trait aux noirs</string>
|
|
||||||
<string name="prep_opponent_plays">L’adversaire joue</string>
|
|
||||||
<string name="prep_opponents_play">Ses adversaires jouent</string>
|
|
||||||
<string name="prep_after">après %1$s</string>
|
|
||||||
<string name="prep_beginning">début</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Impossible de calculer les continuations</string>
|
|
||||||
<string name="prep_no_memory">Mémoire insuffisante pour rechercher dans cette base</string>
|
|
||||||
<string name="prep_calculating">Calcul des continuations…</string>
|
|
||||||
<string name="prep_position_absent">Cette position n’apparaît pas dans les parties de %1$s</string>
|
|
||||||
<string name="prep_position_absent_hint">Vous pouvez continuer sur l’échiquier ou revenir en arrière</string>
|
|
||||||
<string name="prep_all_ended">Toutes les parties se terminent ici</string>
|
|
||||||
<string name="prep_ended_here">Terminées ici : %1$s</string>
|
|
||||||
<string name="prep_no_normal">Aucune continuation normale : %1$s</string>
|
|
||||||
<string name="to_game">Retour à la partie</string>
|
|
||||||
<string name="to_players">Retour aux joueurs</string>
|
|
||||||
<string name="prep_choose_move">Choisir un coup</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s victoire</item><item quantity="many">%1$s victoires</item><item quantity="other">%1$s victoires</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s nulle</item><item quantity="many">%1$s nulles</item><item quantity="other">%1$s nulles</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s défaite</item><item quantity="many">%1$s défaites</item><item quantity="other">%1$s défaites</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Résultats inconnus : %1$d ; exclus des pourcentages.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Jouer</string>
|
|
||||||
<string name="prep_unknown_short">plus %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,6 @@
|
||||||
<string name="to_start">All\'inizio</string>
|
<string name="to_start">All\'inizio</string>
|
||||||
<string name="move_back">Mossa indietro</string>
|
<string name="move_back">Mossa indietro</string>
|
||||||
<string name="move_forward">Mossa avanti</string>
|
<string name="move_forward">Mossa avanti</string>
|
||||||
<string name="move_back_hint">Mossa precedente. Tieni premuto per andare all\'inizio</string>
|
|
||||||
<string name="move_forward_hint">Mossa successiva. Tieni premuto per andare alla fine della linea</string>
|
|
||||||
<string name="to_end">Alla fine della linea</string>
|
<string name="to_end">Alla fine della linea</string>
|
||||||
<string name="next_moves">Seguito:</string>
|
<string name="next_moves">Seguito:</string>
|
||||||
<string name="board_description">Scacchiera, posizione dopo %1$s</string>
|
<string name="board_description">Scacchiera, posizione dopo %1$s</string>
|
||||||
|
|
@ -114,7 +112,8 @@
|
||||||
<string name="about">Informazioni</string>
|
<string name="about">Informazioni</string>
|
||||||
<string name="build_full">Stockfish incluso</string>
|
<string name="build_full">Stockfish incluso</string>
|
||||||
<string name="build_light">Stockfish si scarica nell\'app</string>
|
<string name="build_light">Stockfish si scarica nell\'app</string>
|
||||||
<string name="about_text">Database scacchistici, analisi delle partite e gioco contro il computer. I tuoi file vengono solo letti, mai modificati.</string>
|
<string name="alpha">alfa</string>
|
||||||
|
<string name="about_text">Un visualizzatore di database scacchistici: PGN, ChessBase, archivi. I file vengono solo letti, mai modificati.</string>
|
||||||
<string name="licenses">Licenze e autori</string>
|
<string name="licenses">Licenze e autori</string>
|
||||||
<string name="website">Sito web e codice sorgente</string>
|
<string name="website">Sito web e codice sorgente</string>
|
||||||
|
|
||||||
|
|
@ -219,15 +218,6 @@
|
||||||
<string name="add_paste_hint">Partite copiate in un’altra app</string>
|
<string name="add_paste_hint">Partite copiate in un’altra app</string>
|
||||||
<string name="paste_none">Nessuna partita PGN negli appunti</string>
|
<string name="paste_none">Nessuna partita PGN negli appunti</string>
|
||||||
<string name="paste_db">Incollato il %1$s</string>
|
<string name="paste_db">Incollato il %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">Partita negli appunti</item>
|
|
||||||
<item quantity="many">Partite negli appunti</item>
|
|
||||||
<item quantity="other">Partite negli appunti</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Salvare questa partita PGN e aprirla sulla scacchiera?</string>
|
|
||||||
<string name="clipboard_open_many">Salvare %1$s e aprire la prima partita sulla scacchiera? Tutte le partite saranno conservate nella copia locale.</string>
|
|
||||||
<string name="clipboard_open">Apri</string>
|
|
||||||
<string name="clipboard_database_name">Appunti</string>
|
|
||||||
<string name="opening_file">Apertura del file…</string>
|
<string name="opening_file">Apertura del file…</string>
|
||||||
<string name="file_failed">Impossibile aprire il file</string>
|
<string name="file_failed">Impossibile aprire il file</string>
|
||||||
<string name="file_no_games">Questo file non contiene partite a scacchi.</string>
|
<string name="file_no_games">Questo file non contiene partite a scacchi.</string>
|
||||||
|
|
@ -240,10 +230,15 @@
|
||||||
<string name="review_menu">Analisi della partita</string>
|
<string name="review_menu">Analisi della partita</string>
|
||||||
<string name="review_report_menu">Resoconto della partita</string>
|
<string name="review_report_menu">Resoconto della partita</string>
|
||||||
<string name="review_text">Il motore valuta ogni posizione della linea principale. La partita non viene modificata.</string>
|
<string name="review_text">Il motore valuta ogni posizione della linea principale. La partita non viene modificata.</string>
|
||||||
|
<string name="review_quality">Qualità</string>
|
||||||
|
<string name="review_fast">Veloce</string>
|
||||||
|
<string name="review_normal">Normale</string>
|
||||||
|
<string name="review_deep">Approfondito</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d min</string>
|
<string name="review_minutes">%d min</string>
|
||||||
<string name="review_start">Analizza</string>
|
<string name="review_start">Analizza</string>
|
||||||
<string name="review_fill">Completa</string>
|
<string name="review_fill">Completa</string>
|
||||||
|
<string name="review_again">Analizza di nuovo</string>
|
||||||
<string name="review_partial">%1$d posizioni su %2$d sono già valutate.</string>
|
<string name="review_partial">%1$d posizioni su %2$d sono già valutate.</string>
|
||||||
<string name="review_progress">Analisi · %1$d di %2$d</string>
|
<string name="review_progress">Analisi · %1$d di %2$d</string>
|
||||||
<string name="review_stop">Interrompi l\'analisi</string>
|
<string name="review_stop">Interrompi l\'analisi</string>
|
||||||
|
|
@ -257,10 +252,6 @@
|
||||||
<string name="review_inaccuracies">Imprecisioni</string>
|
<string name="review_inaccuracies">Imprecisioni</string>
|
||||||
<string name="review_mistakes">Errori</string>
|
<string name="review_mistakes">Errori</string>
|
||||||
<string name="review_blunders">Svarioni</string>
|
<string name="review_blunders">Svarioni</string>
|
||||||
<string name="review_great">Ottima mossa</string>
|
|
||||||
<string name="review_brilliant">Mossa brillante</string>
|
|
||||||
<string name="review_greats">Ottime mosse</string>
|
|
||||||
<string name="review_brilliants">Mosse brillanti</string>
|
|
||||||
<string name="review_missing">Non valutate: %d</string>
|
<string name="review_missing">Non valutate: %d</string>
|
||||||
<string name="review_failed">L\'analisi si è interrotta</string>
|
<string name="review_failed">L\'analisi si è interrotta</string>
|
||||||
<string name="review_resume">Continua</string>
|
<string name="review_resume">Continua</string>
|
||||||
|
|
@ -270,17 +261,13 @@
|
||||||
<string name="review_endgame">Finale</string>
|
<string name="review_endgame">Finale</string>
|
||||||
<string name="review_source">%1$s · %2$s nodi per mossa</string>
|
<string name="review_source">%1$s · %2$s nodi per mossa</string>
|
||||||
<string name="review_source_pgn" formatted="false">Valutazioni dal PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Valutazioni dal PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! e ! richiedono il motore: il PGN contiene solo valutazioni</string>
|
|
||||||
<string name="review_no_seconds">Questa analisi non ha ancora cercato !! e !</string>
|
|
||||||
<string name="review_stale">Analisi fatta con altre impostazioni del motore</string>
|
|
||||||
<string name="review_update">Aggiorna</string>
|
|
||||||
<string name="review_engine">Analizza con il motore</string>
|
|
||||||
<string name="review_hide">Nascondi l\'analisi</string>
|
<string name="review_hide">Nascondi l\'analisi</string>
|
||||||
<string name="review_graph">Grafico di valutazione</string>
|
<string name="review_graph">Grafico di valutazione</string>
|
||||||
<string name="review_engine_paused">In pausa: analisi della partita in corso</string>
|
<string name="review_engine_paused">In pausa: analisi della partita in corso</string>
|
||||||
<string name="review_best_preview">Linea migliore · mossa %1$d di %2$d</string>
|
<string name="review_best_preview">Linea migliore · mossa %1$d di %2$d</string>
|
||||||
<string name="review_next">Vai alla prossima mossa di questo tipo</string>
|
<string name="review_next">Vai alla prossima mossa di questo tipo</string>
|
||||||
<string name="review_show_best">Mostra la linea migliore sulla scacchiera</string>
|
<string name="review_show_best">Mostra la linea migliore sulla scacchiera</string>
|
||||||
|
<string name="review_restart">Ricomincia</string>
|
||||||
<string name="review_graph_state">%1$s, valutazione %2$s</string>
|
<string name="review_graph_state">%1$s, valutazione %2$s</string>
|
||||||
<string name="review_start_position">Posizione iniziale</string>
|
<string name="review_start_position">Posizione iniziale</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -678,56 +665,4 @@
|
||||||
<string name="strength_range">%1$s, da %2$s a %3$s</string>
|
<string name="strength_range">%1$s, da %2$s a %3$s</string>
|
||||||
<string name="strength">Forza</string>
|
<string name="strength">Forza</string>
|
||||||
<string name="books_delete_cd">Elimina i libri di aperture</string>
|
<string name="books_delete_cd">Elimina i libri di aperture</string>
|
||||||
|
|
||||||
<!-- Preparazione contro l\'avversario (attività 48). -->
|
|
||||||
<string name="players">Giocatori</string>
|
|
||||||
<string name="player_name_hint">Nome del giocatore</string>
|
|
||||||
<string name="players_read_failed">Impossibile leggere i giocatori</string>
|
|
||||||
<string name="reading_players">Lettura dei giocatori…</string>
|
|
||||||
<string name="no_named_players">Questo database non contiene giocatori con nome</string>
|
|
||||||
<string name="player_not_found">Giocatore non trovato</string>
|
|
||||||
<string name="to_games">Torna alle partite</string>
|
|
||||||
<string name="reset_search">Cancella ricerca</string>
|
|
||||||
<string name="prepare_action">Prepara</string>
|
|
||||||
<string name="prep_choose_color">Scegli un colore</string>
|
|
||||||
<string name="prep_against_player">Preparati contro %1$s</string>
|
|
||||||
<string name="prep_against_white">Contro il Bianco</string>
|
|
||||||
<string name="prep_against_black">Contro il Nero</string>
|
|
||||||
<string name="prep_opponent">Preparati contro l\'avversario…</string>
|
|
||||||
<string name="prep_title">Preparazione contro l\'avversario</string>
|
|
||||||
<string name="prep_close_engine_line">Chiudi prima la linea del motore</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">La ricerca dopo un -- didattico non è disponibile</string>
|
|
||||||
<string name="prep_as_white">Bianco</string>
|
|
||||||
<string name="prep_as_black">Nero</string>
|
|
||||||
<string name="prep_move_failed">Impossibile giocare questa mossa</string>
|
|
||||||
<string name="prep_play_continuation">Gioca %1$s, %2$s, %3$s per cento</string>
|
|
||||||
<string name="prep_board_start">Scacchiera, posizione iniziale. %1$s in basso.</string>
|
|
||||||
<string name="prep_board_after">Scacchiera, posizione dopo %1$s. %2$s in basso.</string>
|
|
||||||
<string name="turn_white">Tocca al bianco</string>
|
|
||||||
<string name="turn_black">Tocca al nero</string>
|
|
||||||
<string name="prep_opponent_plays">Gioca l\'avversario</string>
|
|
||||||
<string name="prep_opponents_play">Giocano i suoi avversari</string>
|
|
||||||
<string name="prep_after">dopo %1$s</string>
|
|
||||||
<string name="prep_beginning">inizio</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Impossibile calcolare le continuazioni</string>
|
|
||||||
<string name="prep_no_memory">Memoria insufficiente per cercare in questo database</string>
|
|
||||||
<string name="prep_calculating">Calcolo delle continuazioni…</string>
|
|
||||||
<string name="prep_position_absent">Questa posizione non compare nelle partite di %1$s</string>
|
|
||||||
<string name="prep_position_absent_hint">Puoi continuare sulla scacchiera o tornare indietro</string>
|
|
||||||
<string name="prep_all_ended">Tutte le partite sono terminate qui</string>
|
|
||||||
<string name="prep_ended_here">Terminate qui: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Nessuna continuazione normale: %1$s</string>
|
|
||||||
<string name="to_game">Torna alla partita</string>
|
|
||||||
<string name="to_players">Torna ai giocatori</string>
|
|
||||||
<string name="prep_choose_move">Scegli una mossa</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s vittoria</item><item quantity="many">%1$s vittorie</item><item quantity="other">%1$s vittorie</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s patta</item><item quantity="many">%1$s patte</item><item quantity="other">%1$s patte</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s sconfitta</item><item quantity="many">%1$s sconfitte</item><item quantity="other">%1$s sconfitte</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Risultati sconosciuti: %1$d; esclusi dalle percentuali.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Gioca</string>
|
|
||||||
<string name="prep_unknown_short">altri %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -36,8 +36,6 @@
|
||||||
<string name="to_start">Басына</string>
|
<string name="to_start">Басына</string>
|
||||||
<string name="move_back">Бір жүріс артқа</string>
|
<string name="move_back">Бір жүріс артқа</string>
|
||||||
<string name="move_forward">Бір жүріс алға</string>
|
<string name="move_forward">Бір жүріс алға</string>
|
||||||
<string name="move_back_hint">Алдыңғы жүріс. Басына өту үшін басып тұрыңыз</string>
|
|
||||||
<string name="move_forward_hint">Келесі жүріс. Варианттың соңына өту үшін басып тұрыңыз</string>
|
|
||||||
<string name="to_end">Варианттың соңына</string>
|
<string name="to_end">Варианттың соңына</string>
|
||||||
<string name="next_moves">Келесі:</string>
|
<string name="next_moves">Келесі:</string>
|
||||||
<string name="board_description">Тақта, %1$s кейінгі позиция</string>
|
<string name="board_description">Тақта, %1$s кейінгі позиция</string>
|
||||||
|
|
@ -113,7 +111,8 @@
|
||||||
<string name="about">Бағдарлама туралы</string>
|
<string name="about">Бағдарлама туралы</string>
|
||||||
<string name="build_full">Stockfish кіріктірілген</string>
|
<string name="build_full">Stockfish кіріктірілген</string>
|
||||||
<string name="build_light">Stockfish бағдарлама ішінде жүктеледі</string>
|
<string name="build_light">Stockfish бағдарлама ішінде жүктеледі</string>
|
||||||
<string name="about_text">Шахмат базалары, партияларды талдау және компьютермен ойын. Файлдарыңыз тек оқылады, ешқашан өзгертілмейді.</string>
|
<string name="alpha">альфа</string>
|
||||||
|
<string name="about_text">Шахмат базаларын қарау құралы: PGN, ChessBase, мұрағаттар. Файлдар тек оқылады, ешқашан өзгертілмейді.</string>
|
||||||
<string name="licenses">Лицензиялар мен авторлар</string>
|
<string name="licenses">Лицензиялар мен авторлар</string>
|
||||||
<string name="website">Сайт және бастапқы код</string>
|
<string name="website">Сайт және бастапқы код</string>
|
||||||
|
|
||||||
|
|
@ -215,14 +214,6 @@
|
||||||
<string name="add_paste_hint">Басқа бағдарламада көшірілген партиялар</string>
|
<string name="add_paste_hint">Басқа бағдарламада көшірілген партиялар</string>
|
||||||
<string name="paste_none">Алмасу буферінде PGN партиясы жоқ</string>
|
<string name="paste_none">Алмасу буферінде PGN партиясы жоқ</string>
|
||||||
<string name="paste_db">Қойылды: %1$s</string>
|
<string name="paste_db">Қойылды: %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">Алмасу буферіндегі партия</item>
|
|
||||||
<item quantity="other">Алмасу буферіндегі партиялар</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Осы PGN партиясын сақтап, тақтада ашу керек пе?</string>
|
|
||||||
<string name="clipboard_open_many">%1$s сақтап, бірінші партияны тақтада ашу керек пе? Барлық партиялар жергілікті көшірмеде сақталады.</string>
|
|
||||||
<string name="clipboard_open">Ашу</string>
|
|
||||||
<string name="clipboard_database_name">Алмасу буфері</string>
|
|
||||||
<string name="opening_file">Файл ашылуда…</string>
|
<string name="opening_file">Файл ашылуда…</string>
|
||||||
<string name="file_failed">Файлды ашу мүмкін болмады</string>
|
<string name="file_failed">Файлды ашу мүмкін болмады</string>
|
||||||
<string name="file_no_games">Бұл файлда шахмат партиялары жоқ.</string>
|
<string name="file_no_games">Бұл файлда шахмат партиялары жоқ.</string>
|
||||||
|
|
@ -235,10 +226,15 @@
|
||||||
<string name="review_menu">Партияны талдау</string>
|
<string name="review_menu">Партияны талдау</string>
|
||||||
<string name="review_report_menu">Партия есебі</string>
|
<string name="review_report_menu">Партия есебі</string>
|
||||||
<string name="review_text">Қозғалтқыш негізгі варианттың әр позициясын бағалайды. Партияның өзі өзгермейді.</string>
|
<string name="review_text">Қозғалтқыш негізгі варианттың әр позициясын бағалайды. Партияның өзі өзгермейді.</string>
|
||||||
|
<string name="review_quality">Сапа</string>
|
||||||
|
<string name="review_fast">Жылдам</string>
|
||||||
|
<string name="review_normal">Қалыпты</string>
|
||||||
|
<string name="review_deep">Терең</string>
|
||||||
<string name="review_seconds">%d с</string>
|
<string name="review_seconds">%d с</string>
|
||||||
<string name="review_minutes">%d мин</string>
|
<string name="review_minutes">%d мин</string>
|
||||||
<string name="review_start">Талдау</string>
|
<string name="review_start">Талдау</string>
|
||||||
<string name="review_fill">Толықтыру</string>
|
<string name="review_fill">Толықтыру</string>
|
||||||
|
<string name="review_again">Қайта талдау</string>
|
||||||
<string name="review_partial">%2$d позицияның %1$d бағаланып қойған.</string>
|
<string name="review_partial">%2$d позицияның %1$d бағаланып қойған.</string>
|
||||||
<string name="review_progress">Партияны талдау · %1$d / %2$d</string>
|
<string name="review_progress">Партияны талдау · %1$d / %2$d</string>
|
||||||
<string name="review_stop">Талдауды тоқтату</string>
|
<string name="review_stop">Талдауды тоқтату</string>
|
||||||
|
|
@ -252,10 +248,6 @@
|
||||||
<string name="review_inaccuracies">Дәлсіздіктер</string>
|
<string name="review_inaccuracies">Дәлсіздіктер</string>
|
||||||
<string name="review_mistakes">Қателер</string>
|
<string name="review_mistakes">Қателер</string>
|
||||||
<string name="review_blunders">Өрескел қателер</string>
|
<string name="review_blunders">Өрескел қателер</string>
|
||||||
<string name="review_great">Мықты жүріс</string>
|
|
||||||
<string name="review_brilliant">Тамаша жүріс</string>
|
|
||||||
<string name="review_greats">Мықты жүрістер</string>
|
|
||||||
<string name="review_brilliants">Тамаша жүрістер</string>
|
|
||||||
<string name="review_missing">Бағаланбаған: %d</string>
|
<string name="review_missing">Бағаланбаған: %d</string>
|
||||||
<string name="review_failed">Талдау тоқтап қалды</string>
|
<string name="review_failed">Талдау тоқтап қалды</string>
|
||||||
<string name="review_resume">Жалғастыру</string>
|
<string name="review_resume">Жалғастыру</string>
|
||||||
|
|
@ -265,17 +257,13 @@
|
||||||
<string name="review_endgame">Эндшпиль</string>
|
<string name="review_endgame">Эндшпиль</string>
|
||||||
<string name="review_source">%1$s · жүріске %2$s түйін</string>
|
<string name="review_source">%1$s · жүріске %2$s түйін</string>
|
||||||
<string name="review_source_pgn" formatted="false">PGN-дағы бағалар ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">PGN-дағы бағалар ([%eval])</string>
|
||||||
<string name="review_no_notes">!! және ! тек қозғалтқышпен: PGN-да тек бағалар бар</string>
|
|
||||||
<string name="review_no_seconds">Бұл талдауда !! мен ! әлі ізделмеген</string>
|
|
||||||
<string name="review_stale">Талдау қозғалтқыштың басқа баптауларымен жасалған</string>
|
|
||||||
<string name="review_update">Жаңарту</string>
|
|
||||||
<string name="review_engine">Қозғалтқышпен талдау</string>
|
|
||||||
<string name="review_hide">Талдауды жасыру</string>
|
<string name="review_hide">Талдауды жасыру</string>
|
||||||
<string name="review_graph">Бағалау графигі</string>
|
<string name="review_graph">Бағалау графигі</string>
|
||||||
<string name="review_engine_paused">Кідіртілді: партия талдануда</string>
|
<string name="review_engine_paused">Кідіртілді: партия талдануда</string>
|
||||||
<string name="review_best_preview">Жақсырақ вариант · жүріс %1$d / %2$d</string>
|
<string name="review_best_preview">Жақсырақ вариант · жүріс %1$d / %2$d</string>
|
||||||
<string name="review_next">Келесі осындай жүріске өту</string>
|
<string name="review_next">Келесі осындай жүріске өту</string>
|
||||||
<string name="review_show_best">Жақсырақ вариантты тақтада көрсету</string>
|
<string name="review_show_best">Жақсырақ вариантты тақтада көрсету</string>
|
||||||
|
<string name="review_restart">Басынан бастау</string>
|
||||||
<string name="review_graph_state">%1$s, баға %2$s</string>
|
<string name="review_graph_state">%1$s, баға %2$s</string>
|
||||||
<string name="review_start_position">Бастапқы позиция</string>
|
<string name="review_start_position">Бастапқы позиция</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -670,56 +658,4 @@
|
||||||
<string name="strength_range">%1$s, %2$s-ден %3$s-ге дейін</string>
|
<string name="strength_range">%1$s, %2$s-ден %3$s-ге дейін</string>
|
||||||
<string name="strength">Күші</string>
|
<string name="strength">Күші</string>
|
||||||
<string name="books_delete_cd">Дебют кітаптарын жою</string>
|
<string name="books_delete_cd">Дебют кітаптарын жою</string>
|
||||||
|
|
||||||
<!-- Қарсыласқа дайындық (48-тапсырма). -->
|
|
||||||
<string name="players">Ойыншылар</string>
|
|
||||||
<string name="player_name_hint">Ойыншының аты</string>
|
|
||||||
<string name="players_read_failed">Ойыншыларды оқу мүмкін болмады</string>
|
|
||||||
<string name="reading_players">Ойыншылар оқылуда…</string>
|
|
||||||
<string name="no_named_players">Бұл базада аты көрсетілген ойыншылар жоқ</string>
|
|
||||||
<string name="player_not_found">Ойыншы табылмады</string>
|
|
||||||
<string name="to_games">Партияларға оралу</string>
|
|
||||||
<string name="reset_search">Іздеуді тазалау</string>
|
|
||||||
<string name="prepare_action">Дайындалу</string>
|
|
||||||
<string name="prep_choose_color">Түсті таңдаңыз</string>
|
|
||||||
<string name="prep_against_player">Қарсыласқа дайындалу %1$s</string>
|
|
||||||
<string name="prep_against_white">Ақтарға қарсы</string>
|
|
||||||
<string name="prep_against_black">Қараларға қарсы</string>
|
|
||||||
<string name="prep_opponent">Қарсыласқа дайындалу…</string>
|
|
||||||
<string name="prep_title">Қарсыласқа дайындық</string>
|
|
||||||
<string name="prep_close_engine_line">Алдымен қозғалтқыш желісін жабыңыз</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">Оқу -- кейін іздеу қолжетімсіз</string>
|
|
||||||
<string name="prep_as_white">Ақтар</string>
|
|
||||||
<string name="prep_as_black">Қаралар</string>
|
|
||||||
<string name="prep_move_failed">Бұл жүрісті жасау мүмкін болмады</string>
|
|
||||||
<string name="prep_play_continuation">%1$s жүру, %2$s, %3$s пайыз</string>
|
|
||||||
<string name="prep_board_start">Тақта, бастапқы позиция. Төменде %1$s.</string>
|
|
||||||
<string name="prep_board_after">Тақта, %1$s кейінгі позиция. Төменде %2$s.</string>
|
|
||||||
<string name="turn_white">Ақтардың жүрісі</string>
|
|
||||||
<string name="turn_black">Қаралардың жүрісі</string>
|
|
||||||
<string name="prep_opponent_plays">Қарсылас жүреді</string>
|
|
||||||
<string name="prep_opponents_play">Оның қарсыластары жүреді</string>
|
|
||||||
<string name="prep_after">%1$s кейін</string>
|
|
||||||
<string name="prep_beginning">басы</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Жалғастарды есептеу мүмкін болмады</string>
|
|
||||||
<string name="prep_no_memory">Бұл базадан іздеуге жад жеткіліксіз</string>
|
|
||||||
<string name="prep_calculating">Жалғастар есептелуде…</string>
|
|
||||||
<string name="prep_position_absent">%1$s партияларында бұл позиция жоқ</string>
|
|
||||||
<string name="prep_position_absent_hint">Тақтада жалғастыруға немесе артқа оралуға болады</string>
|
|
||||||
<string name="prep_all_ended">Барлық партия осы жерде аяқталды</string>
|
|
||||||
<string name="prep_ended_here">Осы жерде аяқталды: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Қалыпты жалғас жоқ: %1$s</string>
|
|
||||||
<string name="to_game">Партияға оралу</string>
|
|
||||||
<string name="to_players">Ойыншыларға оралу</string>
|
|
||||||
<string name="prep_choose_move">Жүрісті таңдаңыз</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s жеңіс</item><item quantity="other">%1$s жеңіс</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s тең ойын</item><item quantity="other">%1$s тең ойын</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s жеңіліс</item><item quantity="other">%1$s жеңіліс</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Белгісіз нәтижелер: %1$d; олар пайызға кірмейді.</string>
|
|
||||||
<string name="prep_continuation_description">%1$s. %3$s ішінен %2$d, %4$s пайыз. %5$s нәтижелері: %6$s, %7$s, %8$s; %9$s, %10$s және %11$s пайыз. %12$s Жүру.</string>
|
|
||||||
<string name="prep_play">Жүру</string>
|
|
||||||
<string name="prep_unknown_short">тағы %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,6 @@
|
||||||
<string name="to_start">Ao início</string>
|
<string name="to_start">Ao início</string>
|
||||||
<string name="move_back">Voltar um lance</string>
|
<string name="move_back">Voltar um lance</string>
|
||||||
<string name="move_forward">Avançar um lance</string>
|
<string name="move_forward">Avançar um lance</string>
|
||||||
<string name="move_back_hint">Lance anterior. Mantenha premido para ir ao início</string>
|
|
||||||
<string name="move_forward_hint">Lance seguinte. Mantenha premido para ir ao fim da linha</string>
|
|
||||||
<string name="to_end">Ao fim da linha</string>
|
<string name="to_end">Ao fim da linha</string>
|
||||||
<string name="next_moves">Próximo:</string>
|
<string name="next_moves">Próximo:</string>
|
||||||
<string name="board_description">Tabuleiro, posição após %1$s</string>
|
<string name="board_description">Tabuleiro, posição após %1$s</string>
|
||||||
|
|
@ -114,7 +112,8 @@
|
||||||
<string name="about">Sobre</string>
|
<string name="about">Sobre</string>
|
||||||
<string name="build_full">Stockfish embutido</string>
|
<string name="build_full">Stockfish embutido</string>
|
||||||
<string name="build_light">Stockfish baixado no app</string>
|
<string name="build_light">Stockfish baixado no app</string>
|
||||||
<string name="about_text">Bases de xadrez, análise de partidas e jogo contra o computador. Os seus arquivos são só lidos, nunca alterados.</string>
|
<string name="alpha">alfa</string>
|
||||||
|
<string name="about_text">Um visualizador de bases de xadrez: PGN, ChessBase, arquivos compactados. Os arquivos são só lidos, nunca alterados.</string>
|
||||||
<string name="licenses">Licenças e autores</string>
|
<string name="licenses">Licenças e autores</string>
|
||||||
<string name="website">Site e código-fonte</string>
|
<string name="website">Site e código-fonte</string>
|
||||||
|
|
||||||
|
|
@ -219,15 +218,6 @@
|
||||||
<string name="add_paste_hint">Partidas copiadas em outro app</string>
|
<string name="add_paste_hint">Partidas copiadas em outro app</string>
|
||||||
<string name="paste_none">Nenhuma partida PGN na área de transferência</string>
|
<string name="paste_none">Nenhuma partida PGN na área de transferência</string>
|
||||||
<string name="paste_db">Colado %1$s</string>
|
<string name="paste_db">Colado %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">%1$s partida na área de transferência</item>
|
|
||||||
<item quantity="many">%1$s partidas na área de transferência</item>
|
|
||||||
<item quantity="other">%1$s partidas na área de transferência</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Salvar esta partida PGN e abri-la no tabuleiro?</string>
|
|
||||||
<string name="clipboard_open_many">Salvar %1$s e abrir a primeira partida no tabuleiro? Todas as partidas serão mantidas na cópia local.</string>
|
|
||||||
<string name="clipboard_open">Abrir</string>
|
|
||||||
<string name="clipboard_database_name">Área de transferência</string>
|
|
||||||
<string name="opening_file">Abrindo o arquivo…</string>
|
<string name="opening_file">Abrindo o arquivo…</string>
|
||||||
<string name="file_failed">Não foi possível abrir o arquivo</string>
|
<string name="file_failed">Não foi possível abrir o arquivo</string>
|
||||||
<string name="file_no_games">Não há partidas de xadrez neste arquivo.</string>
|
<string name="file_no_games">Não há partidas de xadrez neste arquivo.</string>
|
||||||
|
|
@ -240,10 +230,15 @@
|
||||||
<string name="review_menu">Análise da partida</string>
|
<string name="review_menu">Análise da partida</string>
|
||||||
<string name="review_report_menu">Relatório da partida</string>
|
<string name="review_report_menu">Relatório da partida</string>
|
||||||
<string name="review_text">O motor avalia cada posição da linha principal. A partida em si não é alterada.</string>
|
<string name="review_text">O motor avalia cada posição da linha principal. A partida em si não é alterada.</string>
|
||||||
|
<string name="review_quality">Qualidade</string>
|
||||||
|
<string name="review_fast">Rápida</string>
|
||||||
|
<string name="review_normal">Normal</string>
|
||||||
|
<string name="review_deep">Profunda</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d min</string>
|
<string name="review_minutes">%d min</string>
|
||||||
<string name="review_start">Analisar</string>
|
<string name="review_start">Analisar</string>
|
||||||
<string name="review_fill">Completar</string>
|
<string name="review_fill">Completar</string>
|
||||||
|
<string name="review_again">Analisar de novo</string>
|
||||||
<string name="review_partial">%1$d de %2$d posições já estão avaliadas.</string>
|
<string name="review_partial">%1$d de %2$d posições já estão avaliadas.</string>
|
||||||
<string name="review_progress">Análise da partida · %1$d de %2$d</string>
|
<string name="review_progress">Análise da partida · %1$d de %2$d</string>
|
||||||
<string name="review_stop">Parar a análise</string>
|
<string name="review_stop">Parar a análise</string>
|
||||||
|
|
@ -257,10 +252,6 @@
|
||||||
<string name="review_inaccuracies">Imprecisões</string>
|
<string name="review_inaccuracies">Imprecisões</string>
|
||||||
<string name="review_mistakes">Erros</string>
|
<string name="review_mistakes">Erros</string>
|
||||||
<string name="review_blunders">Erros graves</string>
|
<string name="review_blunders">Erros graves</string>
|
||||||
<string name="review_great">Ótimo lance</string>
|
|
||||||
<string name="review_brilliant">Lance brilhante</string>
|
|
||||||
<string name="review_greats">Ótimos lances</string>
|
|
||||||
<string name="review_brilliants">Lances brilhantes</string>
|
|
||||||
<string name="review_missing">Não avaliadas: %d</string>
|
<string name="review_missing">Não avaliadas: %d</string>
|
||||||
<string name="review_failed">A análise parou</string>
|
<string name="review_failed">A análise parou</string>
|
||||||
<string name="review_resume">Continuar</string>
|
<string name="review_resume">Continuar</string>
|
||||||
|
|
@ -270,17 +261,13 @@
|
||||||
<string name="review_endgame">Final</string>
|
<string name="review_endgame">Final</string>
|
||||||
<string name="review_source">%1$s · %2$s nós por lance</string>
|
<string name="review_source">%1$s · %2$s nós por lance</string>
|
||||||
<string name="review_source_pgn" formatted="false">Avaliações do PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Avaliações do PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! e ! exigem o motor: o PGN traz só avaliações</string>
|
|
||||||
<string name="review_no_seconds">Esta análise ainda não procurou !! e !</string>
|
|
||||||
<string name="review_stale">Análise feita com outras definições do motor</string>
|
|
||||||
<string name="review_update">Atualizar</string>
|
|
||||||
<string name="review_engine">Analisar com o motor</string>
|
|
||||||
<string name="review_hide">Ocultar análise</string>
|
<string name="review_hide">Ocultar análise</string>
|
||||||
<string name="review_graph">Gráfico de avaliação</string>
|
<string name="review_graph">Gráfico de avaliação</string>
|
||||||
<string name="review_engine_paused">Em pausa: a partida está sendo analisada</string>
|
<string name="review_engine_paused">Em pausa: a partida está sendo analisada</string>
|
||||||
<string name="review_best_preview">Linha melhor · lance %1$d de %2$d</string>
|
<string name="review_best_preview">Linha melhor · lance %1$d de %2$d</string>
|
||||||
<string name="review_next">Ir para o próximo lance assim</string>
|
<string name="review_next">Ir para o próximo lance assim</string>
|
||||||
<string name="review_show_best">Mostrar a linha melhor no tabuleiro</string>
|
<string name="review_show_best">Mostrar a linha melhor no tabuleiro</string>
|
||||||
|
<string name="review_restart">Recomeçar</string>
|
||||||
<string name="review_graph_state">%1$s, avaliação %2$s</string>
|
<string name="review_graph_state">%1$s, avaliação %2$s</string>
|
||||||
<string name="review_start_position">Posição inicial</string>
|
<string name="review_start_position">Posição inicial</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -679,56 +666,4 @@
|
||||||
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
<string name="strength_range">%1$s, de %2$s a %3$s</string>
|
||||||
<string name="strength">Força</string>
|
<string name="strength">Força</string>
|
||||||
<string name="books_delete_cd">Excluir os livros de aberturas</string>
|
<string name="books_delete_cd">Excluir os livros de aberturas</string>
|
||||||
|
|
||||||
<!-- Preparação contra o adversário (tarefa 48). -->
|
|
||||||
<string name="players">Jogadores</string>
|
|
||||||
<string name="player_name_hint">Nome do jogador</string>
|
|
||||||
<string name="players_read_failed">Não foi possível ler os jogadores</string>
|
|
||||||
<string name="reading_players">A ler jogadores…</string>
|
|
||||||
<string name="no_named_players">Não há jogadores identificados nesta base</string>
|
|
||||||
<string name="player_not_found">Jogador não encontrado</string>
|
|
||||||
<string name="to_games">Voltar às partidas</string>
|
|
||||||
<string name="reset_search">Limpar pesquisa</string>
|
|
||||||
<string name="prepare_action">Preparar</string>
|
|
||||||
<string name="prep_choose_color">Escolha uma cor</string>
|
|
||||||
<string name="prep_against_player">Preparar contra %1$s</string>
|
|
||||||
<string name="prep_against_white">Contra as brancas</string>
|
|
||||||
<string name="prep_against_black">Contra as pretas</string>
|
|
||||||
<string name="prep_opponent">Preparar contra o adversário…</string>
|
|
||||||
<string name="prep_title">Preparação contra o adversário</string>
|
|
||||||
<string name="prep_close_engine_line">Feche primeiro a linha do motor</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">A pesquisa depois de um -- didático não está disponível</string>
|
|
||||||
<string name="prep_as_white">Brancas</string>
|
|
||||||
<string name="prep_as_black">Pretas</string>
|
|
||||||
<string name="prep_move_failed">Não foi possível jogar este lance</string>
|
|
||||||
<string name="prep_play_continuation">Jogar %1$s, %2$s, %3$s por cento</string>
|
|
||||||
<string name="prep_board_start">Tabuleiro, posição inicial. %1$s em baixo.</string>
|
|
||||||
<string name="prep_board_after">Tabuleiro, posição depois de %1$s. %2$s em baixo.</string>
|
|
||||||
<string name="turn_white">Jogam as brancas</string>
|
|
||||||
<string name="turn_black">Jogam as pretas</string>
|
|
||||||
<string name="prep_opponent_plays">O adversário joga</string>
|
|
||||||
<string name="prep_opponents_play">Os seus adversários jogam</string>
|
|
||||||
<string name="prep_after">depois de %1$s</string>
|
|
||||||
<string name="prep_beginning">início</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Não foi possível calcular as continuações</string>
|
|
||||||
<string name="prep_no_memory">Memória insuficiente para pesquisar nesta base</string>
|
|
||||||
<string name="prep_calculating">A calcular continuações…</string>
|
|
||||||
<string name="prep_position_absent">Esta posição não ocorre nas partidas de %1$s</string>
|
|
||||||
<string name="prep_position_absent_hint">Pode continuar no tabuleiro ou retroceder</string>
|
|
||||||
<string name="prep_all_ended">Todas as partidas terminaram aqui</string>
|
|
||||||
<string name="prep_ended_here">Terminaram aqui: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Sem continuação normal: %1$s</string>
|
|
||||||
<string name="to_game">Voltar à partida</string>
|
|
||||||
<string name="to_players">Voltar aos jogadores</string>
|
|
||||||
<string name="prep_choose_move">Escolha um lance</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s vitória</item><item quantity="many">%1$s vitórias</item><item quantity="other">%1$s vitórias</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s empate</item><item quantity="many">%1$s empates</item><item quantity="other">%1$s empates</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s derrota</item><item quantity="many">%1$s derrotas</item><item quantity="other">%1$s derrotas</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Resultados desconhecidos: %1$d; excluídos das percentagens.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Jogar</string>
|
|
||||||
<string name="prep_unknown_short">mais %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -38,8 +38,6 @@
|
||||||
<string name="to_start">В начало</string>
|
<string name="to_start">В начало</string>
|
||||||
<string name="move_back">Ход назад</string>
|
<string name="move_back">Ход назад</string>
|
||||||
<string name="move_forward">Ход вперёд</string>
|
<string name="move_forward">Ход вперёд</string>
|
||||||
<string name="move_back_hint">Предыдущий ход. Удерживайте для перехода в начало</string>
|
|
||||||
<string name="move_forward_hint">Следующий ход. Удерживайте для перехода в конец линии</string>
|
|
||||||
<string name="to_end">В конец линии</string>
|
<string name="to_end">В конец линии</string>
|
||||||
<string name="next_moves">Дальше:</string>
|
<string name="next_moves">Дальше:</string>
|
||||||
<string name="board_description">Доска, позиция после %1$s</string>
|
<string name="board_description">Доска, позиция после %1$s</string>
|
||||||
|
|
@ -115,7 +113,8 @@
|
||||||
<string name="about">О программе</string>
|
<string name="about">О программе</string>
|
||||||
<string name="build_full">Stockfish уже внутри</string>
|
<string name="build_full">Stockfish уже внутри</string>
|
||||||
<string name="build_light">Stockfish скачивается в приложении</string>
|
<string name="build_light">Stockfish скачивается в приложении</string>
|
||||||
<string name="about_text">Шахматные базы, анализ партий и игра с компьютером. Ваши файлы только читаются и никогда не меняются.</string>
|
<string name="alpha">альфа</string>
|
||||||
|
<string name="about_text">Просмотр шахматных баз: PGN, ChessBase, архивы. Файлы только читаются и никогда не меняются.</string>
|
||||||
<string name="licenses">Лицензии и авторы</string>
|
<string name="licenses">Лицензии и авторы</string>
|
||||||
<string name="website">Сайт и исходный код</string>
|
<string name="website">Сайт и исходный код</string>
|
||||||
|
|
||||||
|
|
@ -223,16 +222,6 @@
|
||||||
<string name="add_paste_hint">Партии, скопированные в другом приложении</string>
|
<string name="add_paste_hint">Партии, скопированные в другом приложении</string>
|
||||||
<string name="paste_none">В буфере нет партий в формате PGN</string>
|
<string name="paste_none">В буфере нет партий в формате PGN</string>
|
||||||
<string name="paste_db">Из буфера, %1$s</string>
|
<string name="paste_db">Из буфера, %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">%1$s партия в буфере обмена</item>
|
|
||||||
<item quantity="few">%1$s партии в буфере обмена</item>
|
|
||||||
<item quantity="many">%1$s партий в буфере обмена</item>
|
|
||||||
<item quantity="other">%1$s партии в буфере обмена</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Сохранить PGN-партию и открыть её на доске?</string>
|
|
||||||
<string name="clipboard_open_many">Сохранить %1$s и открыть первую партию на доске? Все партии останутся в локальной копии.</string>
|
|
||||||
<string name="clipboard_open">Открыть</string>
|
|
||||||
<string name="clipboard_database_name">Буфер обмена</string>
|
|
||||||
<string name="opening_file">Открываю файл…</string>
|
<string name="opening_file">Открываю файл…</string>
|
||||||
<string name="file_failed">Файл не открылся</string>
|
<string name="file_failed">Файл не открылся</string>
|
||||||
<string name="file_no_games">В этом файле нет шахматных партий.</string>
|
<string name="file_no_games">В этом файле нет шахматных партий.</string>
|
||||||
|
|
@ -245,10 +234,15 @@
|
||||||
<string name="review_menu">Анализ партии</string>
|
<string name="review_menu">Анализ партии</string>
|
||||||
<string name="review_report_menu">Отчёт по партии</string>
|
<string name="review_report_menu">Отчёт по партии</string>
|
||||||
<string name="review_text">Движок оценит каждую позицию основной линии. Сама партия не изменится.</string>
|
<string name="review_text">Движок оценит каждую позицию основной линии. Сама партия не изменится.</string>
|
||||||
|
<string name="review_quality">Качество</string>
|
||||||
|
<string name="review_fast">Быстро</string>
|
||||||
|
<string name="review_normal">Обычно</string>
|
||||||
|
<string name="review_deep">Глубоко</string>
|
||||||
<string name="review_seconds">%d с</string>
|
<string name="review_seconds">%d с</string>
|
||||||
<string name="review_minutes">%d мин</string>
|
<string name="review_minutes">%d мин</string>
|
||||||
<string name="review_start">Анализировать</string>
|
<string name="review_start">Анализировать</string>
|
||||||
<string name="review_fill">Дополнить</string>
|
<string name="review_fill">Дополнить</string>
|
||||||
|
<string name="review_again">Анализировать заново</string>
|
||||||
<string name="review_partial">Уже оценено позиций: %1$d из %2$d.</string>
|
<string name="review_partial">Уже оценено позиций: %1$d из %2$d.</string>
|
||||||
<string name="review_progress">Анализ партии · %1$d из %2$d</string>
|
<string name="review_progress">Анализ партии · %1$d из %2$d</string>
|
||||||
<string name="review_stop">Остановить анализ</string>
|
<string name="review_stop">Остановить анализ</string>
|
||||||
|
|
@ -262,10 +256,6 @@
|
||||||
<string name="review_inaccuracies">Неточности</string>
|
<string name="review_inaccuracies">Неточности</string>
|
||||||
<string name="review_mistakes">Ошибки</string>
|
<string name="review_mistakes">Ошибки</string>
|
||||||
<string name="review_blunders">Зевки</string>
|
<string name="review_blunders">Зевки</string>
|
||||||
<string name="review_great">Замечательный ход</string>
|
|
||||||
<string name="review_brilliant">Блестящий ход</string>
|
|
||||||
<string name="review_greats">Замечательный</string>
|
|
||||||
<string name="review_brilliants">Блестящий</string>
|
|
||||||
<string name="review_missing">Без оценки: %d</string>
|
<string name="review_missing">Без оценки: %d</string>
|
||||||
<string name="review_failed">Анализ прервался</string>
|
<string name="review_failed">Анализ прервался</string>
|
||||||
<string name="review_resume">Продолжить</string>
|
<string name="review_resume">Продолжить</string>
|
||||||
|
|
@ -275,17 +265,13 @@
|
||||||
<string name="review_endgame">Эндшпиль</string>
|
<string name="review_endgame">Эндшпиль</string>
|
||||||
<string name="review_source">%1$s · %2$s узлов на ход</string>
|
<string name="review_source">%1$s · %2$s узлов на ход</string>
|
||||||
<string name="review_source_pgn" formatted="false">Оценки из PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Оценки из PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! и ! ставит только движок: в PGN есть лишь оценки</string>
|
|
||||||
<string name="review_no_seconds">В этом анализе !! и ! ещё не искали</string>
|
|
||||||
<string name="review_stale">Анализ сделан с прежними настройками движка</string>
|
|
||||||
<string name="review_update">Обновить</string>
|
|
||||||
<string name="review_engine">Проанализировать движком</string>
|
|
||||||
<string name="review_hide">Скрыть анализ</string>
|
<string name="review_hide">Скрыть анализ</string>
|
||||||
<string name="review_graph">График оценки</string>
|
<string name="review_graph">График оценки</string>
|
||||||
<string name="review_engine_paused">Пауза: идёт анализ партии</string>
|
<string name="review_engine_paused">Пауза: идёт анализ партии</string>
|
||||||
<string name="review_best_preview">Лучшая линия · ход %1$d из %2$d</string>
|
<string name="review_best_preview">Лучшая линия · ход %1$d из %2$d</string>
|
||||||
<string name="review_next">Перейти к следующему такому ходу</string>
|
<string name="review_next">Перейти к следующему такому ходу</string>
|
||||||
<string name="review_show_best">Показать лучшую линию на доске</string>
|
<string name="review_show_best">Показать лучшую линию на доске</string>
|
||||||
|
<string name="review_restart">Заново</string>
|
||||||
<string name="review_graph_state">%1$s, оценка %2$s</string>
|
<string name="review_graph_state">%1$s, оценка %2$s</string>
|
||||||
<string name="review_start_position">Начальная позиция</string>
|
<string name="review_start_position">Начальная позиция</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -687,71 +673,4 @@
|
||||||
<string name="strength_range">%1$s, от %2$s до %3$s</string>
|
<string name="strength_range">%1$s, от %2$s до %3$s</string>
|
||||||
<string name="strength">Сила</string>
|
<string name="strength">Сила</string>
|
||||||
<string name="books_delete_cd">Удалить дебютные книги</string>
|
<string name="books_delete_cd">Удалить дебютные книги</string>
|
||||||
|
|
||||||
<!-- Подготовка к сопернику (задача 48). -->
|
|
||||||
<string name="players">Игроки</string>
|
|
||||||
<string name="player_name_hint">Имя игрока</string>
|
|
||||||
<string name="players_read_failed">Не удалось прочитать игроков</string>
|
|
||||||
<string name="reading_players">Читаю игроков…</string>
|
|
||||||
<string name="no_named_players">В этой базе нет именованных игроков</string>
|
|
||||||
<string name="player_not_found">Игрок не найден</string>
|
|
||||||
<string name="to_games">К партиям</string>
|
|
||||||
<string name="reset_search">Сбросить поиск</string>
|
|
||||||
<string name="prepare_action">Подготовиться</string>
|
|
||||||
<string name="prep_choose_color">Выберите цвет</string>
|
|
||||||
<string name="prep_against_player">Подготовиться к %1$s</string>
|
|
||||||
<string name="prep_against_white">Против белых</string>
|
|
||||||
<string name="prep_against_black">Против чёрных</string>
|
|
||||||
<string name="prep_opponent">Подготовиться к сопернику…</string>
|
|
||||||
<string name="prep_title">Подготовка к сопернику</string>
|
|
||||||
<string name="prep_close_engine_line">Сначала закройте линию движка</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">Поиск после учебного -- недоступен</string>
|
|
||||||
<string name="prep_as_white">Белыми</string>
|
|
||||||
<string name="prep_as_black">Чёрными</string>
|
|
||||||
<string name="prep_move_failed">Не удалось сделать ход</string>
|
|
||||||
<string name="prep_play_continuation">Сыграть %1$s, %2$s, %3$s процентов</string>
|
|
||||||
<string name="prep_board_start">Доска, начальная позиция. Внизу %1$s.</string>
|
|
||||||
<string name="prep_board_after">Доска, позиция после %1$s. Внизу %2$s.</string>
|
|
||||||
<string name="turn_white">ход белых</string>
|
|
||||||
<string name="turn_black">ход чёрных</string>
|
|
||||||
<string name="prep_opponent_plays">Соперник играет</string>
|
|
||||||
<string name="prep_opponents_play">Его оппоненты играют</string>
|
|
||||||
<string name="prep_after">после %1$s</string>
|
|
||||||
<string name="prep_beginning">начало</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Не удалось посчитать продолжения</string>
|
|
||||||
<string name="prep_no_memory">Недостаточно памяти для поиска по этой базе</string>
|
|
||||||
<string name="prep_calculating">Считаю продолжения…</string>
|
|
||||||
<string name="prep_position_absent">В партиях %1$s этой позиции нет</string>
|
|
||||||
<string name="prep_position_absent_hint">Можно продолжить на доске или вернуться назад</string>
|
|
||||||
<string name="prep_all_ended">Все партии здесь закончились</string>
|
|
||||||
<string name="prep_ended_here">Здесь закончились: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Нет обычного продолжения: %1$s</string>
|
|
||||||
<string name="to_game">К партии</string>
|
|
||||||
<string name="to_players">К игрокам</string>
|
|
||||||
<string name="prep_choose_move">Выберите ход</string>
|
|
||||||
<plurals name="prep_wins">
|
|
||||||
<item quantity="one">%1$s победа</item>
|
|
||||||
<item quantity="few">%1$s победы</item>
|
|
||||||
<item quantity="many">%1$s побед</item>
|
|
||||||
<item quantity="other">%1$s победы</item>
|
|
||||||
</plurals>
|
|
||||||
<plurals name="prep_draws">
|
|
||||||
<item quantity="one">%1$s ничья</item>
|
|
||||||
<item quantity="few">%1$s ничьи</item>
|
|
||||||
<item quantity="many">%1$s ничьих</item>
|
|
||||||
<item quantity="other">%1$s ничьи</item>
|
|
||||||
</plurals>
|
|
||||||
<plurals name="prep_losses">
|
|
||||||
<item quantity="one">%1$s поражение</item>
|
|
||||||
<item quantity="few">%1$s поражения</item>
|
|
||||||
<item quantity="many">%1$s поражений</item>
|
|
||||||
<item quantity="other">%1$s поражения</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Неизвестных исходов: %1$d; они не входят в знаменатель процентов.</string>
|
|
||||||
<string name="prep_continuation_description">%1$s. %2$d из %3$s, %4$s процентов. Результаты %5$s: %6$s, %7$s, %8$s; %9$s, %10$s и %11$s процентов. %12$s Сыграть.</string>
|
|
||||||
<string name="prep_play">Сыграть</string>
|
|
||||||
<string name="prep_unknown_short">ещё %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,6 @@
|
||||||
<string name="to_start">Boshiga</string>
|
<string name="to_start">Boshiga</string>
|
||||||
<string name="move_back">Bir yurish orqaga</string>
|
<string name="move_back">Bir yurish orqaga</string>
|
||||||
<string name="move_forward">Bir yurish oldinga</string>
|
<string name="move_forward">Bir yurish oldinga</string>
|
||||||
<string name="move_back_hint">Oldingi yurish. Boshiga oʻtish uchun bosib turing</string>
|
|
||||||
<string name="move_forward_hint">Keyingi yurish. Liniya oxiriga oʻtish uchun bosib turing</string>
|
|
||||||
<string name="to_end">Liniya oxiriga</string>
|
<string name="to_end">Liniya oxiriga</string>
|
||||||
<string name="next_moves">Keyin:</string>
|
<string name="next_moves">Keyin:</string>
|
||||||
<string name="board_description">Taxta, %1$sdan keyingi pozitsiya</string>
|
<string name="board_description">Taxta, %1$sdan keyingi pozitsiya</string>
|
||||||
|
|
@ -114,7 +112,8 @@
|
||||||
<string name="about">Dastur haqida</string>
|
<string name="about">Dastur haqida</string>
|
||||||
<string name="build_full">Stockfish ichki</string>
|
<string name="build_full">Stockfish ichki</string>
|
||||||
<string name="build_light">Stockfish ilovada yuklab olinadi</string>
|
<string name="build_light">Stockfish ilovada yuklab olinadi</string>
|
||||||
<string name="about_text">Shaxmat bazalari, partiyalar tahlili va kompyuter bilan oʻyin. Fayllaringiz faqat oʻqiladi, hech qachon oʻzgartirilmaydi.</string>
|
<string name="alpha">alfa</string>
|
||||||
|
<string name="about_text">Shaxmat bazalarini koʻrish vositasi: PGN, ChessBase, arxivlar. Fayllar faqat oʻqiladi, hech qachon oʻzgartirilmaydi.</string>
|
||||||
<string name="licenses">Litsenziyalar va mualliflar</string>
|
<string name="licenses">Litsenziyalar va mualliflar</string>
|
||||||
<string name="website">Sayt va manba kodi</string>
|
<string name="website">Sayt va manba kodi</string>
|
||||||
|
|
||||||
|
|
@ -216,14 +215,6 @@
|
||||||
<string name="add_paste_hint">Boshqa ilovada nusxalangan partiyalar</string>
|
<string name="add_paste_hint">Boshqa ilovada nusxalangan partiyalar</string>
|
||||||
<string name="paste_none">Almashish buferida PGN partiyalar yoʻq</string>
|
<string name="paste_none">Almashish buferida PGN partiyalar yoʻq</string>
|
||||||
<string name="paste_db">Qoʻyildi: %1$s</string>
|
<string name="paste_db">Qoʻyildi: %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">Almashish buferida partiya</item>
|
|
||||||
<item quantity="other">Almashish buferida partiyalar</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Bu PGN partiyani saqlab, doskada ochish?</string>
|
|
||||||
<string name="clipboard_open_many">%1$s saqlab, birinchi partiyani doskada ochish? Barcha partiyalar mahalliy nusxada saqlanadi.</string>
|
|
||||||
<string name="clipboard_open">Ochish</string>
|
|
||||||
<string name="clipboard_database_name">Almashish buferi</string>
|
|
||||||
<string name="opening_file">Fayl ochilmoqda…</string>
|
<string name="opening_file">Fayl ochilmoqda…</string>
|
||||||
<string name="file_failed">Faylni ochib boʻlmadi</string>
|
<string name="file_failed">Faylni ochib boʻlmadi</string>
|
||||||
<string name="file_no_games">Bu faylda shaxmat partiyalari yoʻq.</string>
|
<string name="file_no_games">Bu faylda shaxmat partiyalari yoʻq.</string>
|
||||||
|
|
@ -235,10 +226,15 @@
|
||||||
<string name="review_menu">Partiya tahlili</string>
|
<string name="review_menu">Partiya tahlili</string>
|
||||||
<string name="review_report_menu">Partiya hisoboti</string>
|
<string name="review_report_menu">Partiya hisoboti</string>
|
||||||
<string name="review_text">Dvigatel asosiy liniyaning har bir pozitsiyasini baholaydi. Partiyaning oʻzi oʻzgarmaydi.</string>
|
<string name="review_text">Dvigatel asosiy liniyaning har bir pozitsiyasini baholaydi. Partiyaning oʻzi oʻzgarmaydi.</string>
|
||||||
|
<string name="review_quality">Sifat</string>
|
||||||
|
<string name="review_fast">Tez</string>
|
||||||
|
<string name="review_normal">Oddiy</string>
|
||||||
|
<string name="review_deep">Chuqur</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d daq.</string>
|
<string name="review_minutes">%d daq.</string>
|
||||||
<string name="review_start">Tahlil qilish</string>
|
<string name="review_start">Tahlil qilish</string>
|
||||||
<string name="review_fill">Toʻldirish</string>
|
<string name="review_fill">Toʻldirish</string>
|
||||||
|
<string name="review_again">Qayta tahlil qilish</string>
|
||||||
<string name="review_partial">%2$d ta pozitsiyadan %1$d tasi allaqachon baholangan.</string>
|
<string name="review_partial">%2$d ta pozitsiyadan %1$d tasi allaqachon baholangan.</string>
|
||||||
<string name="review_progress">Partiya tahlili · %1$d / %2$d</string>
|
<string name="review_progress">Partiya tahlili · %1$d / %2$d</string>
|
||||||
<string name="review_stop">Tahlilni toʻxtatish</string>
|
<string name="review_stop">Tahlilni toʻxtatish</string>
|
||||||
|
|
@ -252,10 +248,6 @@
|
||||||
<string name="review_inaccuracies">Noaniqliklar</string>
|
<string name="review_inaccuracies">Noaniqliklar</string>
|
||||||
<string name="review_mistakes">Xatolar</string>
|
<string name="review_mistakes">Xatolar</string>
|
||||||
<string name="review_blunders">Qoʻpol xatolar</string>
|
<string name="review_blunders">Qoʻpol xatolar</string>
|
||||||
<string name="review_great">Kuchli yurish</string>
|
|
||||||
<string name="review_brilliant">Ajoyib yurish</string>
|
|
||||||
<string name="review_greats">Kuchli yurishlar</string>
|
|
||||||
<string name="review_brilliants">Ajoyib yurishlar</string>
|
|
||||||
<string name="review_missing">Baholanmagan: %d</string>
|
<string name="review_missing">Baholanmagan: %d</string>
|
||||||
<string name="review_failed">Tahlil toʻxtadi</string>
|
<string name="review_failed">Tahlil toʻxtadi</string>
|
||||||
<string name="review_resume">Davom etish</string>
|
<string name="review_resume">Davom etish</string>
|
||||||
|
|
@ -265,17 +257,13 @@
|
||||||
<string name="review_endgame">Endshpil</string>
|
<string name="review_endgame">Endshpil</string>
|
||||||
<string name="review_source">%1$s · har yurishga %2$s tugun</string>
|
<string name="review_source">%1$s · har yurishga %2$s tugun</string>
|
||||||
<string name="review_source_pgn" formatted="false">PGNdagi baholar ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">PGNdagi baholar ([%eval])</string>
|
||||||
<string name="review_no_notes">!! va ! faqat dvigatel bilan: PGNda faqat baholar bor</string>
|
|
||||||
<string name="review_no_seconds">Bu tahlilda !! va ! hali qidirilmagan</string>
|
|
||||||
<string name="review_stale">Tahlil dvigatelning boshqa sozlamalari bilan qilingan</string>
|
|
||||||
<string name="review_update">Yangilash</string>
|
|
||||||
<string name="review_engine">Dvigatel bilan tahlil qilish</string>
|
|
||||||
<string name="review_hide">Tahlilni yashirish</string>
|
<string name="review_hide">Tahlilni yashirish</string>
|
||||||
<string name="review_graph">Baho grafigi</string>
|
<string name="review_graph">Baho grafigi</string>
|
||||||
<string name="review_engine_paused">Pauza: partiya tahlil qilinmoqda</string>
|
<string name="review_engine_paused">Pauza: partiya tahlil qilinmoqda</string>
|
||||||
<string name="review_best_preview">Yaxshiroq liniya · yurish %1$d / %2$d</string>
|
<string name="review_best_preview">Yaxshiroq liniya · yurish %1$d / %2$d</string>
|
||||||
<string name="review_next">Keyingi shunday yurishga oʻtish</string>
|
<string name="review_next">Keyingi shunday yurishga oʻtish</string>
|
||||||
<string name="review_show_best">Yaxshiroq liniyani taxtada koʻrsatish</string>
|
<string name="review_show_best">Yaxshiroq liniyani taxtada koʻrsatish</string>
|
||||||
|
<string name="review_restart">Qaytadan boshlash</string>
|
||||||
<string name="review_graph_state">%1$s, baho %2$s</string>
|
<string name="review_graph_state">%1$s, baho %2$s</string>
|
||||||
<string name="review_start_position">Boshlangʻich pozitsiya</string>
|
<string name="review_start_position">Boshlangʻich pozitsiya</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -668,56 +656,4 @@
|
||||||
<string name="strength_range">%1$s, %2$s dan %3$s gacha</string>
|
<string name="strength_range">%1$s, %2$s dan %3$s gacha</string>
|
||||||
<string name="strength">Kuch</string>
|
<string name="strength">Kuch</string>
|
||||||
<string name="books_delete_cd">Debyut kitoblarini o‘chirish</string>
|
<string name="books_delete_cd">Debyut kitoblarini o‘chirish</string>
|
||||||
|
|
||||||
<!-- Raqibga tayyorgarlik (48-vazifa). -->
|
|
||||||
<string name="players">Oʻyinchilar</string>
|
|
||||||
<string name="player_name_hint">Oʻyinchi ismi</string>
|
|
||||||
<string name="players_read_failed">Oʻyinchilarni oʻqib boʻlmadi</string>
|
|
||||||
<string name="reading_players">Oʻyinchilar oʻqilmoqda…</string>
|
|
||||||
<string name="no_named_players">Bu bazada nomi koʻrsatilgan oʻyinchilar yoʻq</string>
|
|
||||||
<string name="player_not_found">Oʻyinchi topilmadi</string>
|
|
||||||
<string name="to_games">Partiyalarga qaytish</string>
|
|
||||||
<string name="reset_search">Qidiruvni tozalash</string>
|
|
||||||
<string name="prepare_action">Tayyorlanish</string>
|
|
||||||
<string name="prep_choose_color">Rangni tanlang</string>
|
|
||||||
<string name="prep_against_player">Raqibga tayyorlanish %1$s</string>
|
|
||||||
<string name="prep_against_white">Oqlarga qarshi</string>
|
|
||||||
<string name="prep_against_black">Qoralarga qarshi</string>
|
|
||||||
<string name="prep_opponent">Raqibga tayyorlanish…</string>
|
|
||||||
<string name="prep_title">Raqibga tayyorgarlik</string>
|
|
||||||
<string name="prep_close_engine_line">Avval dvigatel chizigʻini yoping</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">Oʻquv -- dan keyin qidirish mavjud emas</string>
|
|
||||||
<string name="prep_as_white">Oqlar</string>
|
|
||||||
<string name="prep_as_black">Qoralar</string>
|
|
||||||
<string name="prep_move_failed">Bu yurishni bajarib boʻlmadi</string>
|
|
||||||
<string name="prep_play_continuation">%1$s yurish, %2$s, %3$s foiz</string>
|
|
||||||
<string name="prep_board_start">Doska, boshlangʻich pozitsiya. Pastda %1$s.</string>
|
|
||||||
<string name="prep_board_after">Doska, %1$s dan keyingi pozitsiya. Pastda %2$s.</string>
|
|
||||||
<string name="turn_white">Oqlar yurishi</string>
|
|
||||||
<string name="turn_black">Qoralar yurishi</string>
|
|
||||||
<string name="prep_opponent_plays">Raqib yuradi</string>
|
|
||||||
<string name="prep_opponents_play">Uning raqiblari yuradi</string>
|
|
||||||
<string name="prep_after">%1$s dan keyin</string>
|
|
||||||
<string name="prep_beginning">boshlanishi</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Davomlarni hisoblab boʻlmadi</string>
|
|
||||||
<string name="prep_no_memory">Bu bazadan qidirish uchun xotira yetarli emas</string>
|
|
||||||
<string name="prep_calculating">Davomlar hisoblanmoqda…</string>
|
|
||||||
<string name="prep_position_absent">%1$s partiyalarida bu pozitsiya yoʻq</string>
|
|
||||||
<string name="prep_position_absent_hint">Doskada davom etishingiz yoki orqaga qaytishingiz mumkin</string>
|
|
||||||
<string name="prep_all_ended">Barcha partiyalar shu yerda tugagan</string>
|
|
||||||
<string name="prep_ended_here">Shu yerda tugagan: %1$s</string>
|
|
||||||
<string name="prep_no_normal">Oddiy davom yoʻq: %1$s</string>
|
|
||||||
<string name="to_game">Partiyaga qaytish</string>
|
|
||||||
<string name="to_players">Oʻyinchilarga qaytish</string>
|
|
||||||
<string name="prep_choose_move">Yurishni tanlang</string>
|
|
||||||
<plurals name="prep_wins"><item quantity="one">%1$s gʻalaba</item><item quantity="other">%1$s gʻalaba</item></plurals>
|
|
||||||
<plurals name="prep_draws"><item quantity="one">%1$s durang</item><item quantity="other">%1$s durang</item></plurals>
|
|
||||||
<plurals name="prep_losses"><item quantity="one">%1$s magʻlubiyat</item><item quantity="other">%1$s magʻlubiyat</item></plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Nomaʼlum natijalar: %1$d; ular foizlarga kiritilmaydi.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Yurish</string>
|
|
||||||
<string name="prep_unknown_short">yana %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -37,8 +37,6 @@
|
||||||
<string name="to_start">To the start</string>
|
<string name="to_start">To the start</string>
|
||||||
<string name="move_back">Move back</string>
|
<string name="move_back">Move back</string>
|
||||||
<string name="move_forward">Move forward</string>
|
<string name="move_forward">Move forward</string>
|
||||||
<string name="move_back_hint">Previous move. Hold for the first position</string>
|
|
||||||
<string name="move_forward_hint">Next move. Hold for the end of the line</string>
|
|
||||||
<string name="to_end">To the end of the line</string>
|
<string name="to_end">To the end of the line</string>
|
||||||
<string name="next_moves">Next:</string>
|
<string name="next_moves">Next:</string>
|
||||||
<string name="board_description">Board, position after %1$s</string>
|
<string name="board_description">Board, position after %1$s</string>
|
||||||
|
|
@ -114,7 +112,8 @@
|
||||||
<string name="about">About</string>
|
<string name="about">About</string>
|
||||||
<string name="build_full">Stockfish built in</string>
|
<string name="build_full">Stockfish built in</string>
|
||||||
<string name="build_light">Stockfish downloaded in the app</string>
|
<string name="build_light">Stockfish downloaded in the app</string>
|
||||||
<string name="about_text">Chess databases, game analysis and play against the computer. Your files are only read, never changed.</string>
|
<string name="alpha">alpha</string>
|
||||||
|
<string name="about_text">A viewer of chess databases: PGN, ChessBase, archives. Files are only read, never changed.</string>
|
||||||
<string name="licenses">Licenses and authors</string>
|
<string name="licenses">Licenses and authors</string>
|
||||||
<string name="website">Website and source code</string>
|
<string name="website">Website and source code</string>
|
||||||
|
|
||||||
|
|
@ -218,14 +217,6 @@
|
||||||
<string name="add_paste_hint">Games copied in another app</string>
|
<string name="add_paste_hint">Games copied in another app</string>
|
||||||
<string name="paste_none">No PGN games in the clipboard</string>
|
<string name="paste_none">No PGN games in the clipboard</string>
|
||||||
<string name="paste_db">Pasted %1$s</string>
|
<string name="paste_db">Pasted %1$s</string>
|
||||||
<plurals name="clipboard_open_title">
|
|
||||||
<item quantity="one">Game in clipboard</item>
|
|
||||||
<item quantity="other">Games in clipboard</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="clipboard_open_one">Save this PGN game and open it on the board?</string>
|
|
||||||
<string name="clipboard_open_many">Save %1$s and open the first game on the board? All games will be kept in the local copy.</string>
|
|
||||||
<string name="clipboard_open">Open</string>
|
|
||||||
<string name="clipboard_database_name">Clipboard</string>
|
|
||||||
<string name="opening_file">Opening the file…</string>
|
<string name="opening_file">Opening the file…</string>
|
||||||
<string name="file_failed">Couldn’t open the file</string>
|
<string name="file_failed">Couldn’t open the file</string>
|
||||||
<string name="file_no_games">There are no chess games in this file.</string>
|
<string name="file_no_games">There are no chess games in this file.</string>
|
||||||
|
|
@ -238,10 +229,15 @@
|
||||||
<string name="review_menu">Game analysis</string>
|
<string name="review_menu">Game analysis</string>
|
||||||
<string name="review_report_menu">Game report</string>
|
<string name="review_report_menu">Game report</string>
|
||||||
<string name="review_text">The engine evaluates every position of the main line. The game itself is not changed.</string>
|
<string name="review_text">The engine evaluates every position of the main line. The game itself is not changed.</string>
|
||||||
|
<string name="review_quality">Quality</string>
|
||||||
|
<string name="review_fast">Fast</string>
|
||||||
|
<string name="review_normal">Normal</string>
|
||||||
|
<string name="review_deep">Deep</string>
|
||||||
<string name="review_seconds">%d s</string>
|
<string name="review_seconds">%d s</string>
|
||||||
<string name="review_minutes">%d min</string>
|
<string name="review_minutes">%d min</string>
|
||||||
<string name="review_start">Analyse</string>
|
<string name="review_start">Analyse</string>
|
||||||
<string name="review_fill">Fill in</string>
|
<string name="review_fill">Fill in</string>
|
||||||
|
<string name="review_again">Analyse again</string>
|
||||||
<string name="review_partial">%1$d of %2$d positions are evaluated already.</string>
|
<string name="review_partial">%1$d of %2$d positions are evaluated already.</string>
|
||||||
<string name="review_progress">Game analysis · %1$d of %2$d</string>
|
<string name="review_progress">Game analysis · %1$d of %2$d</string>
|
||||||
<string name="review_stop">Stop the analysis</string>
|
<string name="review_stop">Stop the analysis</string>
|
||||||
|
|
@ -255,10 +251,6 @@
|
||||||
<string name="review_inaccuracies">Inaccuracies</string>
|
<string name="review_inaccuracies">Inaccuracies</string>
|
||||||
<string name="review_mistakes">Mistakes</string>
|
<string name="review_mistakes">Mistakes</string>
|
||||||
<string name="review_blunders">Blunders</string>
|
<string name="review_blunders">Blunders</string>
|
||||||
<string name="review_great">Great move</string>
|
|
||||||
<string name="review_brilliant">Brilliant move</string>
|
|
||||||
<string name="review_greats">Great moves</string>
|
|
||||||
<string name="review_brilliants">Brilliant moves</string>
|
|
||||||
<string name="review_missing">Not evaluated: %d</string>
|
<string name="review_missing">Not evaluated: %d</string>
|
||||||
<string name="review_failed">The analysis stopped</string>
|
<string name="review_failed">The analysis stopped</string>
|
||||||
<string name="review_resume">Continue</string>
|
<string name="review_resume">Continue</string>
|
||||||
|
|
@ -268,17 +260,13 @@
|
||||||
<string name="review_endgame">Endgame</string>
|
<string name="review_endgame">Endgame</string>
|
||||||
<string name="review_source">%1$s · %2$s nodes per move</string>
|
<string name="review_source">%1$s · %2$s nodes per move</string>
|
||||||
<string name="review_source_pgn" formatted="false">Evaluations from the PGN ([%eval])</string>
|
<string name="review_source_pgn" formatted="false">Evaluations from the PGN ([%eval])</string>
|
||||||
<string name="review_no_notes">!! and ! need the engine: the PGN has evaluations only</string>
|
|
||||||
<string name="review_no_seconds">!! and ! were not looked for in this analysis</string>
|
|
||||||
<string name="review_stale">This analysis was made with other engine settings</string>
|
|
||||||
<string name="review_update">Update</string>
|
|
||||||
<string name="review_engine">Analyse with the engine</string>
|
|
||||||
<string name="review_hide">Hide analysis</string>
|
<string name="review_hide">Hide analysis</string>
|
||||||
<string name="review_graph">Evaluation graph</string>
|
<string name="review_graph">Evaluation graph</string>
|
||||||
<string name="review_engine_paused">Paused: the game is being analysed</string>
|
<string name="review_engine_paused">Paused: the game is being analysed</string>
|
||||||
<string name="review_best_preview">Better line · move %1$d of %2$d</string>
|
<string name="review_best_preview">Better line · move %1$d of %2$d</string>
|
||||||
<string name="review_next">Go to the next such move</string>
|
<string name="review_next">Go to the next such move</string>
|
||||||
<string name="review_show_best">Show the better line on the board</string>
|
<string name="review_show_best">Show the better line on the board</string>
|
||||||
|
<string name="review_restart">Start over</string>
|
||||||
<string name="review_graph_state">%1$s, evaluation %2$s</string>
|
<string name="review_graph_state">%1$s, evaluation %2$s</string>
|
||||||
<string name="review_start_position">Start position</string>
|
<string name="review_start_position">Start position</string>
|
||||||
<plurals name="review_estimate">
|
<plurals name="review_estimate">
|
||||||
|
|
@ -673,65 +661,4 @@
|
||||||
<string name="strength_range">%1$s, from %2$s to %3$s</string>
|
<string name="strength_range">%1$s, from %2$s to %3$s</string>
|
||||||
<string name="strength">Strength</string>
|
<string name="strength">Strength</string>
|
||||||
<string name="books_delete_cd">Delete the opening books</string>
|
<string name="books_delete_cd">Delete the opening books</string>
|
||||||
|
|
||||||
<!-- Opponent preparation (task 48). -->
|
|
||||||
<string name="players">Players</string>
|
|
||||||
<string name="player_name_hint">Player name</string>
|
|
||||||
<string name="players_read_failed">Could not read players</string>
|
|
||||||
<string name="reading_players">Reading players…</string>
|
|
||||||
<string name="no_named_players">There are no named players in this database</string>
|
|
||||||
<string name="player_not_found">Player not found</string>
|
|
||||||
<string name="to_games">Back to games</string>
|
|
||||||
<string name="reset_search">Clear search</string>
|
|
||||||
<string name="prepare_action">Prepare</string>
|
|
||||||
<string name="prep_choose_color">Choose a color</string>
|
|
||||||
<string name="prep_against_player">Prepare against %1$s</string>
|
|
||||||
<string name="prep_against_white">Against White</string>
|
|
||||||
<string name="prep_against_black">Against Black</string>
|
|
||||||
<string name="prep_opponent">Prepare for opponent…</string>
|
|
||||||
<string name="prep_title">Opponent preparation</string>
|
|
||||||
<string name="prep_close_engine_line">Close the engine line first</string>
|
|
||||||
<!--suppress TypographyDashes: literal PGN null move -->
|
|
||||||
<string name="prep_null_move_unavailable">Search after a teaching -- is unavailable</string>
|
|
||||||
<string name="prep_as_white">White</string>
|
|
||||||
<string name="prep_as_black">Black</string>
|
|
||||||
<string name="prep_move_failed">Could not play this move</string>
|
|
||||||
<string name="prep_play_continuation">Play %1$s, %2$s, %3$s percent</string>
|
|
||||||
<string name="prep_board_start">Board, starting position. %1$s at the bottom.</string>
|
|
||||||
<string name="prep_board_after">Board, position after %1$s. %2$s at the bottom.</string>
|
|
||||||
<string name="turn_white">White to move</string>
|
|
||||||
<string name="turn_black">Black to move</string>
|
|
||||||
<string name="prep_opponent_plays">Opponent plays</string>
|
|
||||||
<string name="prep_opponents_play">Their opponents play</string>
|
|
||||||
<string name="prep_after">after %1$s</string>
|
|
||||||
<string name="prep_beginning">start</string>
|
|
||||||
<string name="prep_context_description">%1$s, %2$s, %3$s, %4$s</string>
|
|
||||||
<string name="prep_failed">Could not calculate continuations</string>
|
|
||||||
<string name="prep_no_memory">Not enough memory to search this database</string>
|
|
||||||
<string name="prep_calculating">Calculating continuations…</string>
|
|
||||||
<string name="prep_position_absent">This position does not occur in games by %1$s</string>
|
|
||||||
<string name="prep_position_absent_hint">You can continue on the board or go back</string>
|
|
||||||
<string name="prep_all_ended">All games ended here</string>
|
|
||||||
<string name="prep_ended_here">Ended here: %1$s</string>
|
|
||||||
<string name="prep_no_normal">No normal continuation: %1$s</string>
|
|
||||||
<string name="to_game">Back to game</string>
|
|
||||||
<string name="to_players">Back to players</string>
|
|
||||||
<string name="prep_choose_move">Choose a move</string>
|
|
||||||
<plurals name="prep_wins">
|
|
||||||
<item quantity="one">%1$s win</item>
|
|
||||||
<item quantity="other">%1$s wins</item>
|
|
||||||
</plurals>
|
|
||||||
<plurals name="prep_draws">
|
|
||||||
<item quantity="one">%1$s draw</item>
|
|
||||||
<item quantity="other">%1$s draws</item>
|
|
||||||
</plurals>
|
|
||||||
<plurals name="prep_losses">
|
|
||||||
<item quantity="one">%1$s loss</item>
|
|
||||||
<item quantity="other">%1$s losses</item>
|
|
||||||
</plurals>
|
|
||||||
<string name="prep_unknown_accessibility">Unknown results: %1$d; excluded from the percentages.</string>
|
|
||||||
<string name="prep_continuation_description">%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.</string>
|
|
||||||
<string name="prep_play">Play</string>
|
|
||||||
<string name="prep_unknown_short">more %1$s</string>
|
|
||||||
<string name="prep_wdl_counts">+%1$s =%2$s −%3$s · W/D/L %4$s/%5$s/%6$s %%</string>
|
|
||||||
</resources>
|
</resources>
|
||||||
|
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
<?xml version="1.0" encoding="utf-8"?>
|
|
||||||
<!-- The RuStore build (build.gradle.kts, buildType "rustore"): the store installs and
|
|
||||||
updates the app, so it neither installs packages nor receives the installer's answer. -->
|
|
||||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
|
||||||
xmlns:tools="http://schemas.android.com/tools">
|
|
||||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" tools:node="remove" />
|
|
||||||
<uses-permission android:name="android.permission.UPDATE_PACKAGES_WITHOUT_USER_ACTION" tools:node="remove" />
|
|
||||||
<application>
|
|
||||||
<receiver android:name=".data.InstallResult" tools:node="remove" />
|
|
||||||
</application>
|
|
||||||
</manifest>
|
|
||||||
|
|
@ -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<UInt>())
|
|
||||||
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?>(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?>(Incoming.Opened(entry))
|
|
||||||
val expected = incoming.value
|
|
||||||
incoming.value = Incoming.Opening
|
|
||||||
|
|
||||||
assertFalse(incoming.compareAndSet(expected, null))
|
|
||||||
assertEquals(Incoming.Opening, incoming.value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -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<String>()
|
|
||||||
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<String>()
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
@ -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"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -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())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -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)
|
|
||||||
}
|
|
||||||
|
|
@ -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,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -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),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
@ -2,9 +2,6 @@
|
||||||
# Builds the two signed release APKs into androidApp/dist:
|
# Builds the two signed release APKs into androidApp/dist:
|
||||||
# ChessPenguin-<version>-android.apk Stockfish built in ("full")
|
# ChessPenguin-<version>-android.apk Stockfish built in ("full")
|
||||||
# ChessPenguin-<version>-android-noengine.apk Stockfish downloaded in the app ("light")
|
# ChessPenguin-<version>-android-noengine.apk Stockfish downloaded in the app ("light")
|
||||||
# and, apart (not a file of the release), into androidApp/dist-rustore:
|
|
||||||
# ChessPenguin-<version>-rustore.apk the full one for RuStore: no updates of its
|
|
||||||
# own, no check the site counts
|
|
||||||
# The key comes from the environment or from ~/.config/chesspenguin/android/.env.
|
# The key comes from the environment or from ~/.config/chesspenguin/android/.env.
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
|
|
@ -16,22 +13,15 @@ if [[ -z "${CP_KEYSTORE:-}" && -f "${env_file}" ]]; then
|
||||||
set +a
|
set +a
|
||||||
fi
|
fi
|
||||||
: "${CP_KEYSTORE:?no release key: set CP_KEYSTORE and the passwords, or CP_SIGNING_ENV}"
|
: "${CP_KEYSTORE:?no release key: set CP_KEYSTORE and the passwords, or CP_SIGNING_ENV}"
|
||||||
./gradlew --console=plain assembleFullRelease assembleLightRelease assembleFullRustore
|
./gradlew --console=plain assembleFullRelease assembleLightRelease
|
||||||
version="$(sed -n 's/^version = "\(.*\)"/\1/p' ../Cargo.toml | head -n1)"
|
version="$(sed -n 's/^version = "\(.*\)"/\1/p' ../Cargo.toml | head -n1)"
|
||||||
mkdir -p dist
|
mkdir -p dist
|
||||||
cp app/build/outputs/apk/full/release/app-full-release.apk "dist/ChessPenguin-${version}-android.apk"
|
cp app/build/outputs/apk/full/release/app-full-release.apk "dist/ChessPenguin-${version}-android.apk"
|
||||||
cp app/build/outputs/apk/light/release/app-light-release.apk "dist/ChessPenguin-${version}-android-noengine.apk"
|
cp app/build/outputs/apk/light/release/app-light-release.apk "dist/ChessPenguin-${version}-android-noengine.apk"
|
||||||
mkdir -p dist-rustore
|
|
||||||
cp app/build/outputs/apk/full/rustore/app-full-rustore.apk "dist-rustore/ChessPenguin-${version}-rustore.apk"
|
|
||||||
build_tools="$(ls -d "${ANDROID_HOME:-$HOME/Android/Sdk}"/build-tools/* | sort -V | tail -n1)"
|
build_tools="$(ls -d "${ANDROID_HOME:-$HOME/Android/Sdk}"/build-tools/* | sort -V | tail -n1)"
|
||||||
for apk in dist/ChessPenguin-"${version}"-android*.apk dist-rustore/ChessPenguin-"${version}"-rustore.apk; do
|
for apk in dist/ChessPenguin-"${version}"-android*.apk; do
|
||||||
"${build_tools}/apksigner" verify "${apk}"
|
"${build_tools}/apksigner" verify "${apk}"
|
||||||
"${build_tools}/zipalign" -c -P 16 4 "${apk}"
|
"${build_tools}/zipalign" -c -P 16 4 "${apk}"
|
||||||
done
|
done
|
||||||
(cd dist && sha256sum ChessPenguin-"${version}"-android*.apk > ChessPenguin-"${version}"-android.sha256)
|
(cd dist && sha256sum ChessPenguin-"${version}"-android*.apk > ChessPenguin-"${version}"-android.sha256)
|
||||||
# The store's build asks for nothing it would not need.
|
ls -l dist
|
||||||
if "${build_tools}/aapt2" dump permissions "dist-rustore/ChessPenguin-${version}-rustore.apk" | grep -q 'INSTALL_PACKAGES'; then
|
|
||||||
echo "the RuStore build may install packages" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
ls -l dist dist-rustore
|
|
||||||
|
|
|
||||||
|
|
@ -9,22 +9,10 @@ edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
license.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]
|
[dependencies]
|
||||||
chess-core.workspace = true
|
chess-core.workspace = true
|
||||||
chess-openings.workspace = true
|
|
||||||
maia.workspace = true
|
maia.workspace = true
|
||||||
game-review.workspace = true
|
game-review.workspace = true
|
||||||
prep.workspace = true
|
|
||||||
chess-import.workspace = true
|
chess-import.workspace = true
|
||||||
shakmaty.workspace = true
|
shakmaty.workspace = true
|
||||||
uci.workspace = true
|
uci.workspace = true
|
||||||
|
|
@ -32,16 +20,23 @@ egui.workspace = true
|
||||||
eframe.workspace = true
|
eframe.workspace = true
|
||||||
egui_extras.workspace = true
|
egui_extras.workspace = true
|
||||||
image.workspace = true
|
image.workspace = true
|
||||||
|
rfd.workspace = true
|
||||||
|
arboard.workspace = true
|
||||||
|
rodio.workspace = true
|
||||||
directories.workspace = true
|
directories.workspace = true
|
||||||
trainer.workspace = true
|
trainer.workspace = true
|
||||||
play.workspace = true
|
play.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
thiserror.workspace = true
|
|
||||||
online-games.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"
|
sha2 = "0.11"
|
||||||
zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs"] }
|
zip = { version = "9.0.5", default-features = false, features = ["deflate-flate2-zlib-rs"] }
|
||||||
|
|
||||||
# The system language for the first start.
|
# The system language for the first start.
|
||||||
sys-locale = "0.3"
|
sys-locale = "0.3"
|
||||||
whatlang = "0.18.0"
|
whatlang = "0.18.0"
|
||||||
|
|
@ -53,42 +48,6 @@ log = "0.4"
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
form_urlencoded = "1"
|
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]
|
[build-dependencies]
|
||||||
winresource = "0.1"
|
winresource = "0.1"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,96 +0,0 @@
|
||||||
-------------------------------
|
|
||||||
UBUNTU FONT LICENCE Version 1.0
|
|
||||||
-------------------------------
|
|
||||||
|
|
||||||
PREAMBLE
|
|
||||||
This licence allows the licensed fonts to be used, studied, modified and
|
|
||||||
redistributed freely. The fonts, including any derivative works, can be
|
|
||||||
bundled, embedded, and redistributed provided the terms of this licence
|
|
||||||
are met. The fonts and derivatives, however, cannot be released under
|
|
||||||
any other licence. The requirement for fonts to remain under this
|
|
||||||
licence does not require any document created using the fonts or their
|
|
||||||
derivatives to be published under this licence, as long as the primary
|
|
||||||
purpose of the document is not to be a vehicle for the distribution of
|
|
||||||
the fonts.
|
|
||||||
|
|
||||||
DEFINITIONS
|
|
||||||
"Font Software" refers to the set of files released by the Copyright
|
|
||||||
Holder(s) under this licence and clearly marked as such. This may
|
|
||||||
include source files, build scripts and documentation.
|
|
||||||
|
|
||||||
"Original Version" refers to the collection of Font Software components
|
|
||||||
as received under this licence.
|
|
||||||
|
|
||||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
|
||||||
or substituting -- in part or in whole -- any of the components of the
|
|
||||||
Original Version, by changing formats or by porting the Font Software to
|
|
||||||
a new environment.
|
|
||||||
|
|
||||||
"Copyright Holder(s)" refers to all individuals and companies who have a
|
|
||||||
copyright ownership of the Font Software.
|
|
||||||
|
|
||||||
"Substantially Changed" refers to Modified Versions which can be easily
|
|
||||||
identified as dissimilar to the Font Software by users of the Font
|
|
||||||
Software comparing the Original Version with the Modified Version.
|
|
||||||
|
|
||||||
To "Propagate" a work means to do anything with it that, without
|
|
||||||
permission, would make you directly or secondarily liable for
|
|
||||||
infringement under applicable copyright law, except executing it on a
|
|
||||||
computer or modifying a private copy. Propagation includes copying,
|
|
||||||
distribution (with or without modification and with or without charging
|
|
||||||
a redistribution fee), making available to the public, and in some
|
|
||||||
countries other activities as well.
|
|
||||||
|
|
||||||
PERMISSION & CONDITIONS
|
|
||||||
This licence does not grant any rights under trademark law and all such
|
|
||||||
rights are reserved.
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a
|
|
||||||
copy of the Font Software, to propagate the Font Software, subject to
|
|
||||||
the below conditions:
|
|
||||||
|
|
||||||
1) Each copy of the Font Software must contain the above copyright
|
|
||||||
notice and this licence. These can be included either as stand-alone
|
|
||||||
text files, human-readable headers or in the appropriate machine-
|
|
||||||
readable metadata fields within text or binary files as long as those
|
|
||||||
fields can be easily viewed by the user.
|
|
||||||
|
|
||||||
2) The font name complies with the following:
|
|
||||||
(a) The Original Version must retain its name, unmodified.
|
|
||||||
(b) Modified Versions which are Substantially Changed must be renamed to
|
|
||||||
avoid use of the name of the Original Version or similar names entirely.
|
|
||||||
(c) Modified Versions which are not Substantially Changed must be
|
|
||||||
renamed to both (i) retain the name of the Original Version and (ii) add
|
|
||||||
additional naming elements to distinguish the Modified Version from the
|
|
||||||
Original Version. The name of such Modified Versions must be the name of
|
|
||||||
the Original Version, with "derivative X" where X represents the name of
|
|
||||||
the new work, appended to that name.
|
|
||||||
|
|
||||||
3) The name(s) of the Copyright Holder(s) and any contributor to the
|
|
||||||
Font Software shall not be used to promote, endorse or advertise any
|
|
||||||
Modified Version, except (i) as required by this licence, (ii) to
|
|
||||||
acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
|
|
||||||
their explicit written permission.
|
|
||||||
|
|
||||||
4) The Font Software, modified or unmodified, in part or in whole, must
|
|
||||||
be distributed entirely under this licence, and must not be distributed
|
|
||||||
under any other licence. The requirement for fonts to remain under this
|
|
||||||
licence does not affect any document created using the Font Software,
|
|
||||||
except any version of the Font Software extracted from a document
|
|
||||||
created using the Font Software may only be distributed under this
|
|
||||||
licence.
|
|
||||||
|
|
||||||
TERMINATION
|
|
||||||
This licence becomes null and void if any of the above conditions are
|
|
||||||
not met.
|
|
||||||
|
|
||||||
DISCLAIMER
|
|
||||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
|
|
||||||
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
|
||||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
||||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
|
||||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
||||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
|
|
||||||
DEALINGS IN THE FONT SOFTWARE.
|
|
||||||
Binary file not shown.
|
|
@ -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.} *
|
|
||||||
|
|
@ -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.} *
|
|
||||||
|
|
@ -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.} *
|
|
||||||
|
|
@ -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 {Английская атака: обе стороны наступают на противоположных флангах.} *
|
|
||||||
|
|
@ -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.} *
|
|
||||||
|
|
@ -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.} *
|
|
||||||
|
|
@ -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.} *
|
|
||||||
|
|
@ -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 {Чёрные атакуют центр и готовы рокироваться.} *
|
|
||||||
|
|
@ -1,12 +1,5 @@
|
||||||
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.
|
// Embeds the application icon into the Windows executable.
|
||||||
|
fn main() {
|
||||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
|
||||||
let mut res = winresource::WindowsResource::new();
|
let mut res = winresource::WindowsResource::new();
|
||||||
res.set_icon("../../packaging/windows/chesspenguin.ico");
|
res.set_icon("../../packaging/windows/chesspenguin.ico");
|
||||||
|
|
|
||||||
|
|
@ -124,7 +124,6 @@ impl Card {
|
||||||
circles: &[],
|
circles: &[],
|
||||||
badge: None,
|
badge: None,
|
||||||
interactive: false,
|
interactive: false,
|
||||||
temporary_shapes: false,
|
|
||||||
show_coords: false,
|
show_coords: false,
|
||||||
theme: settings.board_theme.theme(),
|
theme: settings.board_theme.theme(),
|
||||||
pieces: settings.piece_set,
|
pieces: settings.piece_set,
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
//! Engine analysis controller: owns the engine (a UCI process; in a browser a Web
|
//! Engine analysis controller: owns the UCI process, binds results to the analysed position.
|
||||||
//! Worker), binds results to the analysed position.
|
|
||||||
|
|
||||||
use crate::i18n::{tr, trf};
|
use crate::i18n::{tr, trf};
|
||||||
|
use std::sync::mpsc::{Receiver, channel};
|
||||||
|
|
||||||
use shakmaty::san::SanPlus;
|
use shakmaty::san::SanPlus;
|
||||||
use shakmaty::uci::UciMove;
|
use shakmaty::uci::UciMove;
|
||||||
|
|
@ -38,39 +38,9 @@ struct Target {
|
||||||
engine_pos: EnginePosition,
|
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<Result<EngineHandle, uci::EngineError>>),
|
|
||||||
/// 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<Result<EngineHandle, uci::EngineError>> {
|
|
||||||
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 {
|
pub struct Analysis {
|
||||||
engine: Option<EngineHandle>,
|
engine: Option<EngineHandle>,
|
||||||
spawning: Option<Launch>,
|
spawning: Option<Receiver<Result<EngineHandle, uci::EngineError>>>,
|
||||||
pub status: Status,
|
pub status: Status,
|
||||||
pub engine_name: String,
|
pub engine_name: String,
|
||||||
next_id: u64,
|
next_id: u64,
|
||||||
|
|
@ -86,14 +56,7 @@ pub struct Analysis {
|
||||||
/// The current search ended (time limit reached); lines stay as the final result.
|
/// The current search ended (time limit reached); lines stay as the final result.
|
||||||
pub finished: bool,
|
pub finished: bool,
|
||||||
/// Executable of the running engine (to detect a switch of the active engine).
|
/// Executable of the running engine (to detect a switch of the active engine).
|
||||||
pub engine_path: Option<crate::engines::EngineLocation>,
|
pub engine_path: Option<std::path::PathBuf>,
|
||||||
}
|
|
||||||
|
|
||||||
impl Analysis {
|
|
||||||
/// Lines the engine is asked for (the panel keeps their room while they come).
|
|
||||||
pub fn line_count(&self) -> usize {
|
|
||||||
self.multipv.max(1) as usize
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Analysis {
|
impl Analysis {
|
||||||
|
|
@ -120,7 +83,7 @@ impl Analysis {
|
||||||
matches!(self.status, Status::Starting | Status::Running)
|
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) {
|
pub fn start(&mut self, cfg: &EngineConfig, ctx: &egui::Context) {
|
||||||
self.stop();
|
self.stop();
|
||||||
let Some(path) = cfg.executable() else {
|
let Some(path) = cfg.executable() else {
|
||||||
|
|
@ -128,32 +91,48 @@ impl Analysis {
|
||||||
Status::Failed(tr("The built-in engine is not part of this build").into());
|
Status::Failed(tr("The built-in engine is not part of this build").into());
|
||||||
return;
|
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.engine_name = cfg.name.clone();
|
||||||
self.multipv = cfg.multipv.max(1);
|
self.multipv = cfg.multipv.max(1);
|
||||||
self.limit = cfg.search_secs;
|
self.limit = cfg.search_secs;
|
||||||
self.engine_path = Some(path.clone());
|
self.engine_path = Some(path.clone());
|
||||||
match launch(path, cfg.clone(), ctx) {
|
let spawned = std::thread::Builder::new()
|
||||||
Ok(l) => {
|
.name("engine-spawn".into())
|
||||||
self.spawning = Some(l);
|
.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;
|
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) {
|
pub fn stop(&mut self) {
|
||||||
if let Some(e) = self.engine.take() {
|
if let Some(e) = self.engine.take() {
|
||||||
// quit() may wait up to the quit timeout; do it off the UI thread. A worker
|
// quit() may wait up to the quit timeout; do it off the UI thread.
|
||||||
// stops at once.
|
|
||||||
#[cfg(not(web))]
|
|
||||||
let _ = std::thread::Builder::new()
|
let _ = std::thread::Builder::new()
|
||||||
.name("engine-quit".into())
|
.name("engine-quit".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
e.quit();
|
e.quit();
|
||||||
});
|
});
|
||||||
#[cfg(web)]
|
|
||||||
e.quit();
|
|
||||||
}
|
}
|
||||||
self.spawning = None;
|
self.spawning = None;
|
||||||
self.current = None;
|
self.current = None;
|
||||||
|
|
@ -226,7 +205,9 @@ impl Analysis {
|
||||||
|
|
||||||
/// Drains engine events; call once per frame.
|
/// Drains engine events; call once per frame.
|
||||||
pub fn poll(&mut self) {
|
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;
|
self.spawning = None;
|
||||||
match res {
|
match res {
|
||||||
Ok(h) => {
|
Ok(h) => {
|
||||||
|
|
@ -293,49 +274,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<Launch, String> {
|
|
||||||
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<Launch, String> {
|
|
||||||
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 {
|
impl Drop for Analysis {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.stop();
|
self.stop();
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -131,11 +131,6 @@ impl PieceSet {
|
||||||
format!("bytes://pieces/{}/{}.svg", self.name(), Self::index(piece))
|
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) {
|
pub fn paint(self, ui: &egui::Ui, piece: Piece, rect: Rect) {
|
||||||
egui::Image::new(self.uri(piece)).paint_at(ui, rect);
|
egui::Image::new(self.uri(piece)).paint_at(ui, rect);
|
||||||
}
|
}
|
||||||
|
|
@ -161,14 +156,6 @@ pub fn install(ctx: &egui::Context) {
|
||||||
ctx.set_fonts(font_definitions());
|
ctx.set_fonts(font_definitions());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The font family of the bold face.
|
|
||||||
pub const BOLD: &str = "ubuntu-bold";
|
|
||||||
|
|
||||||
/// A font of the bold face (the moves of the notation, the marks on the board).
|
|
||||||
pub fn bold(size: f32) -> egui::FontId {
|
|
||||||
egui::FontId::new(size, egui::FontFamily::Name(BOLD.into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// egui's fonts with ours added: figurines for the move notation, then the fallbacks.
|
/// egui's fonts with ours added: figurines for the move notation, then the fallbacks.
|
||||||
pub fn font_definitions() -> egui::FontDefinitions {
|
pub fn font_definitions() -> egui::FontDefinitions {
|
||||||
// Arrows (→ ⇄ ↔) are only in egui's monospace font, and three evaluation signs
|
// Arrows (→ ⇄ ↔) are only in egui's monospace font, and three evaluation signs
|
||||||
|
|
@ -194,30 +181,7 @@ pub fn font_definitions() -> egui::FontDefinitions {
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
// The bold face of the same family (egui's text is Ubuntu Light): the moves of the
|
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
|
||||||
// notation and the marks on the board.
|
|
||||||
fonts.font_data.insert(
|
|
||||||
BOLD.into(),
|
|
||||||
std::sync::Arc::new(egui::FontData::from_static(include_bytes!(
|
|
||||||
"../assets/fonts/Ubuntu-B.ttf"
|
|
||||||
))),
|
|
||||||
);
|
|
||||||
let mut bold = vec![BOLD.to_string()];
|
|
||||||
bold.extend(
|
|
||||||
fonts
|
|
||||||
.families
|
|
||||||
.get(&egui::FontFamily::Proportional)
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or_default(),
|
|
||||||
);
|
|
||||||
fonts
|
|
||||||
.families
|
|
||||||
.insert(egui::FontFamily::Name(BOLD.into()), bold);
|
|
||||||
for family in [
|
|
||||||
egui::FontFamily::Proportional,
|
|
||||||
egui::FontFamily::Monospace,
|
|
||||||
egui::FontFamily::Name(BOLD.into()),
|
|
||||||
] {
|
|
||||||
if let Some(list) = fonts.families.get_mut(&family) {
|
if let Some(list) = fonts.families.get_mut(&family) {
|
||||||
list.insert(1, "figurine".into());
|
list.insert(1, "figurine".into());
|
||||||
}
|
}
|
||||||
|
|
@ -227,11 +191,7 @@ pub fn font_definitions() -> egui::FontDefinitions {
|
||||||
.get(&egui::FontFamily::Monospace)
|
.get(&egui::FontFamily::Monospace)
|
||||||
.and_then(|f| f.first())
|
.and_then(|f| f.first())
|
||||||
.cloned();
|
.cloned();
|
||||||
for family in [
|
for family in [egui::FontFamily::Proportional, egui::FontFamily::Monospace] {
|
||||||
egui::FontFamily::Proportional,
|
|
||||||
egui::FontFamily::Monospace,
|
|
||||||
egui::FontFamily::Name(BOLD.into()),
|
|
||||||
] {
|
|
||||||
if let Some(list) = fonts.families.get_mut(&family) {
|
if let Some(list) = fonts.families.get_mut(&family) {
|
||||||
if let Some(m) = &mono
|
if let Some(m) = &mono
|
||||||
&& !list.contains(m)
|
&& !list.contains(m)
|
||||||
|
|
|
||||||
|
|
@ -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<u64>,
|
|
||||||
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<u32> {
|
|
||||||
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<usize> {
|
|
||||||
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<String> {
|
|
||||||
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<u32>,
|
|
||||||
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<usize>,
|
|
||||||
/// Record numbers (from 0) that could not be read.
|
|
||||||
pub unreadable: Vec<usize>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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`: `.<name>.part-<pid>-<random>`, 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 (`.<name>.pgn.part-<pid>-<hex>`) and only when
|
|
||||||
/// no process `<pid>` 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<u32> {
|
|
||||||
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::<Vec<_>>().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<Result<CopyReport, CopyError>> {
|
|
||||||
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<Option<CopyReport>, 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<u128, u32> = HashMap::new();
|
|
||||||
let mut more: Vec<u32> = 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<String> = 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;
|
|
||||||
|
|
@ -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<PathBuf> {
|
|
||||||
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<Result<CopyReport, CopyError>> {
|
|
||||||
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<String> = 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<String> = (0..3)
|
|
||||||
.map(|i| {
|
|
||||||
open(&target)
|
|
||||||
.load_game(i)
|
|
||||||
.unwrap()
|
|
||||||
.game
|
|
||||||
.tag("White")
|
|
||||||
.unwrap()
|
|
||||||
.to_owned()
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let wanted: Vec<String> = 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<u8> {
|
|
||||||
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<u32> = (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<u32> = (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=<file>` and `CP_PROBE_N=<records>` (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<u32> = (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
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -32,9 +32,6 @@ pub enum Drawn {
|
||||||
Circle(chess_core::ShapeColor, Square),
|
Circle(chess_core::ShapeColor, Square),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) type TestAnimation<'a> = (f64, &'a [(Piece, Square, Square)], f32);
|
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct BoardState {
|
pub struct BoardState {
|
||||||
selected: Option<Square>,
|
selected: Option<Square>,
|
||||||
|
|
@ -44,9 +41,6 @@ pub struct BoardState {
|
||||||
shape_from: Option<Square>,
|
shape_from: Option<Square>,
|
||||||
/// A shape drawn this frame, for the game to take (`take_shape`).
|
/// A shape drawn this frame, for the game to take (`take_shape`).
|
||||||
shape: Option<Drawn>,
|
shape: Option<Drawn>,
|
||||||
/// Temporary shapes in play and training; never written to the PGN.
|
|
||||||
temporary_shapes: Vec<Drawn>,
|
|
||||||
temporary_position: Option<Chess>,
|
|
||||||
/// The position drawn last: a different one next frame is animated from it.
|
/// The position drawn last: a different one next frame is animated from it.
|
||||||
shown: Option<Board>,
|
shown: Option<Board>,
|
||||||
anim: Option<Anim>,
|
anim: Option<Anim>,
|
||||||
|
|
@ -95,42 +89,10 @@ impl BoardState {
|
||||||
self.shape.take()
|
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.
|
/// A piece is selected or dragged, or a promotion is being chosen.
|
||||||
pub fn is_busy(&self) -> bool {
|
pub fn is_busy(&self) -> bool {
|
||||||
self.selected.is_some() || self.drag.is_some() || self.promotion.is_some()
|
self.selected.is_some() || self.drag.is_some() || self.promotion.is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) fn animation_at(&self, now: f64) -> Option<TestAnimation<'_>> {
|
|
||||||
let anim = self.anim.as_ref()?;
|
|
||||||
Some((anim.duration, &anim.slides, anim.rest(now)?))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pieces moving from one position to the next, as on Lichess (chessground): each piece
|
/// 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, …).
|
/// Move assessment shown on the destination square of the last move ("??" in red, …).
|
||||||
pub badge: Option<Badge>,
|
pub badge: Option<Badge>,
|
||||||
pub interactive: bool,
|
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 show_coords: bool,
|
||||||
pub theme: BoardTheme,
|
pub theme: BoardTheme,
|
||||||
pub pieces: PieceSet,
|
pub pieces: PieceSet,
|
||||||
|
|
@ -247,11 +207,6 @@ impl BoardView<'_> {
|
||||||
state.selected = None;
|
state.selected = None;
|
||||||
state.drag = None;
|
state.drag = None;
|
||||||
}
|
}
|
||||||
if self.temporary_shapes {
|
|
||||||
state.sync_temporary_position(self.pos);
|
|
||||||
} else {
|
|
||||||
state.temporary_shapes.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- input -----------------------------------------------------------------------
|
// --- input -----------------------------------------------------------------------
|
||||||
if (self.interactive || premoving) && state.promotion.is_none() {
|
if (self.interactive || premoving) && state.promotion.is_none() {
|
||||||
|
|
@ -310,11 +265,10 @@ impl BoardView<'_> {
|
||||||
.and_then(|p| geo.square_at(p));
|
.and_then(|p| geo.square_at(p));
|
||||||
let color = shape_color_for(ui.input(|i| i.modifiers));
|
let color = shape_color_for(ui.input(|i| i.modifiers));
|
||||||
if let Some(from) = state.shape_from.take() {
|
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),
|
Some(to) if to != from => Drawn::Arrow(color, from, to),
|
||||||
_ => Drawn::Circle(color, from),
|
_ => Drawn::Circle(color, from),
|
||||||
};
|
});
|
||||||
self.record_shape(state, drawn);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if response.secondary_clicked() {
|
if response.secondary_clicked() {
|
||||||
|
|
@ -322,27 +276,14 @@ impl BoardView<'_> {
|
||||||
state.premove = None;
|
state.premove = None;
|
||||||
if let Some(sq) = pointer.and_then(|p| geo.square_at(p)) {
|
if let Some(sq) = pointer.and_then(|p| geo.square_at(p)) {
|
||||||
let color = shape_color_for(ui.input(|i| i.modifiers));
|
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 ---------------------------------------------------------------------
|
// --- animation ---------------------------------------------------------------------
|
||||||
let now = ui.input(|i| i.time);
|
let now = ui.input(|i| i.time);
|
||||||
let board = painted_position.board();
|
let board = self.pos.board();
|
||||||
if state.shown.as_ref() != Some(board) {
|
if state.shown.as_ref() != Some(board) {
|
||||||
state.anim = None;
|
state.anim = None;
|
||||||
if let Some(prev) = &state.shown
|
if let Some(prev) = &state.shown
|
||||||
|
|
@ -399,8 +340,8 @@ impl BoardView<'_> {
|
||||||
hl(&painter, from, red);
|
hl(&painter, from, red);
|
||||||
hl(&painter, to, red);
|
hl(&painter, to, red);
|
||||||
}
|
}
|
||||||
if painted_position.is_check()
|
if self.pos.is_check()
|
||||||
&& let Some(k) = painted_position.board().king_of(painted_position.turn())
|
&& let Some(k) = self.pos.board().king_of(self.pos.turn())
|
||||||
{
|
{
|
||||||
let r = geo.square_rect(k);
|
let r = geo.square_rect(k);
|
||||||
painter.circle_filled(
|
painter.circle_filled(
|
||||||
|
|
@ -423,7 +364,7 @@ impl BoardView<'_> {
|
||||||
.paint_tinted(ui, piece, r, Color32::WHITE.gamma_multiply(rest));
|
.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() {
|
if state.drag == Some(sq) && response.dragged() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -476,31 +417,6 @@ impl BoardView<'_> {
|
||||||
for a in self.arrows {
|
for a in self.arrows {
|
||||||
draw_arrow(&painter, &geo, a);
|
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
|
if let Some(from) = state.shape_from
|
||||||
&& response.dragged_by(egui::PointerButton::Secondary)
|
&& response.dragged_by(egui::PointerButton::Secondary)
|
||||||
{
|
{
|
||||||
|
|
@ -553,7 +469,7 @@ impl BoardView<'_> {
|
||||||
c,
|
c,
|
||||||
egui::Align2::CENTER_CENTER,
|
egui::Align2::CENTER_CENTER,
|
||||||
b.text,
|
b.text,
|
||||||
crate::assets::bold(radius * 1.05),
|
egui::FontId::proportional(radius * 1.05),
|
||||||
Color32::WHITE,
|
Color32::WHITE,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -613,14 +529,6 @@ impl BoardView<'_> {
|
||||||
result
|
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.
|
/// The side that moves on this board now: the side to move, or the premoving one.
|
||||||
fn mover(&self) -> Color {
|
fn mover(&self) -> Color {
|
||||||
match self.premove {
|
match self.premove {
|
||||||
|
|
@ -1014,252 +922,4 @@ mod tests {
|
||||||
);
|
);
|
||||||
assert!(fadings.is_empty());
|
assert!(fadings.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn board_frame(
|
|
||||||
ctx: &egui::Context,
|
|
||||||
state: &mut BoardState,
|
|
||||||
pos: &Chess,
|
|
||||||
time: f64,
|
|
||||||
events: Vec<egui::Event>,
|
|
||||||
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<egui::Event> {
|
|
||||||
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::<Square>().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::<San>().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());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -519,7 +519,6 @@ impl SearchBoard {
|
||||||
circles: &[],
|
circles: &[],
|
||||||
badge: None,
|
badge: None,
|
||||||
interactive: true,
|
interactive: true,
|
||||||
temporary_shapes: false,
|
|
||||||
show_coords: settings.show_coords,
|
show_coords: settings.show_coords,
|
||||||
theme: settings.board_theme.theme(),
|
theme: settings.board_theme.theme(),
|
||||||
pieces: settings.piece_set,
|
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<T> {
|
pub struct Background<T> {
|
||||||
cancel: Arc<AtomicBool>,
|
cancel: Arc<AtomicBool>,
|
||||||
progress: Arc<AtomicUsize>,
|
progress: Arc<AtomicUsize>,
|
||||||
|
|
@ -903,7 +902,9 @@ impl<T: Send + 'static> Background<T> {
|
||||||
let progress = Arc::new(AtomicUsize::new(0));
|
let progress = Arc::new(AtomicUsize::new(0));
|
||||||
let (tx, rx) = channel();
|
let (tx, rx) = channel();
|
||||||
let (c, p, ctx) = (cancel.clone(), progress.clone(), ctx.clone());
|
let (c, p, ctx) = (cancel.clone(), progress.clone(), ctx.clone());
|
||||||
crate::platform::spawn("position-search", move || {
|
std::thread::Builder::new()
|
||||||
|
.name("position-search".into())
|
||||||
|
.spawn(move || {
|
||||||
let r = work(&p, &c);
|
let r = work(&p, &c);
|
||||||
let _ = tx.send(r);
|
let _ = tx.send(r);
|
||||||
ctx.request_repaint();
|
ctx.request_repaint();
|
||||||
|
|
@ -930,11 +931,6 @@ impl<T: Send + 'static> Background<T> {
|
||||||
pub fn cancel(&self) {
|
pub fn cancel(&self) {
|
||||||
self.cancel.store(true, Ordering::Relaxed);
|
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<Option<T>> {
|
|
||||||
self.rx.recv_timeout(timeout).ok()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Drop for Background<T> {
|
impl<T> Drop for Background<T> {
|
||||||
|
|
|
||||||
|
|
@ -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<u32>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub accuracy: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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<Found>,
|
|
||||||
/// Analysed with the engine settings of before (counted as analysed).
|
|
||||||
#[serde(default)]
|
|
||||||
pub stale: bool,
|
|
||||||
#[serde(default)]
|
|
||||||
pub skip: Option<Skip>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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<Entry> {
|
|
||||||
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<Skip> {
|
|
||||||
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<PathBuf>,
|
|
||||||
records: BTreeMap<u32, Entry>,
|
|
||||||
/// 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<PathBuf> {
|
|
||||||
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::<IndexFile>(&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<Item = u32> + '_ {
|
|
||||||
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<u32>,
|
|
||||||
/// 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<dyn Fn(&str) -> 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<game_review::Target>,
|
|
||||||
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<game_review::Target>,
|
|
||||||
_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<Index>,
|
|
||||||
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<u32>, Vec<u32>)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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<f64>,
|
|
||||||
pub accuracy: Option<f64>,
|
|
||||||
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<u32>,
|
|
||||||
/// 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::<f64>() / 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<SelectedGames>,
|
|
||||||
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<u32>,
|
|
||||||
pub selected: Option<SelectedGames>,
|
|
||||||
progress: std::sync::Arc<Progress>,
|
|
||||||
cancel: std::sync::Arc<AtomicBool>,
|
|
||||||
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<Database>,
|
|
||||||
records: Vec<u32>,
|
|
||||||
filter: chess_import::chessbase::base::Filter,
|
|
||||||
selected: Option<SelectedGames>,
|
|
||||||
index: std::sync::Arc<Mutex<Index>>,
|
|
||||||
cache: PathBuf,
|
|
||||||
engine: Engine,
|
|
||||||
) -> std::io::Result<PassJob> {
|
|
||||||
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<u32> {
|
|
||||||
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<Item = usize>, processes: usize) -> f64 {
|
|
||||||
plies
|
|
||||||
.map(|p| (p + 1) as f64 * SECS_PER_POSITION)
|
|
||||||
.sum::<f64>()
|
|
||||||
/ 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;
|
|
||||||
|
|
@ -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<Index>,
|
|
||||||
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::<serde_json::Value>(&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<u32> = 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::<Vec<_>>(),
|
|
||||||
[(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::<Vec<_>>(),
|
|
||||||
["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::<Vec<_>>()
|
|
||||||
.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::<Vec<_>>(),
|
|
||||||
[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}");
|
|
||||||
}
|
|
||||||
|
|
@ -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<u32>,
|
|
||||||
pub left: Vec<u32>,
|
|
||||||
pub plies_left: Vec<usize>,
|
|
||||||
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<Index>,
|
|
||||||
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<u32>,
|
|
||||||
pub filter: Filter,
|
|
||||||
pub about: String,
|
|
||||||
pub selected: Option<SelectedGames>,
|
|
||||||
rx: Receiver<Counted>,
|
|
||||||
cancel: Arc<AtomicBool>,
|
|
||||||
pub counted: Option<Counted>,
|
|
||||||
}
|
|
||||||
|
|
||||||
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<Database>,
|
|
||||||
records: Vec<u32>,
|
|
||||||
filter: Filter,
|
|
||||||
about: String,
|
|
||||||
selected: Option<SelectedGames>,
|
|
||||||
cache: PathBuf,
|
|
||||||
index: Arc<std::sync::Mutex<Index>>,
|
|
||||||
) -> 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<StartOutcome> {
|
|
||||||
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<SelectedGames>,
|
|
||||||
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<u32>,
|
|
||||||
pub skipped: Vec<(u32, Skip)>,
|
|
||||||
pub rows: Vec<BrilliantRow>,
|
|
||||||
pub selected: Option<usize>,
|
|
||||||
/// 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<u32>,
|
|
||||||
filter: Box<Filter>,
|
|
||||||
},
|
|
||||||
/// 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<SelectedGames>,
|
|
||||||
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<u32>| {
|
|
||||||
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<SummaryAction> {
|
|
||||||
let mut out = None;
|
|
||||||
// `CP_SUMMARY_CONTINUE=1`, `CP_SUMMARY_OPEN=<i>`: «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::<usize>().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<String> =
|
|
||||||
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<String>| 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<String> = 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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -12,8 +12,7 @@ use std::sync::Arc;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::mpsc::{Receiver, channel};
|
use std::sync::mpsc::{Receiver, channel};
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
use web_time::{Instant, SystemTime, UNIX_EPOCH};
|
|
||||||
|
|
||||||
use base64::Engine as _;
|
use base64::Engine as _;
|
||||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||||
|
|
@ -21,9 +20,7 @@ use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::translate::{Failure, update_credentials};
|
use crate::translate::{Failure, agent, update_credentials, with_waits};
|
||||||
#[cfg(not(web))]
|
|
||||||
use crate::translate::{agent, with_waits};
|
|
||||||
|
|
||||||
const AUTHORIZE: &str = "https://auth.openai.com/api/accounts/authorize";
|
const AUTHORIZE: &str = "https://auth.openai.com/api/accounts/authorize";
|
||||||
const TOKEN: &str = "https://auth.openai.com/api/accounts/oauth/token";
|
const TOKEN: &str = "https://auth.openai.com/api/accounts/oauth/token";
|
||||||
|
|
@ -151,13 +148,6 @@ pub struct SignIn {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl 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<SignIn, String> {
|
|
||||||
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.
|
/// 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<SignIn, String> {
|
pub fn start(ctx: &egui::Context, host_id: &str, client_id: &str) -> Result<SignIn, String> {
|
||||||
let listener = PORTS
|
let listener = PORTS
|
||||||
|
|
@ -227,7 +217,6 @@ impl Drop for SignIn {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// The page the browser tab shows after the sign-in.
|
/// The page the browser tab shows after the sign-in.
|
||||||
fn page(ok: bool) -> String {
|
fn page(ok: bool) -> String {
|
||||||
let (title, text) = if ok {
|
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) {
|
fn reply(stream: &mut TcpStream, status: &str, body: &str) {
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
stream,
|
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).
|
/// Waits for the browser to come back to the callback: (code, issued client id).
|
||||||
fn wait_for_callback(
|
fn wait_for_callback(
|
||||||
listener: &TcpListener,
|
listener: &TcpListener,
|
||||||
|
|
@ -323,7 +310,6 @@ fn wait_for_callback(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
fn token_request(body: &str) -> Result<Value, (u16, String)> {
|
fn token_request(body: &str) -> Result<Value, (u16, String)> {
|
||||||
let mut resp = agent(Duration::from_secs(30))
|
let mut resp = agent(Duration::from_secs(30))
|
||||||
.post(TOKEN)
|
.post(TOKEN)
|
||||||
|
|
@ -354,7 +340,6 @@ fn tokens_from(v: &Value, client_id: &str, old_refresh: &str) -> Tokens {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
fn exchange(
|
fn exchange(
|
||||||
code: &str,
|
code: &str,
|
||||||
verifier: &str,
|
verifier: &str,
|
||||||
|
|
@ -395,11 +380,9 @@ fn exchange(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// Refreshes are one at a time: the refresh token rotates.
|
/// Refreshes are one at a time: the refresh token rotates.
|
||||||
static REFRESH: Mutex<()> = Mutex::new(());
|
static REFRESH: Mutex<()> = Mutex::new(());
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// A valid access token, refreshed when it is about to expire.
|
/// A valid access token, refreshed when it is about to expire.
|
||||||
fn access_token() -> Result<String, Failure> {
|
fn access_token() -> Result<String, Failure> {
|
||||||
let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner());
|
let _one = REFRESH.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
|
@ -415,7 +398,6 @@ fn access_token() -> Result<String, Failure> {
|
||||||
refresh(&t)
|
refresh(&t)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
fn refresh(t: &Tokens) -> Result<String, Failure> {
|
fn refresh(t: &Tokens) -> Result<String, Failure> {
|
||||||
let body = form(&[
|
let body = form(&[
|
||||||
("grant_type", "refresh_token"),
|
("grant_type", "refresh_token"),
|
||||||
|
|
@ -477,15 +459,11 @@ pub fn sign_out() {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
update_credentials(|c| c.chatgpt = None);
|
update_credentials(|c| c.chatgpt = None);
|
||||||
#[cfg(not(web))]
|
|
||||||
let _ = std::thread::Builder::new()
|
let _ = std::thread::Builder::new()
|
||||||
.name("chatgpt-sign-out".into())
|
.name("chatgpt-sign-out".into())
|
||||||
.spawn(move || revoke(&t));
|
.spawn(move || revoke(&t));
|
||||||
#[cfg(web)]
|
|
||||||
let _ = t;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
fn revoke(t: &Tokens) -> bool {
|
fn revoke(t: &Tokens) -> bool {
|
||||||
let body = form(&[
|
let body = form(&[
|
||||||
("token", &t.refresh),
|
("token", &t.refresh),
|
||||||
|
|
@ -511,22 +489,6 @@ fn revoke(t: &Tokens) -> bool {
|
||||||
|
|
||||||
// --- Requests ------------------------------------------------------------------------------
|
// --- Requests ------------------------------------------------------------------------------
|
||||||
|
|
||||||
#[cfg(web)]
|
|
||||||
pub fn models() -> Result<Vec<String>, Failure> {
|
|
||||||
Err(crate::translate::no_requests())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(web)]
|
|
||||||
pub fn respond(
|
|
||||||
_model: &str,
|
|
||||||
_system: &str,
|
|
||||||
_user: &str,
|
|
||||||
_cancel: &AtomicBool,
|
|
||||||
) -> Result<String, Failure> {
|
|
||||||
Err(crate::translate::no_requests())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// The models this account may use (`visibility: list`).
|
/// The models this account may use (`visibility: list`).
|
||||||
pub fn models() -> Result<Vec<String>, Failure> {
|
pub fn models() -> Result<Vec<String>, Failure> {
|
||||||
let token = access_token()?;
|
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.
|
/// One answer of the model, read from the event stream.
|
||||||
pub fn respond(
|
pub fn respond(
|
||||||
model: &str,
|
model: &str,
|
||||||
|
|
@ -640,16 +601,14 @@ pub fn respond(
|
||||||
user: &str,
|
user: &str,
|
||||||
cancel: &AtomicBool,
|
cancel: &AtomicBool,
|
||||||
) -> Result<String, Failure> {
|
) -> Result<String, Failure> {
|
||||||
let mut body = json!({
|
let body = json!({
|
||||||
"model": model,
|
"model": model,
|
||||||
"instructions": system,
|
"instructions": system,
|
||||||
"input": [{"role": "user", "content": [{"type": "input_text", "text": user}]}],
|
"input": [{"role": "user", "content": [{"type": "input_text", "text": user}]}],
|
||||||
"store": false,
|
"store": false,
|
||||||
"stream": true,
|
"stream": true,
|
||||||
// Translating needs no long thought: at the default effort the model thinks for
|
})
|
||||||
// most of a minute over each request before it writes a word.
|
.to_string();
|
||||||
"reasoning": {"effort": "low"},
|
|
||||||
});
|
|
||||||
let mut refreshed = false;
|
let mut refreshed = false;
|
||||||
with_waits(cancel, || {
|
with_waits(cancel, || {
|
||||||
loop {
|
loop {
|
||||||
|
|
@ -659,7 +618,7 @@ pub fn respond(
|
||||||
.header("Authorization", format!("Bearer {token}"))
|
.header("Authorization", format!("Bearer {token}"))
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Accept", "text/event-stream")
|
.header("Accept", "text/event-stream")
|
||||||
.send(&body.to_string())
|
.send(&body)
|
||||||
.map_err(|e| Failure::Offline(e.to_string()))?;
|
.map_err(|e| Failure::Offline(e.to_string()))?;
|
||||||
let status = resp.status().as_u16();
|
let status = resp.status().as_u16();
|
||||||
if status == 401 && !refreshed {
|
if status == 401 && !refreshed {
|
||||||
|
|
@ -677,16 +636,6 @@ pub fn respond(
|
||||||
if status != 200 {
|
if status != 200 {
|
||||||
let mut resp = resp;
|
let mut resp = resp;
|
||||||
let text = resp.body_mut().read_to_string().unwrap_or_default();
|
let text = resp.body_mut().read_to_string().unwrap_or_default();
|
||||||
// A model that does not think takes no effort: asked again without it.
|
|
||||||
if status == 400
|
|
||||||
&& text.contains("reasoning")
|
|
||||||
&& body
|
|
||||||
.as_object_mut()
|
|
||||||
.and_then(|b| b.remove("reasoning"))
|
|
||||||
.is_some()
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
return Err(failure(status, &text));
|
return Err(failure(status, &text));
|
||||||
}
|
}
|
||||||
return read_stream(BufReader::new(resp.into_body().into_reader()), cancel);
|
return read_stream(BufReader::new(resp.into_body().into_reader()), cancel);
|
||||||
|
|
@ -694,7 +643,6 @@ pub fn respond(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// The text of a Responses event stream: the deltas until `response.completed`.
|
/// The text of a Responses event stream: the deltas until `response.completed`.
|
||||||
fn read_stream(reader: impl BufRead, cancel: &AtomicBool) -> Result<String, Failure> {
|
fn read_stream(reader: impl BufRead, cancel: &AtomicBool) -> Result<String, Failure> {
|
||||||
let mut text = String::new();
|
let mut text = String::new();
|
||||||
|
|
|
||||||
|
|
@ -1,294 +0,0 @@
|
||||||
//! 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.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
|
||||||
use std::sync::{Arc, Mutex};
|
|
||||||
|
|
||||||
use chess_import::Database;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// What a card says of a database: its games and whether it is a ChessBase one read in
|
|
||||||
/// place (a lock: it cannot take games).
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
|
||||||
pub struct Count {
|
|
||||||
pub games: usize,
|
|
||||||
pub locked: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Count {
|
|
||||||
pub fn of(db: &Database) -> Count {
|
|
||||||
match db.as_chessbase() {
|
|
||||||
Some(b) => Count {
|
|
||||||
games: b.games() + b.texts(),
|
|
||||||
locked: true,
|
|
||||||
},
|
|
||||||
None => Count {
|
|
||||||
games: db.len(),
|
|
||||||
locked: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A count and the file it was taken from.
|
|
||||||
#[derive(Clone, Copy, Serialize, Deserialize)]
|
|
||||||
struct Entry {
|
|
||||||
size: u64,
|
|
||||||
modified: u64,
|
|
||||||
count: Count,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum Job {
|
|
||||||
/// Count the file, unless the count remembered is of the file as it is.
|
|
||||||
Count(PathBuf),
|
|
||||||
/// The database was opened: its count, nothing to read.
|
|
||||||
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<Mutex<HashMap<PathBuf, Entry>>>,
|
|
||||||
/// `None`: for this run only.
|
|
||||||
file: Option<PathBuf>,
|
|
||||||
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<ToCount> {
|
|
||||||
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<Job>) -> 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<Job>) -> 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<Job>,
|
|
||||||
busy: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(web)]
|
|
||||||
thread_local! {
|
|
||||||
static WEB: std::cell::RefCell<Option<Web>> = const { std::cell::RefCell::new(None) };
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Counts {
|
|
||||||
known: Arc<Mutex<HashMap<PathBuf, Entry>>>,
|
|
||||||
asked: HashSet<PathBuf>,
|
|
||||||
jobs: Option<Sender<Job>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Counts {
|
|
||||||
pub fn new(ctx: &egui::Context) -> Self {
|
|
||||||
let file = crate::settings::Settings::cache_dir().map(|d| d.join("database-counts.json"));
|
|
||||||
Self::kept_in(file, ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Counts remembered in `file` (`None`: for this run only).
|
|
||||||
fn kept_in(file: Option<PathBuf>, ctx: &egui::Context) -> Self {
|
|
||||||
let known: HashMap<PathBuf, Entry> = file
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|f| crate::platform::fs::read(f).ok())
|
|
||||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
|
||||||
.unwrap_or_default();
|
|
||||||
let known = Arc::new(Mutex::new(known));
|
|
||||||
let (tx, rx) = channel::<Job>();
|
|
||||||
let counter = Counter {
|
|
||||||
known: known.clone(),
|
|
||||||
file,
|
|
||||||
ctx: ctx.clone(),
|
|
||||||
};
|
|
||||||
Self {
|
|
||||||
known,
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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<Count> {
|
|
||||||
if self.asked.insert(path.to_owned()) {
|
|
||||||
self.send(Job::Count(path.to_owned()));
|
|
||||||
}
|
|
||||||
self.known.lock().ok()?.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)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use std::time::Duration;
|
|
||||||
use web_time::Instant;
|
|
||||||
|
|
||||||
fn wait(counts: &mut Counts, path: &Path, want: usize) -> bool {
|
|
||||||
let deadline = Instant::now() + Duration::from_secs(5);
|
|
||||||
while Instant::now() < deadline {
|
|
||||||
if counts.get(path).map(|c| c.games) == Some(want) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
std::thread::sleep(Duration::from_millis(20));
|
|
||||||
}
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_database_is_counted_away_from_the_screen_and_again_when_it_changes() {
|
|
||||||
let dir = std::env::temp_dir().join(format!("cp-db-counts-{}", std::process::id()));
|
|
||||||
std::fs::create_dir_all(&dir).unwrap();
|
|
||||||
let pgn = dir.join("a.pgn");
|
|
||||||
std::fs::write(
|
|
||||||
&pgn,
|
|
||||||
"[White \"A\"]\n\n1. e4 *\n\n[White \"B\"]\n\n1. d4 *\n",
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let mut counts = Counts::kept_in(None, &egui::Context::default());
|
|
||||||
// Asked: nothing known yet, nothing waited for.
|
|
||||||
assert_eq!(counts.get(&pgn), None);
|
|
||||||
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;
|
|
||||||
counts.opened(&pgn, &db);
|
|
||||||
assert!(wait(&mut counts, &pgn, 1));
|
|
||||||
assert!(!counts.get(&pgn).unwrap().locked);
|
|
||||||
let _ = std::fs::remove_dir_all(&dir);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -66,14 +66,11 @@ fn asset() -> Option<Asset> {
|
||||||
|
|
||||||
/// Whether a download is offered on this platform at all.
|
/// Whether a download is offered on this platform at all.
|
||||||
pub fn available() -> bool {
|
pub fn available() -> bool {
|
||||||
cfg!(web) || asset().is_some()
|
asset().is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Size of the download in megabytes (rounded), for the offer.
|
/// Size of the download in megabytes (rounded), for the offer.
|
||||||
pub fn size_mb() -> u64 {
|
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))
|
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.
|
/// The downloaded engine, if it is there.
|
||||||
pub fn installed() -> Option<crate::engines::EngineLocation> {
|
pub fn installed() -> Option<PathBuf> {
|
||||||
#[cfg(web)]
|
|
||||||
return crate::platform::web::engine::worker_script()
|
|
||||||
.map(crate::engines::EngineLocation::Worker);
|
|
||||||
#[cfg(not(web))]
|
|
||||||
{
|
|
||||||
let p = dir()?.join(EXE);
|
let p = dir()?.join(EXE);
|
||||||
p.is_file()
|
p.is_file().then_some(p)
|
||||||
.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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes the downloaded engine (frees its space).
|
/// Removes the downloaded engine (frees its space).
|
||||||
pub fn remove() -> std::io::Result<()> {
|
pub fn remove() -> std::io::Result<()> {
|
||||||
#[cfg(web)]
|
|
||||||
{
|
|
||||||
crate::platform::web::engine::remove();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
#[cfg(not(web))]
|
|
||||||
match dir() {
|
match dir() {
|
||||||
Some(d) if d.exists() => std::fs::remove_dir_all(d),
|
Some(d) if d.exists() => std::fs::remove_dir_all(d),
|
||||||
_ => Ok(()),
|
_ => Ok(()),
|
||||||
|
|
@ -178,54 +148,11 @@ pub struct Download {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Download {
|
impl Download {
|
||||||
#[cfg(not(web))]
|
|
||||||
pub fn start(ctx: &egui::Context) -> Download {
|
pub fn start(ctx: &egui::Context) -> Download {
|
||||||
let total = asset().map_or(0, |a| a.size);
|
let total = asset().map_or(0, |a| a.size);
|
||||||
Download::spawn(ctx, total, run)
|
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
|
/// Runs `job` (a download and what follows it) in a thread of its own; `total`: the
|
||||||
/// bytes expected, shown until the server says.
|
/// bytes expected, shown until the server says.
|
||||||
pub fn spawn(ctx: &egui::Context, total: u64, job: Job) -> Download {
|
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<PathBuf, Failure> {
|
fn run(report: &dyn Fn(Stage), cancel: &AtomicBool) -> Result<PathBuf, Failure> {
|
||||||
let asset = asset().ok_or(Failure::Unsupported)?;
|
let asset = asset().ok_or(Failure::Unsupported)?;
|
||||||
let dir = dir().ok_or_else(|| Failure::Disk("no data directory".into()))?;
|
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<PathBuf, Failure>
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// Downloads `url` into `to`, checking the size and the SHA-256 on the way. The file is
|
/// 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
|
/// 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
|
/// (macOS on Apple silicon kills an executable rewritten in place after it once ran: it
|
||||||
|
|
@ -325,7 +250,6 @@ pub fn fetch(
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
fn fetch_into(
|
fn fetch_into(
|
||||||
url: &str,
|
url: &str,
|
||||||
to: &Path,
|
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.
|
/// Takes the engine executable and its license files out of the archive.
|
||||||
#[cfg(not(web))]
|
|
||||||
fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result<PathBuf, Failure> {
|
fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result<PathBuf, Failure> {
|
||||||
let exe = dir.join(EXE);
|
let exe = dir.join(EXE);
|
||||||
let wanted = |name: &str| -> Option<PathBuf> {
|
let wanted = |name: &str| -> Option<PathBuf> {
|
||||||
|
|
@ -459,7 +382,6 @@ fn unpack(archive: &Path, dir: &Path, zip: bool) -> Result<PathBuf, Failure> {
|
||||||
Ok(exe)
|
Ok(exe)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(web))]
|
|
||||||
/// Starts the engine once and waits for its name: the binary runs on this computer.
|
/// Starts the engine once and waits for its name: the binary runs on this computer.
|
||||||
fn check_runs(exe: &Path) -> Result<(), Failure> {
|
fn check_runs(exe: &Path) -> Result<(), Failure> {
|
||||||
let mut cmd = std::process::Command::new(exe);
|
let mut cmd = std::process::Command::new(exe);
|
||||||
|
|
@ -533,10 +455,7 @@ mod tests {
|
||||||
.output()
|
.output()
|
||||||
.expect("runs");
|
.expect("runs");
|
||||||
assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish"));
|
assert!(String::from_utf8_lossy(&out.stdout).contains("Stockfish"));
|
||||||
assert_eq!(
|
assert_eq!(installed(), Some(exe));
|
||||||
installed(),
|
|
||||||
Some(crate::engines::EngineLocation::Program(exe))
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -18,25 +18,7 @@ pub const DOWNLOAD_INDICATOR: &str = "download_indicator";
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub enum Pending {
|
pub enum Pending {
|
||||||
LiveAnalysis,
|
LiveAnalysis,
|
||||||
/// The search for great moves in a database's list (task 27), waiting in the app.
|
GameAnalysis,
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the owner should do.
|
/// What the owner should do.
|
||||||
|
|
@ -46,7 +28,6 @@ pub enum OfferEvent {
|
||||||
/// Use the Stockfish found on this computer, then run `Pending`.
|
/// Use the Stockfish found on this computer, then run `Pending`.
|
||||||
UseSystem(PathBuf, Option<Pending>),
|
UseSystem(PathBuf, Option<Pending>),
|
||||||
/// Open the file dialog to choose an engine.
|
/// Open the file dialog to choose an engine.
|
||||||
#[cfg(not(web))]
|
|
||||||
ChooseFile,
|
ChooseFile,
|
||||||
Toast(String),
|
Toast(String),
|
||||||
}
|
}
|
||||||
|
|
@ -58,11 +39,6 @@ enum Mode {
|
||||||
System(PathBuf),
|
System(PathBuf),
|
||||||
/// The downloaded engine was deleted from the disk.
|
/// The downloaded engine was deleted from the disk.
|
||||||
Missing,
|
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 {
|
pub struct EngineOffer {
|
||||||
|
|
@ -91,16 +67,17 @@ impl EngineOffer {
|
||||||
|
|
||||||
/// Whether the active engine can be started.
|
/// Whether the active engine can be started.
|
||||||
pub fn engine_ready(settings: &Settings) -> bool {
|
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.
|
/// Opens the offer for an action that needs an engine.
|
||||||
pub fn ask(&mut self, pending: Pending, settings: &Settings) {
|
pub fn ask(&mut self, pending: Pending, settings: &Settings) {
|
||||||
self.pending = Some(pending);
|
self.pending = Some(pending);
|
||||||
self.failure = None;
|
self.failure = None;
|
||||||
self.mode = if pending != Pending::LiveAnalysis {
|
self.mode = if settings.active_engine().is_some_and(|e| e.builtin) {
|
||||||
Mode::Own
|
|
||||||
} else if settings.active_engine().is_some_and(|e| e.builtin) {
|
|
||||||
Mode::Missing
|
Mode::Missing
|
||||||
} else if settings.engines.is_empty()
|
} else if settings.engines.is_empty()
|
||||||
&& let Some(p) = crate::engines::system_stockfish()
|
&& let Some(p) = crate::engines::system_stockfish()
|
||||||
|
|
@ -112,15 +89,6 @@ impl EngineOffer {
|
||||||
self.open = true;
|
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).
|
/// Starts the download (from the offer or from the settings).
|
||||||
pub fn start(&mut self, ctx: &egui::Context) {
|
pub fn start(&mut self, ctx: &egui::Context) {
|
||||||
if self.download.as_ref().is_some_and(Download::running) {
|
if self.download.as_ref().is_some_and(Download::running) {
|
||||||
|
|
@ -155,18 +123,12 @@ impl EngineOffer {
|
||||||
events.push(OfferEvent::Installed(pending));
|
events.push(OfferEvent::Installed(pending));
|
||||||
events.push(OfferEvent::Toast(
|
events.push(OfferEvent::Toast(
|
||||||
match pending {
|
match pending {
|
||||||
Some(Pending::GameAnalysis { .. }) => {
|
Some(Pending::GameAnalysis) => {
|
||||||
tr("Stockfish installed — game analysis started")
|
tr("Stockfish installed — game analysis started")
|
||||||
}
|
}
|
||||||
Some(Pending::LiveAnalysis) => {
|
Some(Pending::LiveAnalysis) => {
|
||||||
tr("Stockfish installed — analysis is on")
|
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"),
|
None => tr("Stockfish installed"),
|
||||||
}
|
}
|
||||||
.to_string(),
|
.to_string(),
|
||||||
|
|
@ -240,32 +202,20 @@ impl EngineOffer {
|
||||||
|
|
||||||
fn offer_body(&mut self, ui: &mut Ui, events: &mut Vec<OfferEvent>) {
|
fn offer_body(&mut self, ui: &mut Ui, events: &mut Vec<OfferEvent>) {
|
||||||
let size = engine_download::size_mb();
|
let size = engine_download::size_mb();
|
||||||
let (title, text): (&str, String) = match &self.mode {
|
let (title, text) = match &self.mode {
|
||||||
Mode::Offer => (
|
Mode::Offer => (
|
||||||
tr("Analysis needs a chess engine"),
|
tr("Analysis needs a chess engine"),
|
||||||
tr(
|
tr(
|
||||||
"Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.",
|
"Download Stockfish, the strongest free chess engine? Analysis will start as soon as the download finishes.",
|
||||||
)
|
),
|
||||||
.into(),
|
|
||||||
),
|
),
|
||||||
Mode::System(_) => (
|
Mode::System(_) => (
|
||||||
tr("Analysis needs a chess engine"),
|
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 => (
|
Mode::Missing => (
|
||||||
tr("Stockfish not found"),
|
tr("Stockfish not found"),
|
||||||
tr("The Stockfish file is missing from the disk. Download it again?").into(),
|
tr("The Stockfish file is missing from the disk. Download it again?"),
|
||||||
),
|
|
||||||
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),
|
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
ui.heading(title);
|
ui.heading(title);
|
||||||
|
|
@ -280,19 +230,6 @@ impl EngineOffer {
|
||||||
))
|
))
|
||||||
.weak(),
|
.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 {
|
} else {
|
||||||
ui.label(
|
ui.label(
|
||||||
RichText::new(trf(
|
RichText::new(trf(
|
||||||
|
|
@ -341,10 +278,6 @@ 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| {
|
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||||
if ui.button(tr("Choose engine file…")).clicked() {
|
if ui.button(tr("Choose engine file…")).clicked() {
|
||||||
events.push(OfferEvent::ChooseFile);
|
events.push(OfferEvent::ChooseFile);
|
||||||
|
|
@ -352,7 +285,6 @@ impl EngineOffer {
|
||||||
self.pending = None;
|
self.pending = None;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -393,15 +325,9 @@ impl EngineOffer {
|
||||||
}
|
}
|
||||||
ui.add_space(4.0);
|
ui.add_space(4.0);
|
||||||
let after = match self.pending {
|
let after = match self.pending {
|
||||||
Some(Pending::GameAnalysis { .. }) => {
|
Some(Pending::GameAnalysis) => {
|
||||||
tr("Game analysis will start by itself when the download finishes.")
|
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."),
|
_ => tr("Analysis will start by itself when the download finishes."),
|
||||||
};
|
};
|
||||||
ui.label(RichText::new(after).weak());
|
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<OfferEvent>) {
|
fn failure_body(&mut self, ui: &mut Ui, f: &Failure, events: &mut Vec<OfferEvent>) {
|
||||||
ui.heading(tr("⚠ Stockfish wasn't downloaded"));
|
ui.heading(tr("⚠ Stockfish wasn't downloaded"));
|
||||||
ui.add_space(6.0);
|
ui.add_space(6.0);
|
||||||
|
|
@ -434,10 +358,7 @@ impl EngineOffer {
|
||||||
ui.label(RichText::new(d).small().weak());
|
ui.label(RichText::new(d).small().weak());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if matches!(f, Failure::Network(_))
|
if matches!(f, Failure::Network(_)) && cfg!(target_os = "linux") {
|
||||||
&& cfg!(target_os = "linux")
|
|
||||||
&& !matches!(self.mode, Mode::Own | Mode::OwnInstead(_))
|
|
||||||
{
|
|
||||||
ui.label(
|
ui.label(
|
||||||
RichText::new(tr(
|
RichText::new(tr(
|
||||||
"A stockfish package of your distribution is found by ChessPenguin too.",
|
"A stockfish package of your distribution is found by ChessPenguin too.",
|
||||||
|
|
@ -459,8 +380,6 @@ impl EngineOffer {
|
||||||
self.failure = None;
|
self.failure = None;
|
||||||
self.pending = 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| {
|
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||||
if ui.button(tr("Choose engine file…")).clicked() {
|
if ui.button(tr("Choose engine file…")).clicked() {
|
||||||
events.push(OfferEvent::ChooseFile);
|
events.push(OfferEvent::ChooseFile);
|
||||||
|
|
@ -469,7 +388,6 @@ impl EngineOffer {
|
||||||
self.pending = 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<Pending>) -> 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).
|
/// What to tell the user about a failure, and the technical details (collapsed).
|
||||||
fn failure_text(f: &Failure) -> (String, Option<String>) {
|
fn failure_text(f: &Failure) -> (String, Option<String>) {
|
||||||
match f {
|
match f {
|
||||||
|
|
@ -611,51 +468,3 @@ fn failure_text(f: &Failure) -> (String, Option<String>) {
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[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"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -27,53 +27,14 @@ pub fn bundled_stockfish() -> Option<PathBuf> {
|
||||||
candidates.into_iter().flatten().find(|p| is_executable(p))
|
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.
|
/// ChessPenguin's Stockfish: the bundled one, or else the downloaded one.
|
||||||
pub fn own_stockfish() -> Option<EngineLocation> {
|
pub fn own_stockfish() -> Option<PathBuf> {
|
||||||
#[cfg(not(web))]
|
bundled_stockfish().or_else(crate::engine_download::installed)
|
||||||
return bundled_stockfish()
|
|
||||||
.map(EngineLocation::Program)
|
|
||||||
.or_else(crate::engine_download::installed);
|
|
||||||
#[cfg(web)]
|
|
||||||
crate::engine_download::installed()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `stockfish` from `PATH` (for example, the distribution package). On macOS an app
|
/// `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
|
/// started from the Finder does not get the shell's `PATH`: Homebrew's directories are
|
||||||
/// looked at too.
|
/// looked at too.
|
||||||
#[cfg(not(web))]
|
|
||||||
pub fn system_stockfish() -> Option<PathBuf> {
|
pub fn system_stockfish() -> Option<PathBuf> {
|
||||||
let path = std::env::var_os("PATH").unwrap_or_default();
|
let path = std::env::var_os("PATH").unwrap_or_default();
|
||||||
let extra: &[&str] = if cfg!(target_os = "macos") {
|
let extra: &[&str] = if cfg!(target_os = "macos") {
|
||||||
|
|
@ -87,12 +48,6 @@ pub fn system_stockfish() -> Option<PathBuf> {
|
||||||
.find(|p| is_executable(p))
|
.find(|p| is_executable(p))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A browser has no programs of the system to find.
|
|
||||||
#[cfg(web)]
|
|
||||||
pub fn system_stockfish() -> Option<PathBuf> {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_executable(p: &Path) -> bool {
|
fn is_executable(p: &Path) -> bool {
|
||||||
let Ok(meta) = std::fs::metadata(p) else {
|
let Ok(meta) = std::fs::metadata(p) else {
|
||||||
return false;
|
return false;
|
||||||
|
|
|
||||||
|
|
@ -1,36 +1,29 @@
|
||||||
//! Sample databases of the program, so the library is not empty: classic games with
|
//! Sample databases for the first start, so the library is not empty: classic games
|
||||||
//! short introductions, and Alekhine's games (moves only). At the first start they are
|
//! with short introductions, and Alekhine's games (moves only). They are written once,
|
||||||
//! written, named in the interface language, to `<local data dir>/examples/` and put on
|
//! named in the interface language, to `<local data dir>/examples/` and put on the
|
||||||
//! the library shelf; a sample removed from the shelf does not come back.
|
//! 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.
|
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use crate::i18n::{all_languages, tr};
|
use crate::i18n::tr;
|
||||||
use crate::settings::Settings;
|
use crate::settings::Settings;
|
||||||
|
|
||||||
/// The samples: the English name (a key of the translations) and the text.
|
fn files() -> [(&'static str, &'static str); 2] {
|
||||||
const SAMPLES: [(&str, &str); 2] = [
|
[
|
||||||
(
|
(
|
||||||
"Classic games",
|
tr("Classic games"),
|
||||||
include_str!("../../../examples/classics.pgn"),
|
include_str!("../../../examples/classics.pgn"),
|
||||||
),
|
),
|
||||||
("Alekhine", include_str!("../../../examples/alekhine.pgn")),
|
(
|
||||||
];
|
tr("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 dir() -> Option<PathBuf> {
|
fn dir() -> Option<PathBuf> {
|
||||||
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
|
/// 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))
|
dir().is_some_and(|d| path.starts_with(d))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds the samples at the first start and brings their files up to this version;
|
/// Adds the samples once; `true` when the settings changed. A new library starts with
|
||||||
/// `true` when the settings changed. A new library starts with them (the classics
|
/// them (the classics open); an existing one gets them after its own databases.
|
||||||
/// open); an existing one gets them after its own databases.
|
pub fn first_run_setup(settings: &mut Settings) -> bool {
|
||||||
pub fn setup(settings: &mut Settings) -> bool {
|
if settings.examples_added {
|
||||||
match dir() {
|
return false;
|
||||||
Some(dir) => setup_in(&dir, settings),
|
|
||||||
None => !std::mem::replace(&mut settings.examples_added, true),
|
|
||||||
}
|
}
|
||||||
|
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() {
|
||||||
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 path = dir.join(format!("{name}.pgn"));
|
||||||
let kept = crate::platform::fs::exists(&path) || settings.databases.contains(&path);
|
if !path.exists()
|
||||||
if (kept || (first && path == named))
|
&& let Err(e) = std::fs::write(&path, text)
|
||||||
&& let Err(e) = bring_up_to_date(&path, text)
|
|
||||||
{
|
{
|
||||||
eprintln!("examples: cannot write {}: {e}", path.display());
|
eprintln!("examples: cannot write {}: {e}", path.display());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !settings.databases.contains(&path) {
|
||||||
|
settings.databases.push(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if first && crate::platform::fs::exists(&named) && !settings.databases.contains(&named) {
|
true
|
||||||
settings.databases.push(named);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn samples_are_valid_pgn() {
|
fn samples_are_valid_pgn() {
|
||||||
let dir = folder("valid");
|
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();
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
for (name, text) in SAMPLES {
|
|
||||||
let path = dir.join(format!("{name}.pgn"));
|
let path = dir.join(format!("{name}.pgn"));
|
||||||
std::fs::write(&path, text).unwrap();
|
std::fs::write(&path, text).unwrap();
|
||||||
let db = chess_core::PgnDatabase::open(
|
let db = chess_core::PgnDatabase::open(
|
||||||
|
|
@ -118,138 +88,7 @@ mod tests {
|
||||||
parsed.diagnostics
|
parsed.diagnostics
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
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<String> = 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);
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,7 @@
|
||||||
//! read only) without touching the disk in the frame: a network drive that has lost its
|
//! 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
|
//! 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
|
//! 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
|
//! what it last found. A file not looked at yet counts as there.
|
||||||
//! files are the page's, in memory: they are looked at when asked.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
@ -32,7 +31,6 @@ pub struct FileStates {
|
||||||
const EVERY: Duration = Duration::from_secs(3);
|
const EVERY: Duration = Duration::from_secs(3);
|
||||||
|
|
||||||
impl FileStates {
|
impl FileStates {
|
||||||
#[cfg(not(web))]
|
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let shared = Arc::new(Mutex::new(Shared::default()));
|
let shared = Arc::new(Mutex::new(Shared::default()));
|
||||||
let looked = shared.clone();
|
let looked = shared.clone();
|
||||||
|
|
@ -57,21 +55,7 @@ impl FileStates {
|
||||||
Self { shared }
|
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<State> {
|
|
||||||
Some(look(path))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The file as last found (`None`: not looked at yet); it is looked at from now on.
|
/// 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<State> {
|
pub fn get(&self, path: &Path) -> Option<State> {
|
||||||
let mut s = self.shared.lock().ok()?;
|
let mut s = self.shared.lock().ok()?;
|
||||||
if !s.asked.contains(path) {
|
if !s.asked.contains(path) {
|
||||||
|
|
@ -87,11 +71,11 @@ impl FileStates {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn look(path: &Path) -> State {
|
fn look(path: &Path) -> State {
|
||||||
match crate::platform::fs::meta(path) {
|
match std::fs::metadata(path) {
|
||||||
Ok(m) => State {
|
Ok(m) => State {
|
||||||
exists: true,
|
exists: true,
|
||||||
size: m.len,
|
size: m.len(),
|
||||||
readonly: m.readonly,
|
readonly: m.permissions().readonly(),
|
||||||
},
|
},
|
||||||
Err(_) => State {
|
Err(_) => State {
|
||||||
exists: false,
|
exists: false,
|
||||||
|
|
@ -116,8 +100,8 @@ mod tests {
|
||||||
// Not looked at yet: counted as there, nothing waited for.
|
// Not looked at yet: counted as there, nothing waited for.
|
||||||
assert!(states.get(&there).is_none());
|
assert!(states.get(&there).is_none());
|
||||||
assert!(states.exists(&gone));
|
assert!(states.exists(&gone));
|
||||||
let deadline = web_time::Instant::now() + Duration::from_secs(5);
|
let deadline = std::time::Instant::now() + Duration::from_secs(5);
|
||||||
while states.get(&gone).is_none() && web_time::Instant::now() < deadline {
|
while states.get(&gone).is_none() && std::time::Instant::now() < deadline {
|
||||||
std::thread::sleep(Duration::from_millis(20));
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
}
|
}
|
||||||
assert!(!states.exists(&gone));
|
assert!(!states.exists(&gone));
|
||||||
|
|
|
||||||
|
|
@ -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<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The game's web address from its tags (Link first, then Site), if it has one.
|
|
||||||
pub fn of(tag: impl Fn(&str) -> Option<String>) -> Option<GameLink> {
|
|
||||||
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<GameLink> {
|
|
||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -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
|
/// 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.
|
/// dropped frame each frame) is written once a minute with how many times it came.
|
||||||
struct LibraryLog {
|
struct LibraryLog {
|
||||||
last: std::sync::Mutex<Option<(String, web_time::Instant, u32)>>,
|
last: std::sync::Mutex<Option<(String, std::time::Instant, u32)>>,
|
||||||
/// `CP_LOG_FRAMES=1`: also how each frame reaches the screen (egui_wgpu's debug and
|
/// `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).
|
/// trace messages: a frame skipped as "occluded" is said only there).
|
||||||
frames: bool,
|
frames: bool,
|
||||||
|
|
@ -194,7 +194,7 @@ impl log::Log for LibraryLog {
|
||||||
}
|
}
|
||||||
eprintln!("{text}");
|
eprintln!("{text}");
|
||||||
log(&text);
|
log(&text);
|
||||||
*last = Some((text, web_time::Instant::now(), 0));
|
*last = Some((text, std::time::Instant::now(), 0));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush(&self) {}
|
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) {
|
if std::fs::metadata(&f).is_ok_and(|m| m.len() > 1 << 20) {
|
||||||
let _ = std::fs::remove_file(&f);
|
let _ = std::fs::remove_file(&f);
|
||||||
}
|
}
|
||||||
let now = web_time::SystemTime::now()
|
let now = std::time::SystemTime::now()
|
||||||
.duration_since(web_time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
.map_or(0, |d| d.as_secs());
|
.map_or(0, |d| d.as_secs());
|
||||||
if let Ok(mut file) = std::fs::OpenOptions::new()
|
if let Ok(mut file) = std::fs::OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -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<String>,
|
|
||||||
) -> 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<u8>) {
|
|
||||||
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 <database> [report.txt]]`.
|
|
||||||
#[cfg(not(web))]
|
|
||||||
pub fn run_native() -> eframe::Result {
|
|
||||||
// `chesspenguin --bench <database> [report.txt]`: timings instead of the window
|
|
||||||
// (`docs/dev/import.md`, "Замер на другой машине").
|
|
||||||
let args: Vec<std::ffi::OsString> = 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 <database> [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::<f32>().ok()?, height.parse::<f32>().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
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue